public class MainActivity extends ActionBarActivity {
Handler myHandler;
Runnable myRunnable;
TextView tv;
int no;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myHandler.post(myRunnable);
}
public void initialize(){
no = 10;
tv = (TextView) findViewById(R.id.textView1);
myRunnable = new Runnable() {
@Override
public void run() {
tv.setText(Integer.toString(no));
no--;
if(no != 0)
myHandler.postDelayed(myRunnable, 1000);
}
};
}
}
我尝试将Orientation强制为纵向运行此代码,但它再次失败。
每当我尝试处理程序基本上每秒后更改视图文本时,我都会收到此错误。
对于Android开发的新手大学生如果有任何错误,请承担。
提前谢谢。
日志如下。
10-04 04:22:35.750: E/AndroidRuntime(2123):FATAL EXCEPTION: main
10-04 04:22:35.750: E/AndroidRuntime(2123):java.lang.RuntimeException: Unable to start activity ComponentInfo{we.funnycorps.handlerpractise/we.funnycorps.handlerpractise.MainActivity}: java.lang.NullPointerException
10-04 04:22:35.750: E/AndroidRuntime(2123):at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
10-04 04:22:35.750: E/AndroidRuntime(2123):at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
答案 0 :(得分:2)
你没有在oncreate中使用initialize()
函数,在代码使用之下,你将得到预期的结果。
public class Dummycls extends Activity {
Handler myHandler;
Runnable myRunnable;
TextView tv;
int no;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialize();
//myHandler.post(myRunnable);
}
public void initialize(){
no = 10;
tv = (TextView) findViewById(R.id.pinchTitleText);
myHandler=new Handler();
myRunnable = new Runnable(){
public void run() {
tv.setText(Integer.toString(no));
no--;
if(no != 0)
myHandler.postDelayed(myRunnable, 1000);
//handler.postDelayed(r, 1000);
}
};
myHandler.post(myRunnable);
}
}
答案 1 :(得分:1)
将myHandler
初始化为
Handler myHandler = new Handler();
即。替换
Handler myHandler;
到
Handler myHandler = new Handler();
在initialize()
之前调用myHandler.post(myRunnable);
方法
initialize();
myHandler.post(myRunnable);
答案 2 :(得分:0)
myHandler没有被初始化,并且因为你的onCreate()没有调用initialize()方法,所以myRunnable在尝试发布之前也没有初始化。