不幸的是,(应用程序名称)已停止工作

时间:2014-09-05 12:34:23

标签: android eclipse sdk android-emulator

这是logcat:

09-05 11:58:12.719: E/AndroidRuntime(710): Caused by: java.lang.NullPointerException
09-05 11:58:12.719: E/AndroidRuntime(710):  at com.example.new_idea.second_layout.onCreate(second_layout.java:30)
09-05 11:58:12.719: E/AndroidRuntime(710):  at android.app.Activity.performCreate(Activity.java:5008)
09-05 11:58:12.719: E/AndroidRuntime(710):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
09-05 11:58:12.719: E/AndroidRuntime(710):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
09-05 11:58:12.719: E/AndroidRuntime(710):  ... 11 more
09-05 11:58:15.560: I/Process(710): Sending signal. PID: 710 SIG: 9

第二个layout.java:

package com.example.new_idea;
import android.app.Activity;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class second_layout extends Activity {

TextView display_temp;
Button but_temp;

@Override
protected void onCreate(Bundle savedInstanceState) {
    display_temp = (TextView) findViewById(R.id.display_temp_id);
    but_temp = (Button) findViewById(R.id.button_temp_id);
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.ui);

    try
    {
        Thread.sleep(5000);
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

    but_temp.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            display_temp.setText("yes , thread is working");
        }
    }); 

}}

那么我该怎么做才能解决这个问题 我正在尝试通过按“按钮”按钮来更改文本视图的程序 但模拟器给我错误,不能执行上面的代码

2 个答案:

答案 0 :(得分:0)

display_temp = (TextView) findViewById(R.id.display_temp_id);
but_temp = (Button) findViewById(R.id.button_temp_id);

setContentView()之后移动这些内容。在此之前,您可以获得的是null,并且在null对象上调用setOnClickListener()之类的方法会导致NPE。

另外,删除Thread.sleep()。永远不要睡在主线上。

答案 1 :(得分:0)

只需更改onCreate方法并删除Thread.sleep()

@Override    
// TODO Auto-generated method stub
protected void onCreate(Bundle savedInstanceState) {  
super.onCreate(savedInstanceState);
setContentView(R.layout.ui);

display_temp = (TextView) findViewById(R.id.display_temp_id);
but_temp = (Button) findViewById(R.id.button_temp_id);

try
{
    Thread.sleep(5000);
}
catch (Exception e)
{
    e.printStackTrace();
}

but_temp.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        display_temp.setText("yes , thread is working");
    }
});}