java.lang.IllegalStateException: Could not execute method of the activity

来源:互联网 发布:mac srt 字幕 编辑:程序博客网 时间:2024/05/18 12:01

转载:http://www.xuebuyuan.com/2097467.html

Android编程里面很多问题其实都不算大问题,很多错误也是小错误,比如这次要说的
LogCat信息:
java.lang.IllegalStateException: Could not execute method of the activity
Caused by: java.lang.reflect.InvocationTargetException
Caused by: java.lang.NullPointerException
说白了就是无法执行和activity相关的方法,为什么无法执行呢,因为你给系统的是空引用,出现空指针错误
造成这种因素的原因很多,我目前已知的,就是代码的顺序问题,在onCreate方法中,应有如下代码

@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);username = (EditText) findViewById(R.id.username);pwd = (EditText) findViewById(R.id.pwd);}

这是一般的写法,如果照这样写,不会出现任何问题
注意现在把

setContentView(R.layout.activity_main);

的顺序换一下

@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);username = (EditText) findViewById(R.id.username);pwd = (EditText) findViewById(R.id.pwd);setContentView(R.layout.activity_login);}
这样只要执行和activity相关的方法,就会出现Could not execute method of the activity
为什么呢,因为绑定控件必须在整个界面出来之后,也就是说,系统还不知道使用的是哪个xml文件的时候,你告诉系统把xml文件中id为username的赋给username,系统当然会赋null,你对null执行getText()当然会出错.

所以写代码的时候注意先后顺序,setContentView先执行之后再进行相关控件的绑定.




自己错的地方:


自己的activity没有加进去,找不到,报错

0 0
原创粉丝点击