0

I want to refresh the List of a ListFragment. Therefore I created a method in my ListFragment:

public void setAdapter(List<String> valueList) {
    ArrayAdapter adapter = new ArrayAdapter<String>(ctx, android.R.layout.simple_list_item_1, valueList);
    setListAdapter(adapter);
    adapter.notifyDataSetChanged();
}

And in my Activity I have a AsyncTask where I call the method above in onPostExecute:

    @Override
    protected void onPostExecute(ArrayList<String> valueList) {
        OtherClass otherClasst = new OtherClass();

        otherclass.setAdapter(valueList);
    }

Everything should work fine. The valueList isn't empty or something like that and also the onPostExecute gets called.

So now my Problem is, that if I initialize the Context ctx in the onCreate method of my ListFragment I get a NullPointerException. When I initialize it in my setAdapter method with ctx = getActivity I get the same error. The only thing I can do is to get the context of the class with the AsyncTask, but then nothing is shown in the app.

So how do I get this to work?

the-ginger-geek
  • 7,041
  • 4
  • 27
  • 45

1 Answers1

1

Since you are calling setAdapter from onPostExecute of AsyncTask, then your activity might have destroyed and may be that's why you are getting null context by calling getActivity.

Initialize the adapter(make it global) outside setAdapter, may be in onCreateView method of Fragment like this:

adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, valueList);

And onPostExecute of AsyncTask just update the valueList and call adapter.notifyDataSetChanged()

Rohit Arya
  • 6,751
  • 1
  • 26
  • 40
  • This doesn't work. Beacause for some reason calling adapter.notifyDataSetChanged() throws a null pointer exception as well. Is it worth mentioning that the ListFragment is inside the Activity that calls the Method setAdapter? – der kaländer Apr 20 '16 at 11:28