Dreo
Dreo

Reputation: 229

How to use notifyDataSetChanged() with a viewpager which contains a fragment with a listview

I have a ViewPager with a FragmentStatePagerAdapter. Each page loads a fragment which contains a ListView. This ListView loads many TextViews which gets text from a static ArrayList. This static ArrayList is updated in a AsyncTask with data from a server. Well, i want to update the ListView, each time the ArrayList is updated. If i use notifyDataSetChanged() on the ViewPager adaptar it does not work, I have to get access to each ListViewadapter. Any suggestions?

This is my AsyncTask doinBackground method:

protected Object doInBackground(Object[] params) {
        if(socket!=null){
            try {
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            } catch (IOException e) {
                e.printStackTrace();
            }

            while(true){
                try {
                    s = in.readLine();

                } catch (IOException e) {
                    e.printStackTrace();
                }

                Type type = new TypeToken<ArrayList<VirtualSensor>>(){}.getType();
                Gson gson = new Gson();
                _sensorComponents =(ArrayList<VirtualSensor>) gson.fromJson(s, type);
                Log.d("Mesage", _sensorComponents.get(1).get_value()+"");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        adapter.notifyDataSetChanged();

                    }
                });


            }
        }

        return null;

    }

Update: After some testing i found out that the problem occurs when i have more than 1 page in viewpager. I use FragmentStatePagerAdapter.

Upvotes: 2

Views: 555

Answers (3)

Dreo
Dreo

Reputation: 229

After some testing i found out that the problem occurs when i have more than 1 page in viewpager. I use FragmentStatePagerAdapter.

Upvotes: 0

Emil
Emil

Reputation: 2806

Using EventBus is a better solution.

Also try this.

Instead of assigning data to your ArrayList try adding contents to it.

change this line

 _sensorComponents =(ArrayList<VirtualSensor>) gson.fromJson(s, type);

to

 _sensorComponents.clear();
 _sensorComponents.add((ArrayList<VirtualSensor>) gson.fromJson(s, type));

then notify your data set by calling adapter.notifyDataSetChanged();

Upvotes: 1

Marcin Orlowski
Marcin Orlowski

Reputation: 75629

Well, i want to update the listview, each time the arraylist is updated.

I would consider using Observer Pattern, which would make your code cleaner. Each of fragments then would register its listener and once your dataset is updated (by async taks or by any other means) you broadcast event about it and then fragments can do with it what they want. You may use event buses likes GreenRobot's EventBus or OTTO to save you some time.

Upvotes: 0

Related Questions