Transfer data between two activities

Jewgioh :

I am trying to send and receive data between two different activities. I have seen some other questions asked on this site but no question has dealt with preserving the state of the first class.

For example if I want to send an integer X to class B from class A then to do some operations on integer X and then send it back to class A, how does one go about doing this?

Is it as simple as the following code?

in Class A

 Intent i = new Intent(this, ActivityB.class);
 i.putExtra("Value1", 1);
 startActivity(i);

and to receive the response from Class B:

Bundle extras = getIntent().getExtras();
int value1 = extras.getint("Value1",0);

in Class B

Bundle extras = getIntent().getExtras();
int value1 = extras.getint("Value1",0);
//Do some operations on value1 such as maybe adding or subtracting
Intent i = new Intent(this, ActivityA.class);
i.putExtra("Value1", 1);
startActivity(i);

This does not seem correct as I simply want to switch back to Activity A and receive the data from Activity B once the action is completed (perhaps a button in Activity B commences operations on the received data and then sends it back to Activity A?)

Nilesh Deokar :

In First activity :

Intent i = new Intent(this, ActivityB.class);
i.putExtra("Value1", "1");
startActivityForResult(i, 100);

Receive data like :

Intent receivedIntent = getIntent();
if(receiveIntent!=null){
   String value1 = receiveIntent.getStringExtra("Value1");
}

After some operations In second activity:

Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(Activity.RESULT_OK,returnIntent);
finish();

Handle result in FirstActivity :

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

    if (requestCode == 100) {
        if(resultCode == Activity.RESULT_OK){
            String result=data.getStringExtra("result");
        }
    }
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=470521&siteId=1