我有一行代码,当我调试nullpointerexception时,我可以看到它是我的应用程序崩溃的原因.
导致nullpointer的代码行是这样的:
ListView storeList = (ListView) findViewById(R.id.storeList);
Run Code Online (Sandbox Code Playgroud)
然后在调试模式下它尝试分配时崩溃:
storeList.setAdapter(arrayAdapter2);
Run Code Online (Sandbox Code Playgroud)
我不知道为什么对象没有初始化.在ArrayAdapter它下面的初始化罚款.如果你
下面是实际的java活动文件:
public class StoreListView extends Activity {
UserFunctions userFunctions = new UserFunctions();
ArrayAdapter<String> arrayAdapter2;
ArrayList<String> spinnerArray;
protected void onCreate(Bundle savedInstanceState) {
ListView storeList = (ListView) findViewById(R.id.storeList);
super.onCreate(savedInstanceState);
setContentView(R.layout.storelistviewpage);
arrayAdapter2 = new ArrayAdapter<String>(StoreListView.this,android.R.layout.simple_list_item_1);
spinnerArray = getIntent().getStringArrayListExtra("cusName");
arrayAdapter2.addAll(spinnerArray);
storeList.setAdapter(arrayAdapter2);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main_screen, menu);
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
下面是xml文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/storeList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|center_vertical" >
</ListView>
Run Code Online (Sandbox Code Playgroud)
编辑:如果有人想知道我将活动添加到android mainfest
移动
ListView storeList = (ListView) findViewById(R.id.storeList);
Run Code Online (Sandbox Code Playgroud)
setContentView()通话结束后.
由于当前的代码分配的结果findViewById() 之前 setContentView()被调用时,你会总是得到storeList是null,所以,你会得到一个NPE.
| 归档时间: |
|
| 查看次数: |
50 次 |
| 最近记录: |