amirsoltani
amirsoltani

Reputation: 91

Force sending data using SharedPreferences( fragment to fragment in PagerAdapter)

I'm using SharedPreferences to store and send data from a fragment to 4 other fragments, but my problem is when the app is running and I send the data on click button it takes the other fragments sometime to actually receive the data ( or when swipe through the pages after 3 or 4 swipes they update) I have tried setUserVisibleHintin each fragment and onpagechangelistener in the activity but nothing changes. How can I make the other fragments to recieve the data as I swipe to the pages or as I press the button?

note: I don't want to put buttons in each fragment to load the data.

sender:

   int riddle;
   Context context = getActivity();
   SharedPreferences SU = context.getSharedPreferences(
                        "Riddle", Context.MODE_PRIVATE);
   SharedPreferences.Editor editor= SU.edit();
   editor.putString("Riddle",""+riddle);
   editor.commit();

other fragments:

      int Riddle;
      Context context = getActivity();
      SharedPreferences SU = context.getSharedPreferences(
                "Riddle", Context.MODE_PRIVATE);
      Riddle=  Integer.parseInt(SU.getString("riddle",""));

UPDATE I made a mistake in the original post , the sender should be:

    int riddle;
   Context context = getActivity();
   SharedPreferences SU = context.getSharedPreferences(
                        "Riddle", Context.MODE_PRIVATE);
   SharedPreferences.Editor editor= SU.edit();
   editor.putString("riddle",""+riddle);
   editor.commit();

because of the key thing.

one problem remains, the fragment im sending the data from is the last page(page 5) and when i send the data , the page next to it (page 4) doesnt update till i swipe to page 3 and come back to it

Upvotes: 1

Views: 51

Answers (2)

AskNilesh
AskNilesh

Reputation: 69734

use this

Riddle=  Integer.parseInt(SU.getString("Riddle",""));

instead of this

Riddle=  Integer.parseInt(SU.getString("riddle",""));

Upvotes: 1

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132992

Use same key for getting data from SharedPreferences which is used in sender. change :

Riddle=  Integer.parseInt(SU.getString("riddle",""));
                                        ^^^^^

to

Riddle=  Integer.parseInt(SU.getString("Riddle",""));

Upvotes: 2

Related Questions