问题描述
- abdroid 空指针问题,新手求教
-
这种情况是正常的
private Button button;
private Button button1;@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = (Button)findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SharedPreferences.Editor editor = getSharedPreferences(""data"" 0).edit(); editor.putInt(""yi"" 1); editor.putString(""er""二""); editor.apply(); Toast.makeText(MainActivity.thiscomplete"" Toast.LENGTH_SHORT).show(); } });
这样就会报空指针错
private Button button= (Button)findViewById(R.id.button);;
private Button button1;@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { SharedPreferences.Editor editor = getSharedPreferences(""data"" 0).edit(); editor.putInt(""yi"" 1); editor.putString(""er""二""); editor.apply(); Toast.makeText(MainActivity.thiscomplete"" Toast.LENGTH_SHORT).show(); } });
请问这两种的区别在哪里?
解决方案
private Button button= (Button)findViewById(R.id.button);;//第二种初始化在oncreate执行前, 也就是 setContentView(R.layout.activity_main);还没执行,布局都还没加载,肯定找不到R.id.button
解决方案二:
同上;第二个你布局都没有加载就先给button赋内容啦;肯定会报空指针的。。
解决方案三:
button没赋值当然会OOM啦
解决方案四:
setContentView后再findViewById
时间: 2025-01-01 17:11:43