Wannabe
Wannabe

Reputation: 737

Send data between fragments using Shared Preferences

What the code should do: in the first fragment I have several EditText boxes, so people can fill in there name. In the second fragment I want the names to display in a TextView box. I thought using Shared Preferences was a good thing (correct me if I'm wrong).

In my first fragment I have this code:

public static String filename = "player1";
SharedPreferences someData;
[...]
someData = getActivity().getSharedPreferences(filename, 0);
String player1 = etPlayer1.getText().toString();
SharedPreferences.Editor editor = someData.edit();
editor.putString(player1, "player1");
editor.commit();

In my second fragment:

public static String filename = "player1";
SharedPreferences someData;
[...]
points1 = (TextView) getView().findViewById(R.id.tvPoints1);
someData = getActivity().getPreferences(0);
String dataReturned = someData.getString("player1", "Player 1");
points1.setText(dataReturned);

Upvotes: 0

Views: 4198

Answers (3)

Alain Beauvois
Alain Beauvois

Reputation: 5926

There are many ways to pass data between activity and fragment. See this response here : data sharing between fragments and activity in android

Upvotes: 1

Rachit Mishra
Rachit Mishra

Reputation: 6112

You may use an Intent or a Bundle. Shared Preferences are for storing long term data.

See this answer https://stackoverflow.com/a/10960855/826657

and this one for how to share data using a Bundle https://stackoverflow.com/a/16500141/826657

& this resource

http://developer.android.com/guide/components/fragments.html

Upvotes: 2

fasteque
fasteque

Reputation: 4339

Please pass your data (specially if complex) in a Bundle as explained here: Best practice for instantiating a new Android Fragment

Do not use shared preferences to do that.

Upvotes: 1

Related Questions