Zephyr
Zephyr

Reputation: 45

How to pass values between activity

I have created 3 activities: firstActivity, secondActivity, and thirdActivity.

  1. firstActivity is the main activity.
  2. secondActivity will work only if it receives an SMS, and it then sends the message to thirdActivity.
  3. thirdActivity converts the string values to double values, and then sends the double values to firstActivity.

I can send values from secondActivity to thirdActivity, but I don't know how to pass values ​​from thirdActivity to firstActivity. Please advise me on how I should do this.

Upvotes: 3

Views: 168

Answers (3)

Zephyr
Zephyr

Reputation: 45

Thank you for your help. Now I can pass values from thirdActivity to firstActivity, this is how I do.

ThirdActivity :

public class ThirdActivity extends Activity {

double value1, value2;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ...

    value1 = Double.parseDouble(value1FromSecondActivity);
    value2 = Double.parseDouble(value2FromSecondActivity);      

    Intent intent = new Intent(this, FirstActivity.class);
    intent.putExtra("Value1", value1);
    intent.putExtra("Value2", value2);
    startActivity(intent);
    finish();
    }
} 

FirstActivity :

public class FirstActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ...
}   

@Override
protected void onResume() {
    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        dValue1 = extras.getDouble("Value1");
        dValue2 = extras.getDouble("Value2");
        Toast.makeText(getBaseContext(), dValue1 + " : " + dValue2, Toast.LENGTH_SHORT).show();
    }
    else {
        Toast.makeText(getBaseContext(), "Null", Toast.LENGTH_SHORT).show();
    }
    super.onResume();
    }
}

Upvotes: 0

Bilthon
Bilthon

Reputation: 2511

Whenever you have an activity called for a result, like in this case you have thirdActivity you can always use the method startActivityForResult instead of just startActivity. Once thirdActivity has finished its processing and it wants to return the result value, it should call setResult and that's it.

The problem with this approach here is that you kind of have secondActivity in the middle. Is it really necessary?

Upvotes: 1

Pablo Santa Cruz
Pablo Santa Cruz

Reputation: 181450

There are several approaches to this.

One would be using a custom application class to store sort of "global values" for your entire application. That way, you would set the values in firstActivity and use them in thirdActivity.

Take a look at this SO question to learn how to store global state in Android applications.

Upvotes: 1

Related Questions