简体   繁体   中英

ArrayAdapter java.lang.NullPointerException

I have this code but the app crashes on the line setadapter . I really don't understand because I set the adptater by the new arrayadapter.

I tried other ways but no one works !

By the way, this code is in a Fragment and not an activity !

So have you an idea of what happens ?

public class Fragment_product_list extends Fragment{

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        final ListView listview = (ListView) getActivity().findViewById(R.id.list_product);
        String[] values = new String[] { "item1" , "item2" , "item3" , "item4" , "item5" , "item6" , "item7" };

        final ArrayList<String> list = new ArrayList<String>();
        for (int i = 0; i < values.length; ++i) {
            list.add(values[i]);
        }
        final ArrayAdapter adapter = new ArrayAdapter(getActivity(), android.R.layout.list_content , list);

        listview.setAdapter(adapter); /*app crash here*/
        }

        private class StableArrayAdapter extends ArrayAdapter<String> {

        HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();

        public StableArrayAdapter(Context context, int textViewResourceId,
                              List<String> objects) {
        super(context, textViewResourceId, objects);
        for (int i = 0; i < objects.size(); ++i) {
            mIdMap.put(objects.get(i), i);
        }
    }

    @Override
    public long getItemId(int position) {
        String item = getItem(position);
        return mIdMap.get(item);
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }
  }
}

Thanks !

Fragment view inflation happens in onCreateView .
I suggest you to see this fragment example and read more about it life cycle.

Just in case you didn't get NickF's answer, here is the solution: Override the onCreateView method in your fragment and do as follows.

public class Fragment_product_list extends Fragment{
      @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
               View rootView = inflater.inflate(R.layout.your_layout, container,
                false);
               ListView listView = (ListView) rootView.findViewById(R.id.list_product);

               //Rest of the code
        }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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