我正在
FATAL EXCEPTION: main
java.lang.NullPointerException
在这一行:
list_view.setAdapter(adapter1);
我已经发起了list_view和adapter1,我不知道为什么我会收到此错误。
我已经在setContentView:
之后初始化了list_viewlist_view = (ListView) findViewById(R.id.listView2);
任何人都可以帮我解决这个问题,如果您需要更多信息,我会提供给您。提前谢谢。
编辑以添加MainActivity类的完整代码:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category_fragment);
Context context=getApplicationContext();
final ListView listview = (ListView) findViewById(R.id.listView);
final ListView list_view = (ListView) findViewById(R.id.listView2);
final ArrayList<String> list = new ArrayList<>();
final ArrayList<String> list1 = new ArrayList<>();
String[] values = context.getResources().getStringArray(R.array.categories);
final String[] shoes = context.getResources().getStringArray(R.array.shoe_items);
for (int i = 0; i < values.length; ++i) {
list.add(values[i]);
}
//main category
final StableArrayAdapter adapter = new StableArrayAdapter(this,
android.R.layout.simple_list_item_1, list);
listview.setAdapter(adapter);
for (int i = 0; i < shoes.length; ++i) {
list1.add(shoes[i]);
}
final StableArrayAdapter adapter1 = new StableArrayAdapter(this,
android.R.layout.simple_list_item_1, list1);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
setContentView(R.layout.subcategory_fragment);
if (position == 0) {
list_view.setAdapter(adapter1);
}
}
});
}
答案 0 :(得分:2)
在onClick()
内的代码中,您再次调用setContentView()
,这将覆盖之前的布局并替换为新布局。
应该有名为listView2
布局文件subcategory_fragment.xml
的ListView
你必须重新初始化列表视图。因为重绘了整个布局
添加此行
final ListView list_view = (ListView) findViewById(R.id.listView2);
后
setContentView(R.layout.subcategory_fragment);