watch this before: Trying to pass data between activities Ok, so I have this code on the first activity:
prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
coins = prefs.getInt("key2", 0);
and this:
Intent i = new Intent(getApplicationContext(), Shop.class);
i.putExtra("new_variable_name",coins);
startActivity(i);
And at the second activity:
private int coinsValue = 0;
....
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.XXXX);
Bundle extras = getIntent().getExtras();
if (extras != null) {
coinsValue = getIntent().getIntExtra("new_variable_name", 0);
.... }
This code works fine, the coins is shared on both pages, now I want when I get back to the first activity, the coins and the coinsValue will sync and it will save it , I mean, this code works when I go from the first activity to the second, but when I get back to the first activity(intent from shop to firstactivity), the coins value is stays the same as at start, it's not saving the coinsValue.
EDIT:
First activity code:
public SharedPreferences prefs;
public static final int REQUEST_CODE = 1;
....
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.PAUSE:
openPopUP();
return true;
case R.id.SHOP:
openSHOP();
return true;
default:
return super.onOptionsItemSelected(item);
}
.....
private void openSHOP() {
mPlayer.pause();
Context context = getApplicationContext();
Intent i = new Intent(context, Shop.class);
i.putExtra("new_variable_name",coins);
startActivityForResult(i, REQUEST_CODE);
CharSequence text = "You are at the shop";
int duration = Toast.LENGTH_LONG;
Toast.makeText(context, text, duration).show();
}
.......
prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
score = prefs.getInt("key", 0); //0 is the default value
coins = prefs.getInt("key2", 0);
time = prefs.getInt("key1", 0);
.............. }
Second activity code:
public static final int REQUEST_CODE = 1;
......
Bundle extras = getIntent().getExtras();
if (extras != null) {
coinsValue = getIntent().getIntExtra("new_variable_name", 0);
..........
if (id == R.id.button6) {
mPlayer.pause();
startActivityForResult(getIntent(), REQUEST_CODE);
Intent intent = new Intent(Shop.this, FirstActivity.class);
intent.putExtra("key2", coinsValue);
setResult(RESULT_OK, intent);
startActivity(intent);
Context context = getApplicationContext();
CharSequence text = "You went back to the game";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
That's all meanwhile, still not working, When I go to the second activity, it does know how much coins I have, but when I spend them and go back to the first activity, it shows like I haven't buy nothing, like it haven't save the coins after the purchase. :)