0

I am trying to refresh a ListFragment after Asynctask is finished. In my Asynctask doInBackground method I connect to a database and add elements to an ArrayList. In the onPostExecute method I want to access my ListFragment by something like this to call it's refreshData(method):

    //REFRESH ARTISTFRAGMENT
@Override
public void onPostExecute(ArrayList<String> result) {

    ArtistFragment artistFrag = new ArtistFragment();
    artistFrag = (ArtistFragment) artistFrag.getSherlockActivity().getSupportFragmentManager().findFragmentById(R.id.frame_container);
    if (artistFrag != null) {
        artistFrag.refreshData(result);
    }
}

But getSupportFragmentManager results in a NullPointerException!

The refreshData method in my Fragment looks like this:

    public void refreshData(ArrayList<String> data) {
       artists = new ArrayList<String>(data);
       this.artistAdpater.notifyDataSetChanged();
    }

I have found very similar approaches to do the exact thing I want but I can't find a solution to my problem. Basically it's done over here https://stackoverflow.com/a/16388650 - but it doesn't work for me like that.

Has anybody a solution for this or a workaround?

Community
  • 1
  • 1
f4b
  • 868
  • 1
  • 8
  • 10
  • A friend of mine found a simple workaround. He implemented a constructor inside AsyncTask. When instantiating and executing the AsyncTask handing over the Fragment. – f4b Jan 18 '14 at 20:36

1 Answers1

0

I am assuming that artists is the array list that feeds your listview.

 artists = new ArrayList<String>(data);

What you are doing creates a new arraylist object reference to artists. But the list adapter has the older refrence. Thats why the list is not getting update.

Instead of passing the reference of the new arraylist, you can add it to the old one like so:

newArtistsArraylist = new ArrayList<String>(data);
artists .add(newArtistsArraylist );

Here is a nice solution to your problem.

Community
  • 1
  • 1
amalBit
  • 12,041
  • 6
  • 77
  • 94
  • Thanks, this could be part of the problem but I don't even get this far because of the NullPointerException caused by `getSupportFragmentManager()` In the link you provided the old Adapter gets overwritten by a new one. But wouldn't it be better to refresh it with the new values and `notifyDataSetChanged()`? – f4b Jan 18 '14 at 14:41
  • Okay I changed this but I can't call the function refreshData() because I cannot access the instance of my Fragment to call it. Have you got an idea how to call it or how to solve the NullPointerExc.-problem? – f4b Jan 18 '14 at 15:35