0

I am novice programming on Android. I have one question, I have 2 activities. Firs I pass a parameter from the Activity A to the B like this:

Intent intent = new Intent(getBaseContext(), ActivityB.class);
intent.putExtra("ALMACEN_ANTES", almacen.getText().toString());
startActivity(intent);

And now in the activity B y get the extras. Later since the Activity B, I pass parameters to the A too. My question is, is it possible to pass parameters to another activity without doing Intent intent = new Intent(getBaseContext(), ActivityB.class) because I don´t want to open 2 times the same activity.

Thank you!

MilapTank
  • 9,988
  • 7
  • 38
  • 53
user3383415
  • 437
  • 1
  • 7
  • 22

2 Answers2

0

Yes . You can save the value using SharedPreferences

It will be stored in an internal xml file and you can save it and retrive whenever you want. It need not start the activity when value passing.

An example shows below

 SharedPreferences sharedpreferences;
  Editor editor = sharedpreferences.edit();
  editor.putString(Name, n);
  editor.putString(Phone, ph);
  editor.commit;

you can retrive this value from the activity where you need to access these values. It can be done by:

   SharedPreferences sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
  String name=sharedpreferences.getString("Name","");
  String ph=sharedpreferences.getString("Phone","");
user3506595
  • 129
  • 11
0

You want to update a value in the activity A , you mean? because if you don't open it why sending a value to it ?

you can share data between two activities by other ways. In your case the best one would be a Singleton class:

you create a class which is inheriting from Application and containing your data, and from every activity you can update you data or get it...

Your singleton class:

import android.app.Application;
public class MyApplication extends Application {
  private String data;
  public String getData() {return data;}
  public void setData(String data) {this.data = data;}
}

From activity B , you can set your data:

MyApplication app = (MyApplication) getApplicationContext();
app.setData(someData);

And teh Ativity A can have them like this:

MyApplication app = (MyApplication) getApplicationContext();
String data = app.getData();

See this answer

Community
  • 1
  • 1
ahmed_khan_89
  • 2,755
  • 26
  • 49