2012-01-11 208 views
0

当我在eclipse中编写我的代码(以下)时,它在模拟器上给出了一个错误,您的应用程序意外停止。 sdk没有安装错误。这是我的代码。Android应用程序意外停止

public class startingPoint extends Activity { 
    /** Called when the activity is first created. */ 

    int counter1,counter2; 
    Button add; 
    Button sub; 
    TextView display; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     counter1=counter2 = 0; 
     add = (Button) findViewById(R.id.bAdd); 
     add = (Button) findViewById(R.id.bSub); 
     display = (TextView) findViewById(R.id.tvDisplay); 
     add.setOnClickListener(new View.OnClickListener() { 

      public void onClick(View arg0) { 
       counter1=counter1+1; 
       display.setText("Your total is "+counter1); 

      } 
     }); 
     sub.setOnClickListener(new View.OnClickListener() { 

      public void onClick(View arg0) { 
       counter2=counter2-1; 
       display.setText("Your total is "+counter2); 
      } 
     }); 
    } 
} 
+0

什么是logcat的错误? – JoxTraex 2012-01-11 12:44:14

回答

1

您正在为同一变量分配一个新值两次。

add = (Button) findViewById(R.id.bAdd); 
add = (Button) findViewById(R.id.bSub); 

我想这应该是:

add = (Button) findViewById(R.id.bAdd); 
sub = (Button) findViewById(R.id.bSub); 

在你的代码,sub.setOnClickListener抛出一个NullPointerException因为sub为空。

1

你们一份&粘贴错误,你永远不会初始化sub

add = (Button) findViewById(R.id.bAdd); 
add = (Button) findViewById(R.id.bSub); // should be sub instead of add 

对于接下来的问题,请看看你的logcat和后堆栈跟踪,因为这可以帮助我们找到错误更容易。

1

您正在收到nullPointer异常,因为您没有初始化子变量。修改代码:

add = (Button) findViewById(R.id.bAdd); 
add = (Button) findViewById(R.id.bSub); 

add = (Button) findViewById(R.id.bAdd); 
sub = (Button) findViewById(R.id.bSub);