1

Here is what I want:

  1. In Activity No.1. some variables receive values (variable A and B)
  2. Here the user launches Activity No.2. and sets a variable (variable C)
  3. User presses a button that takes him back to Activity No.1.
  4. Activity No.1. has now the value of all the three variables.

I can pass the variables to Activity No.2. with an intent and retrieve them there using a Bundle. But is it an appropriate way to open Activity No.1. by using basically the same lines that I used to start Activity No.2?

In Activity No.1:

Intent intent = new Intent(getApplicationContext(), ActivityNo2.class);
intent.putExtra("date", date);
intent.putExtra("filename", filename);
startActivity(intent);

In Activity No.2:

Bundle bundle = getIntent().getExtras();
String date = bundle.getString("date");
String filename = bundle.getString("filename");
String variableC = "somevalue";

What's the best way to return to Activity No.1. with the new variable?

erdomester
  • 11,789
  • 32
  • 132
  • 234

2 Answers2

0

Could you have a variable in class A (Activity 1), get an instance of class A(from class B[this is the singleton design pattern]) and set the value of that variable via a setMethod?

Cen92
  • 171
  • 1
  • 13
0

What you are doing would work but there is a better way. The way you are doing it is just creating more possible errors. And Android provides a solution for this type of occasion.

You can use startActivityForResult() to go to Activity 2. This will allow you to send a result back to Activity 1 with variable C.

As long as you have given the variables the correct scope in Activity 1 they will still be there when you return to onActivityResult().

This answer gives a little more explanation on how to use it.

Community
  • 1
  • 1
codeMagic
  • 44,549
  • 13
  • 77
  • 93
  • I had a hunch that this would be the solution, just wasn't sure about it then I got distracted by the world of startActivity. – erdomester Apr 08 '14 at 21:51