Transferring data between two actions

I am trying to send and receive data between two different actions. I saw some other questions asked on this site, but not the question of maintaining the state of the first class.

For example, if I want to send the integer X to class B from class A, and then perform some operations with the integer X, and then send it back to class A, how can I do 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 get a 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 right, because I just want to go back to Activity A and get the data from Activity B after the action is completed (maybe the button in Activity B starts the operation with the received data and then sends it back to Activity?)

+5
source share
2 answers

In the first action:

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

Get data like:

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

After some operations In the second activity:

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

Process the result of FirstActivity :

 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 100) { if(resultCode == Activity.RESULT_OK){ String result=data.getStringExtra("result"); } } } 
+2
source

startActivityForResult() and onActivityResult() is your solution.

In ActivityA . Use startActivityForResult() -

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

And in your ActivityB, get your data sent from ActivityA . How -

 int value1 = getIntent().getExtras().getInt("Value1", 0); 

Do your operation and use setResult() to add the result of the operation and finish() . like-

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

And, of course, you need to implement onActivityResult() on ActivityA to get the returned data from ActivityB . How -

 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == requestCodeForOperation) { if(resultCode == Activity.RESULT_OK){ String result=data.getIntExtra("result", 0); } } } 
+2
source

Source: https://habr.com/ru/post/1272598/


All Articles