我在网上搜索了挺多资料的,很多都是重复在说权限问题,然而我报这种错误的大部分程序都恰好不是因为权限问题,而是一些特别细节的问题......
按照我的经验,我的建议是:
找控件代码的错误!
报错原因:一般是由于取不到控件对象、控件的点击事件执行的时候得到了空值等和初始化控件有关的原因造成的。
比如...
private Button bt; //声明
bt.setOnclickListener(new OnClickLisenter(){....}); //调用
有问题吗?有啊!
1、xml布局的控件
检查是不是在java代码中漏写了findViewById()啊!!!
上面就漏了bt=(Button)findViewById(R.id...);这句话
2、java动态新建控件/自定义控件出错
检查是否忘记创建对象!!!
上面就漏了 bt=new Button(); 这句话
所以上面的代码正确的改法是:
private Button bt;
//如果是获取xml中写死的固定控件对象,则:
bt=(Button)findViewById(R.id...);
//如果采用动态创建控件,则上一句代码改为:
//bt=new Button();
bt.setOnclickListener(new OnClickLisenter(){....});
3、控件EditView(文本输入框)取值为空,也会报这个错。
不要在onCreate()或者其他必先执行的方法(例如构造方法)中直接取文本框的值。
这是大忌写法,因为此时用户啥也没输入,取不到值,控件初始化失败,会报错并闪退的
private EditView ev;
private void OnCreate(){
ev=(EditView)findViewById(R.id...);
ev.getText(); //大忌写法
}
4、有关集合的泛型也一定要检查好<>内的是不是一致的,以免出现泛型的类型转换异常。
5、控件的点击或其他事件的监听方法放错了位置或者代码写错!
代码写错:puvlic void onClick(View v)漏了关键的“View v”
不规范写法\放错地方: 新手写点击事件的时候,这两种写法都不报错,但是,有时候运行会,闪退哦。
private Button bt;
private OnClickLisenter ;
private void OnCreate(){
bt=(Button)findViewById(R.id...);
mylisten=new OnClickLisenter(){....};
bt.setOnclickListener(mylisten);
}
private Button bt;
private OnClickLisenter mylisten=new OnClickLisenter(){....};
private void OnCreate(){
bt=(Button)findViewById(R.id...);
bt.setOnclickListener(mylisten);
}