新应用程序在启动时崩溃,调试没有帮助

问题描述:

好吧我试着调试我的代码,使用DDMS,我无法赶上它的窍门。我认为这是因为我的程序在启动时崩溃。无论如何,我向一个朋友展示了这一点,他无法弄清楚我做错了什么。有人能指出为什么我的应用程序在启动时崩溃吗?新应用程序在启动时崩溃,调试没有帮助

感谢:

http://pastebin.com/ZXxHPzng

+0

Android不处理的编程问题,所以我SO迁移这这里。 –

+0

有什么样的错误信息?在您的链接中,我只能看到一个活动文件。你的清单是否正确设置? – Jlange

你是要创建在全球区域的UI元素的问题。如果您希望它成为全局对象,则可以在那里声明它们,但只有在设置了内容视图后才能实例化它们。例如:

private RadioButton rockRB; 
    private RadioButton paperRB; 
    private RadioButton scissorsRB; 
    private TextView result; 



    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     requestWindowFeature(Window.FEATURE_NO_TITLE); 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     // Content View Must be set before making UI Elements 
     rockRB = (RadioButton)findViewById(R.id.radioRock); 
     paperRB = (RadioButton)findViewById(R.id.radioPaper); 
     scissorsRB = (RadioButton)findViewById(R.id.radioScissors); 
     result = (TextView)findViewById(R.id.result); 
+0

不在onCreate之前执行任何操作吗?我必须把它放在onCreate范围内吗?是的,这个想法是在这个时候尽可能全球化。 – BloodyIron

+0

类定义在OnCreate方法之前触发,这是有道理的,否则它的定义在OnCreate中不可用。如果您在全局声明它并在OnCreate中实例化它,它将在整个课程中都可用。 – Pyrodante

+0

记住:所有UI元素必须初始化setContentView – Pyrodante

其实很简单。在初始化课程时,初始化变量rockRB,paperRB,scissorRB和结果。在调用findViewById(...)时,布局尚未加载,因此没有找到具有指定标识的视图。函数findViewById因此返回null来指示。当你以后尝试使用存储的id(它是空的)时,你会得到一个空指针异常,因此整个应用程序崩溃。

要解决您的问题,请使用findViewById(...)将变量的初始化移动到setContentView语句下面的函数onCreate中,但在setOnClickListener语句之前。

像这样:

公共类RockPaperScissorsActivity延伸活动实现Button.OnClickListener { /**当首先创建活动调用。 */

private RadioButton rockRB; 
private RadioButton paperRB; 
private RadioButton scissorsRB; 
private TextView result; 



@Override 
public void onCreate(Bundle savedInstanceState) { 
    requestWindowFeature(Window.FEATURE_NO_TITLE); 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    rockRB = (RadioButton)findViewById(R.id.radioRock); 
    paperRB = (RadioButton)findViewById(R.id.radioPaper); 
    scissorsRB = (RadioButton)findViewById(R.id.radioScissors); 
    result = (RadioButton)findViewById(R.id.result); 

    rockRB.setOnClickListener(this); 
    paperRB.setOnClickListener(this); 
    scissorsRB.setOnClickListener(this); 
} 

等等...