1

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

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”中添加一些东西的错误请帮助..:/

4

1 回答 1

1

你忘了初始化textView1

所以当你在做的时候:

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

它抛出一个NullPointerException并停止你的应用程序。

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

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

PS:当您遇到此类错误时,您应该始终提供堆栈跟踪(logcat)。

于 2013-07-02T12:20:45.003 回答