应用程序DecRa(进程com.Decra)意外停止。请再试一次

时间:2012-05-30 13:30:35

标签: android

logcat的:

FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.Decra/com.Decra.DecRaActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
at android.app.ActivityThread.access$2300(ActivityThread.java:125)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4627)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)

代码:

    TextView dectv=(TextView)findViewById(R.id.dec);
    TextView ratv=(TextView)findViewById(R.id.ra);
    TextView result=(TextView)findViewById(R.id.result);
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button btn=new Button(this);
        btn.setOnClickListener(this);
    }

启动应用程序时,强制关闭时出现以下错误:

the application DecRa (process com.Decra) has stopped unexpectedly.Please try again.

编译器中没有错误,因此必须是运行时错误。 但是我没有得到错误的意思!而我所理解的是其中一个错误是指findViewById

1 个答案:

答案 0 :(得分:1)

如果您事先没有致电findViewById(),则无法致电setContentView()。只需将TextView初始化行移动到onCreate()方法,如下所示:

TextView dectv;
TextView ratv;
TextView result;

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

        dectv=(TextView)findViewById(R.id.dec);
        ratv=(TextView)findViewById(R.id.ra);
        result=(TextView)findViewById(R.id.result);

        ...
        ...
    }