[英]java NullPointerException Android Handler
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);
}
};
}
}
I tried forcing the Orientation to portrait to run this code but it failed again. 我尝试强制将Orientation纵向化以运行此代码,但再次失败。
Whenever i try a handler to basically change the view text after every second i get this error. 每当我尝试处理程序每秒钟基本更改视图文本时,都会收到此错误。
Am new to Android development a college student so bear with my mistakes if any. 我是一名Android开发新手,是一名大学生,如果有的话,请接受我的错误。
Thank you in advance. 先感谢您。
The logs are below. 日志如下。
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)
you have not used the initialize()
function in oncreate ,below code use ,you will get the expected result. 您没有在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);
}
}
initialize myHandler
as 将
myHandler
初始化为
Handler myHandler = new Handler();
ie replace 即替换
Handler myHandler;
to 至
Handler myHandler = new Handler();
And call initialize()
method before myHandler.post(myRunnable);
然后在
myHandler.post(myRunnable);
之前调用initialize()
方法myHandler.post(myRunnable);
as 如
initialize();
myHandler.post(myRunnable);
myHandler未初始化,并且由于未在onCreate()中调用initialize()方法,因此在尝试发布myRunnable之前也未对其进行初始化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.