调用setAdapter时片段中的NullPointerException

时间:2014-02-25 09:21:45

标签: android android-listview android-fragments oncreate listview-adapter

我有点问题。我正在尝试使用片段创建一个布局,但是当我调用setAdapter方法时,我有一个Java NullPointerException,我找不到错误。谢谢大家!

public static class DemoObjectFragment extends Fragment {

        public static final String ARG_OBJECT = "object";
        private List<RowItem> rowItems;

        private static Integer[] images = {
            R.drawable.red,
            R.drawable.red,
            R.drawable.red,
            R.drawable.red,
            R.drawable.red,
            R.drawable.red,
            R.drawable.red,            
            R.drawable.red
            };

        ListView lv;

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_collection_object, container, false);
            Bundle args = getArguments();

            lv = (ListView) this.getActivity().findViewById(R.id.myList);
            rowItems = new ArrayList<RowItem>();

            String[] titles = {"Movie1","Movie2","Movie3","Movie4","Movie5","Movie6","Movie7","Movie8"};
            String[] descriptions = {"First Movie","Second movie","Third Movie","Fourth Movie","Fifth Movie",
                    "Sixth Movie","Seventh Movie","Eighth Movie"};
            //Populate the List
            for (int i = 0; i < titles.length; i++) {
                RowItem item = new RowItem(images[i], titles[i], descriptions[i]);
                rowItems.add(item);
            }

            // Set the adapter on the ListView
            LazyAdapter adapter = new LazyAdapter(getActivity(), R.layout.list_row, rowItems);
            lv.setAdapter(adapter);

            lv.setOnItemSelectedListener(new OnItemSelectedListener() {

                @Override
                public void onItemSelected(AdapterView<?> arg0, View arg1,
                        int arg2, long arg3) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onNothingSelected(AdapterView<?> arg0) {
                    // TODO Auto-generated method stub

                }
            });

            //((TextView) rootView.findViewById(android.R.id.text1)).setText(Integer.toString(args.getInt(ARG_OBJECT)));
            return rootView;
        }
    }

1 个答案:

答案 0 :(得分:9)

更改

lv = (ListView) this.getActivity().findViewById(R.id.myList);

lv = (ListView) rootView.findViewById(R.id.myList);

你正在寻找活动中的ListView,但它可能属于片段的视图层次结构(它在R.layout.fragment_collection_object内声明)