简体   繁体   English

ListView setAdapter()NullPointer异常(使用Inflater)

[英]ListView setAdapter() NullPointer Exception (uses Inflater)

I want to populate a ListView from an ArrayList, here is my code: 我想从ArrayList填充ListView,这是我的代码:

rootView = inflater.inflate(R.layout.verein_layout, container, false);

ListView veaList = (ListView)getView().findViewById(R.id.veaList);
ArrayList<String> items = new ArrayList<String>();

The items get filled in here... then this code: 这些项目在这里填写...然后是此代码:

ListAdapter adapter = new ArrayAdapter(inflater.getContext(),
android.R.layout.simple_list_item_2, android.R.layout.simple_list_item_1, items);

veaList.setAdapter(adapter);

Unfortunately, the code throws a NullPointerException. 不幸的是,代码抛出NullPointerException。 What do I do wrong? 我做错了什么?

Thanks in advance, 提前致谢,

forumfresser forumfresser

Try this.. 尝试这个..

Change the below line 更改以下行

ListView veaList = (ListView)getView().findViewById(R.id.veaList);

as

ListView veaList = (ListView) rootView.findViewById(R.id.veaList);

because getView() returns the view as null that's why that error . 因为getView()将视图返回为null ,这就是该错误的原因。 So you should use rootView because that the main view.... 因此,您应该使用rootView因为该主视图是...。

getView()返回您已放大并在onCreateView内部返回的视图,因此在onCreateView内使用它是错误的,因为它尚不可用。

Just try this one... 只是尝试这个...

ListAdapter adapter = new ArrayAdapter(inflater.getContext(),
android.R.layout.simple_list_item_2, items);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM