Send data from one operation to another without starting it

If I have two actions Activity1 and Activity2, and I want to send data from Activity1 to Activity2 without Start Activity2

I know if I want to start Activity2. I use this code in Activity1.java

Intent intent ;
Bundle bundle = new Bundle();

bundle.putString(BG_SELECT, hexColor);

intent = new Intent(getApplicationContext(), Activity2.class);

intent.putExtras(bundle);

// this is to start but I want just refresh Activity2 not start it
startActivityForResult(intent, uniqueNo);

and in Activity2.java

bundle = getIntent().getExtras();

if (bundle != null) {
   bgColor = bundle.getString(SebhaActivity.BG_SELECT);
   System.out.println("in Activity2, selected BG: "+bgColor);

}

How to update Activity2 to find data in it without starting? Thanks at Advance.

+5
source share
5 answers

if the next action (where you need the data, Activity2 ie) does not start here, you can save the data in SharedPreferences in Activity 1 and access it in Activity2 when you get there

+1
source

LocalBroadcastManager. , Activity1 - Activity2, - .

# Activity1

Intent intent = new Intent("INTENT_NAME").putExtra(BG_SELECT, hexColor);
LocalBroadcastManager.getInstance(Activity1.this).sendBroadcast(intent);

Activity2 , , onCreate, BroadcastReceiver, :

# Activity2

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, new IntentFilter("INTENT_NAME"));
}

mReceiver BG_SELECT

# Activity2

private BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String receivedHexColor = intent.getStringExtra(BG_SELECT);
    }
};
+4

,

.

  public class Datas {
  public static String name;
  }

.

Data  mData = new Data();
String str = mData.name
+2

, .

Shared Preferences , . "".

+1

, SharedPreferences .

SharedPreferences is application specific, that is, data is lost by doing one of the following: PREFS_NAME is the name of the file. mode is the mode of operation. editor.commit () is used to save changes to general settings

Your code is as follows

In the first event, Where do you share data from?

  SharedPreferences preferences=getSharedPreferences("PhoneBook",MODE_PRIVATE);
    SharedPreferences.Editor editor=preferences.edit();

    editor.putInt("registration_id",c.getInt(c.getColumnIndex("db_regiser_id")));
    editor.putBoolean("IsLogin",true);
    editor.commit();

In Second Activity, get data like this

SharedPreferences preferences=getSharedPreferences("PhoneBook",MODE_PRIVATE);
 int registration_id = preferences.getInt("registration_id", 0);

Using SharedPreferences is completely safe.

Also visit

https://developer.android.com/training/data-storage/shared-preferences.html

Hope this will be helpful.

+1
source

All Articles