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

时间:2011-10-03 19:56:33

标签: android crash

好吧,我尝试使用DDMS调试我的代码,但我还不能确定它的问题。我想这是因为我的程序在发布时崩溃了。无论如何,我把它展示给一个伙伴,他无法弄清楚我做错了什么。有人可以指出为什么我的应用程序在启动时崩溃了吗?

感谢:

http://pastebin.com/ZXxHPzng

2 个答案:

答案 0 :(得分:4)

您遇到的问题是您正在全局区域中创建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);

答案 1 :(得分:1)

实际上非常简单。初始化类时,初始化变量rockRB,paperRB,scissorRB和结果。在您调用findViewById(...)时,尚未加载布局,因此找不到具有指定标识的视图。函数findViewById因此返回null以指示。当您稍后尝试使用存储的id(为空)时,您将获得空指针异常,因此整个应用程序崩溃。

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

像这样:

公共类RockPaperScissorsActivity扩展Activity实现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);
}

依旧......

相关问题