DavidBalas
DavidBalas

Reputation: 333

Trying to pass data between activities

Im trying to pass data between two activities using this subject:

How do I pass data between Activities in Android application?

with this answer:

In your current Activity, create a new Intent:

 Intent i = new Intent(getApplicationContext(), NewActivity.class);

 i.putExtra("new_variable_name","value");

 startActivity(i);

Then in the new Activity, retrieve those values:

    Bundle extras = getIntent().getExtras();
  
 if (extras != null) {
     
 String value = extras.getString("new_variable_name");
   
}

My problem is , I'm not success.. I have a game contains a value called coins but it is as a sharedperferences , here is the code of the sharedpreferences: (oncreate)

prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
    coins = prefs.getInt("key2", 0);

Now how do I get the amount of coins I got on the Shop(Shop.java) to buy things with them?

Upvotes: 1

Views: 97

Answers (2)

Mike
Mike

Reputation: 2705

As I see, you get number of coins in SharedPreferences. If you do so, you need to save it to in your Activity -

SharedPreferences.Editor prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE).edit();
prefs.putInt("key2", coins);
prefs.commit();

Upvotes: 0

joao2fast4u
joao2fast4u

Reputation: 6892

Just pass your coins value, in your sending Activity, using:

i.putExtra("new_variable_name",coins);

Note that the second parameter is your int coins value from SharedPreferences.

To read your coins value (int value) on the receiving Activity you have to read it as an Integer, not as a String.

So, use:

private int coinsValue = 0;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Bundle extras = getIntent().getExtras();

 if (extras != null) {

     coinsValue = getIntent().getIntExtra("new_variable_name", 0);

}

}

And there you go, coinsValue variable has your value.

Edit: To use coinsValue anywhere in your receiving class, declare it as a field, at the beginning.

Upvotes: 2

Related Questions