我是「整體碎片」概念的新手,我需要一些幫助。片段中的自定義列表視圖 - 空指針異常
我想在片段中使用自定義列表視圖,我的代碼在Activity中正常工作,但在片段中的實現是相當痛苦的。我得到2空例外,我無法找出在哪裏。
我也有一個非常基本的問題,我應該在片段中使用什麼上下文,從片段活動或片段本身?
這裏是我的代碼片段
public class NewsFeed extends Fragment {
List<NewsFeedList> fr_ne_list = new ArrayList<NewsFeedList>();
Context ctx;
ListView list;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_news_feed, container, false);
list=(ListView)v.findViewById(R.id.listViewNewsFeedFriend);
return v;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(isAdded()) {
ctx=getActivity();
napolniseznamFriendList();
/*"at com.osembitdesign.faceit.NewsFeed.onCreate(NewsFeed.java:49)"*/
fillNewsFeedListView(fr_ne_list);
}
}
//filling custom listview
private void fillNewsFeedListView(List<NewsFeedList> elem) {
// TODO Auto-generated method stub
ArrayAdapter<NewsFeedList> adapter = new MyListAdapter(ctx,R.layout.news_feed_list_item, elem);
/*"at com.osembitdesign.faceit.NewsFeed.fillNewsFeedListView(NewsFeed.java:58)"*/
list.setAdapter(adapter);
}
private class MyListAdapter extends ArrayAdapter<NewsFeedList> {
public MyListAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
// TODO Auto-generated constructor stub
}
private List<NewsFeedList> element;
public MyListAdapter(Context context, int resource, List<NewsFeedList> items) {
super(context, resource, items);
this.element = items;
}
@Override
public View getView...
}
//adding items to my (Array)List
private void napolniseznamFriendList() {
// TODO Auto-generated method stub
fr_ne_list.add(new NewsFeedList("xxxx", "xxxx","xxxx",R.drawable.ic_action_search));
fr_ne_list.add(new NewsFeedList("xxx", "xx","xxx",R.drawable.ic_action_search));
}
}
錯誤
03-13 21:26:21.512 24416-24416/ E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.NewsFeed.fillNewsFeedListView(NewsFeed.java:58)
at com.NewsFeed.onCreate(NewsFeed.java:49)
謝謝!就像你說的我剛剛將條件語句移動到onViewCreated(),它的工作就像一個魅力! – gregaj
不客氣! –
可以幫我在這裏http://stackoverflow.com/questions/41938475/empty-custom-listview-in-fragment-on-back-tab – Panache