Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I communicate between activities? [duplicate]

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.

like image 681
Carl Avatar asked Jan 27 '14 22:01

Carl


People also ask

How do you communicate between activity and activity?

Communicating between activities It's very easy, as follows: Intent intent = new Intent(Activity1. this, Activity2. class);

Why two fragments should never communicate directly?

Two Fragments should never communicate directly. The reason for this is that Fragment s are fluid & dynamic UI components that may fade in and out of view. Only the hosting Activity is capable of determining if a Fragment is added to the UI or has been detached from it.

What is an intent in Java?

An intent is to perform an action on the screen. It is mostly used to start activity, send broadcast receiver,start services and send message between two activities. There are two intents available in android as Implicit Intents and Explicit Intents. Here is a sample example to start new activity with old activity.


1 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

like image 198
RMachnik Avatar answered Sep 18 '22 06:09

RMachnik