NullPointerException

============问题描述============


public class MainActivity extends Activity  
{

    Button button=(Button)findViewById(R.id.button);
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_main);
      button.setOnClickListener(new OnClickListener()
      {

@Override
public void onClick(View v) {
Intent intent=new Intent();
intent.setAction(Intent.ACTION_CALL);//private abstract constant String Intent。ACTION_CALL
intent.setData(Uri.parse("tel:"+"110"));
 
startActivity(intent);
}
});  
    }

}
为啥报错NullPoinerException??

============解决方案1============


Button button=(Button)findViewById(R.id.button);要写在oncreate里面……

============解决方案2============


在没有绑定布局之前,是得不到button对象的,同意楼上

============解决方案3============


写在setContentView(R.layout.fragment_main);的下面

============解决方案4============



如图中提示一样,把button的初始化写到setContentView(R.layout.fragment_main);的下面就ok了

============解决方案5============


需要了解activity的原理,activity 并不是界面,而是window的控制器,只有加载了layout才能有展示,才能找到layout里面的组件

============解决方案6============


加载布局文件之后才能去获取控件

============解决方案7============


  Button button=(Button)findViewById(R.id.button);这个参考楼上,还有要实现接口  implements  OnClickListener

============解决方案8============


button的初始化应该在onCreat里面
posted @ 2014-10-22 22:16  android开发教程2015  阅读(508)  评论(0编辑  收藏  举报
我要啦免费统计