TheQ
TheQ

Reputation: 2019

How do I change an activities's boolean values or other variable values in another activity?

So I have a boolean value in Activity A that is set to false. Then, in another activity I want to change that value to true. Then when i press the back button back to activity A, that boolean is now true and it runs that in the onCreate.

here's what I mean, Activity A

private static boolean newCardcheck = false;

 @Override
protected void onCreate(Bundle savedInstanceState)
{ 

}


public static void setNewCardcheck() {
    newCardcheck = true;
}


@Override
public void onResume() {
    super.onResume();
   if(newCardcheck)
    {
        Toast.makeText(this,"hey everyone",Toast.LENGTH_SHORT).show();
    }
    else
    {
        alfunction();
        sendCards(storeCards);
    }

}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    if(requestCode == RESULT_LOAD_IMAGE)
    {
        newCardcheck = true;
    }
}

Activity B:

@Override
public void onBackPressed()
{
    MyActivity.setNewCardcheck();
    super.onBackPressed();
    setResult(Activity.RESULT_OK, getIntent());
    finish();
}

So when I press back, I want newCardcheck to be true and run the "if" statement not the else statement.

Hope you guys can help.

thanks.

And I also tried putting setNewCard() method in an onClick it didn't work either.

Upvotes: 2

Views: 1876

Answers (1)

Zack Matthews
Zack Matthews

Reputation: 409

The best way to do this is through SharedPreferences. SharedPreferences will write your data to a private file in a key/value within your app's apk that will persist even you turn your device off.

You can initialize SharedPreferences in onCreate like so: SharedPreferences sharedPreferences = getSharedPreferences(getPackageName(), MODE_PRIVATE).

To store a value simply call: sharedPreferences.edit().putString("myKey", stringValue).commit();

To retrieve that value anywhere from your application, initialize SharedPreferences, and then use the following code: String myData = sharedPreferences.getString("myKey");

Let me know if that helps!

EDIT: You may also want to look into getting a result from your Intent. See Getting a Result from an Activity. Use SharedPreferences if you need the boolean to be persistent (ie: written to storage and available on reboot), otherwise you may want to try onActivityResult.

Edit 2:

Try overriding onActivityResult in Activity A as so:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == RESULT_OK) {
            myBoolean = true;
        }
}

Then in Activity B try

setResult(Activity.RESULT_OK, getIntent()); finish();

This is the standard way of passing data to and from activities. Check out my link above about getting a result from an activity to delve a little deeper.

Upvotes: 2

Related Questions