0

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);
Wannabe
  • 727
  • 1
  • 6
  • 21

3 Answers3

2

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

Community
  • 1
  • 1
Rachit Mishra
  • 6,101
  • 4
  • 30
  • 51
  • How do I send data using a bundle. I tried to send data but my application crashes. I have to send a string from the first fragment to the second. – Wannabe Aug 26 '13 at 17:19
1

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.

Community
  • 1
  • 1
fasteque
  • 4,309
  • 8
  • 38
  • 50
1

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

Community
  • 1
  • 1
Alain Beauvois
  • 5,896
  • 3
  • 44
  • 26