Yaniv
Yaniv

Reputation: 1

Sending Strings between activities

I want to send a value to an activity that HighScore which shows the highest score of the game.

I am saving the score at the game activity in shared preferences, and I am trying to send the score(string value) to the activity HighScore.

Intent i = new Intent(this, HighScoreActivity.class); 
i.putExtra("classicHighScore", highScore);

Upvotes: 0

Views: 70

Answers (3)

Laerte
Laerte

Reputation: 7083

You need to save data in a SharedPreferences object in the first Activity and read it in the other activity.

Saving the score using SharedPreferences in the first Activity:

SharedPreferences preferences = getSharedPreferences("SharedScore", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("classicHighScore", highScore);
editor.commit();

Reading the score from SharedPreference in the other activity:

SharedPreferences preferences = getSharedPreferences("SharedScore", MODE_PRIVATE);
int score = preferences.getInt("classicHighScore", -1);

Upvotes: 1

ramses
ramses

Reputation: 505

If you want send a String between activities you must create a Bundle.

Intent i = new Intent(this, HighScoreActivity.class); 

Bundle bundle = new Bundle();
bundle.putString("classicHighScore", highScore);
i.putExtra(bundle);

To read de parameter in HighScoreActivity

Bundle arguments = getIntent().getExtras();
String classicHighScore = arguments.getString("classicHighScore");

Upvotes: 0

JozeRi
JozeRi

Reputation: 3429

it seems like you are sending your string in an intent. which means, in your HighScore activity, write

String highScore = getIntent.getStringExtra("classicHighScore", "");

and there you go, String highScore now has your value,

you can log it to check :

Log.d("HIGH SCORE VALUE ", highScore);

Upvotes: 1

Related Questions