0

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. :)

Community
  • 1
  • 1
DavidBalas
  • 333
  • 7
  • 21

3 Answers3

0

For this I recommend use SharedPreferences, as you do in previous your question. Anyway, you can use startAcvitityForResult(intent, yourRequestCode);

To return data to your previous Acvitity:

Intent intent = new Intent();
intent.putExtra("your_key", key_value);
setResult(RESULT_OK, intent);
finish();

in your previous Acvitity:

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK)
        {
            if(requestCode == yourRequestCode && data != null)
            {
             coins = data.getIntExtra("your_key",default_value);   
            }
        }
    }

EDIT: changed code. First Activity:

public static final int REQUEST_CODE = 1;
      ...........
    private void openSHOP() {
    mPlayer.pause();

    Context context = getApplicationContext();

    Intent i = new Intent(context, Shop.class);
    i.putExtra("new_variable_name",coins);
    startActivityForResult(i, RESULT_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);
     ....
        @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(resultCode == RESULT_OK)
    {
        if(requestCode == REQUEST_CODE && data != null)
        {
         coins = data.getIntExtra("key2", coins);   
        }
    }
   }

Second Activity:

{
    Bundle extras = getIntent().getExtras();
     if (extras != null) {
     coinsValue = getIntent().getIntExtra("new_variable_name", 0);
     ....
     setResultAndFinish();
}

private void setResultAndFinish()
    {
        Intent intent = new Intent();
        // use your number of coins and put it to Intent.
        intent.putExtra("key2", coinsValue);
        setResult(RESULT_OK, intent);
        finish();
    }
Mike
  • 2,547
  • 3
  • 16
  • 30
  • in your previous Activity. – Mike Jul 05 '14 at 20:05
  • I don't know what is this line.. its says yourRequestCode cannot be resolved to a variable.. – DavidBalas Jul 05 '14 at 20:08
  • ok. yourRequestCode is a custom int variable which defines with which Acvitity you want to communicate. I use integer from 1. e.g. declare **public static final int REQUEST_CODE = 1;** and put REQUEST_CODE instead of yourRequestCode. As you can see from the code, I compare requestCode in onActivityResult. Hope you understand other **fake** variables. – Mike Jul 05 '14 at 20:14
  • Actually, I haven't understand it.. I put before the oncreate where all the privates are, the line **public static final int REQUEST_CODE = 1;** and the @Override code you gave after the oncreate but I didn't know where to put the line **startAcvitityForResult(intent, yourRequestCode);** I mean, where , exactly place. – DavidBalas Jul 05 '14 at 20:28
  • you should call startActivityForResult(intent, REQUEST_CODE) instead of just startActivity(); startActivityForResult starts activity which do some work and returns back to the previous activity with some result. and onActivityResult instead of yourRequestCode use - REQUEST_CODE – Mike Jul 05 '14 at 20:57
  • also read this [documentation](http://developer.android.com/reference/android/app/Activity.html#startActivityForResult(android.content.Intent,int)) – Mike Jul 05 '14 at 20:59
  • I haven't really understand it but with your code, how do I get back to the first activity? its just keeping me at the second one... – DavidBalas Jul 05 '14 at 21:15
  • `Intent intent = new Intent(); intent.putExtra("your_key", key_value); setResult(RESULT_OK, intent); finish();` – Mike Jul 05 '14 at 21:16
  • Edited :) Take a look. – DavidBalas Jul 05 '14 at 22:27
  • Ty for helping me that much :) but there is still a problem, you put "startActivityForResult(i,Result_Code)" I think you meant "Request_code" so I changed it.. and the second problem, I want to get back to the first activity by clicking a button not by an action that will happen oncreate :\ – DavidBalas Jul 06 '14 at 11:28
  • I think this is trivial task. Please do some research on this. example - button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setResultAndFinish(); } }); – Mike Jul 06 '14 at 21:06
0

If you are saving your coins value in SharedPreferences, you just have to save it when you change it and read it from Preferences when you need to.

To save, use:

prefs.edit().putInt("key2", coinsValue).commit();

to read, as you do in your first Activity:

coins = prefs.getInt("key2", 0);

This way you always get the updated coins value wherever you want to.

joao2fast4u
  • 6,868
  • 5
  • 28
  • 42
  • Hey again :P ... It's not working to me.. I can use coinsValue only at the second activity so when I put it on the firstactivity it says coinsValue cannot be resolved to a variable – DavidBalas Jul 05 '14 at 20:03
  • Yes, that's because your variable has different names in the two Activities, and Android treats each of the variables as independent ones. Change the variable name in the first activity and you will make it work. – joao2fast4u Jul 05 '14 at 20:07
  • Try to make the other way around, change coins to coinsValue. The variable has to have the same name in one Activity. But the name can be different in your two Activities. This is programming common sense. – joao2fast4u Jul 05 '14 at 20:13
  • Still not working, when im going to the shop, it look likes it creates a new "coinValue" different from the old one that is value is defaulty 0, I mean if I have 10 coins, I go to the shop, buy something, its says I had nothing before. – DavidBalas Jul 05 '14 at 20:22
  • That must be because you are not saving your coins value when you should. Save it and read it from Preferences always using the same key value. "coins", for example. If you read a value from a key that does not exist, it will return 0 to you. – joao2fast4u Jul 05 '14 at 20:26
  • Its too hard to me.. I guess I will leave it this way and that's it.. I really don't understand this things.. – DavidBalas Jul 05 '14 at 20:34
0

Use SharePreferences instead . It is accessible also in other activities. There is no need to send it where as you have stored them in SharedPreferences

The shared preferences are accessible throughout your application, so you can read them from any activity in the application.

Storing a key/value pair in activity A:

SharedPreferences settings = getSharedPreferences("mysettings", 
     Context.MODE_PRIVATE);

SharedPreferences.Editor editor = settings.edit();
editor.putString("mystring", "wahay");
editor.commit();

Reading this value from another activity:

SharedPreferences settings = getSharedPreferences("mysettings", 
    Context.MODE_PRIVATE);
String myString = settings.getString("mystring", "defaultvalue");

You can find more information at http://developer.android.com/guide/topics/data/data-storage.html#pref

Zare Ahmer
  • 808
  • 5
  • 8