【问题标题】:Android app error “Unfortunately App has Stopped”Android应用程序错误“不幸的是应用程序已停止”
【发布时间】:2013-07-02 21:52:41
【问题描述】:

您好,我在运行应用程序时遇到问题,当它运行不良时,它会打开,但是当我按下按钮说应用程序已停止且无法运行时:“不幸的是,应用程序已停止”。这是我的简单代码,我希望我能很快得到答案...... 谢谢分配:)

package com.stefan.stefan1;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

    TextView textView1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final Button button1 = (Button) findViewById(R.id.button1);
        button1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                textView1.setText("Hello Im Stefan !");
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

你好,我又遇到了新问题,我添加了另一个标签(textView2),我试图再次添加这一行 textView2 = (TextView) findViewById(R.id.textView2); 但是在“R.java”类中添加一些东西给我错误 请帮忙..:/

【问题讨论】:

  • onCreate 方法上初始化textView1,例如textView1 = (TextView) findViewById(your_id);

标签: android


【解决方案1】:

你忘了初始化textView1

所以当你在做的时候:

textView1.setText("Hello Im Stefan !");

它会抛出 NullPointerException 并停止您的应用。

如果您在布局中定义了 textview,请在 setContentView 之后添加

textView1 = (TextView) findViewById(R.id.idOfYourTextView);

P.S : 当你遇到这样的错误时,你应该总是提供 stacktrace(logcat)。

【讨论】:

  • 哦,谢谢分配,但还有一个问题,为什么给我 3 个错误:[2013-07-02 14:11:43 - ddms] Can't bind to local 8700 for debugger [2013-07-02 14:11:50 - ddms] Can't bind to local 8700 for debugger [2013-07-02 14:14:14 - ddms] Can't bind to local 8700 for debugger
  • 检查thisthis
  • 顺便说一句,应用程序运行顺利,谢谢! :D
  • 你好,我现在又遇到了一个问题,我添加了另一个标签(textView2),我尝试再次添加这一行textView2 = (TextView) findViewById(R.id.textView2);,但在“R.java”类中添加内容时出错请帮助.. :/
  • @StefanRafa 你声明了字段'TextView textView2;' ?
猜你喜欢
  • 1970-01-01
  • 2015-11-28
  • 2017-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多