2012-04-02 45 views
-2

我做了一个简单的应用程序,它将count加1,并在TextView上显示计数。它编译和安装的很好,但是当我运行它时,一条消息立即说:“不幸的是,Counter已经停止。”Android应用程序不运行

package com.android.counter; 

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


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

private static int count = 0; 
Button increment = (Button) findViewById(R.id.inc); 
TextView tv = (TextView) findViewById(R.id.CountDisp); 


Runnable update = new Runnable() 
{ 
    public void run() { 
     increment.setOnClickListener(new View.OnClickListener() 
     { 
      public void onClick(View v) 
      { 
       count++; 
       tv.setText("Count:" + count); 
      } 
     }); 
    } 
}; 


@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    Thread thr = new Thread(update); 
    thr.start(); 

} 

} 

回答

1

在尝试查找任何视图之前,您需要设置Activity的内容。这样做......

Button increment = (Button) findViewById(R.id.inc); 
TextView tv = (TextView) findViewById(R.id.CountDisp); 

...您当前所在,将意味着双方incrementtvnull。改变这些行...

Button increment; 
TextView tv'; 

onCreate(...)然后使用findViewById(...)之后,你有叫setContentView(...)

而且,使用单独的Thread(Runnable接口)来处理onClick(...)监听器是在复杂的事情,而不是必要。只需在onCreate(...)内创建您的onClick(...)侦听器,并忘记其他线程代码。

+0

实际上'tv.setText(...)'不会失败,因为它将在UI线程中被调用......在UI线程上未调用的唯一部分是'increment.setOnClickListener' – Selvin 2012-04-02 15:54:33

+0

@Selvin:好点和我我编辑了我的答案。我的大脑放慢速度 - 我想我需要另一杯咖啡。 – Squonk 2012-04-02 16:03:04

0

您需要查看LogCat。你可以用Eclipse或DDMS工具来完成。该logcat的日志会告诉你:

  • 什么例外是
  • 凡在它的代码发生

利用这些信息,那么你可以找到原因。从源代码单独做就是受虐狂。