Home » Android » android – How should I communicate between activities?

android – How should I communicate between activities?

Posted by: admin June 15, 2020 Leave a comment

Questions:

I have 3 buttons.
Button A, B, and C. Button A resides in Fragment. It starts intent (activity). Within the new activity button B and C reside. Button B says “NEW” while button C says “OK”.

What I want to do is after clicking button B (“NEW”) the intent should hold that button until the user hits button C (“OK”) where the activity should destroy itself and go back to fragment where there is now a new button called (“NEW”).

What are some easy ways to do this? And should I save this with sqlite if I want the app to remember the newly created button so that it’s not lost upon onDestroy?

I’m not very proficient within Android so hopefully someone can put it in laymans terms or point to an example.

How to&Answers:

Use Bundle please read sth more about it. http://developer.android.com/reference/android/os/Bundle.html

1) Use the Bundle from the Intent:

Intent mIntent = new Intent(this, Example.class);
Bundle extras = mIntent.getExtras();
extras.putString(key, value);

2) Create a new Bundle

Intent mIntent = new Intent(this, Example.class);
Bundle mBundle = new Bundle();
mBundle.extras.putString(key, value);
mIntent.putExtras(mBundle);

3) Use the putExtra() shortcut method of the Intent

Intent mIntent = new Intent(this, Example.class);
mIntent.putExtra(key, value);

Then, in the launched Activity, you would read them via:

String value = getIntent().getExtras().getString(key);

This is the proper way to do that. Another way is SharedPreferences. http://developer.android.com/training/basics/data-storage/shared-preferences.html