Passing data via intent in android - android

I have 5 activities, say activity A,B,C,D and E.
Each activity has two buttons yes & no,buttons have the data which I want to pass to activity E only.
I need to do following things:
--> When user press yes/no button of A_activity, the user move to B_activity but data passed to activity E via intent.
Similarly at activity B user press yes/no button, user will move to activity C but data passed to activity E and so on.
I have done lot of search but couldn't find solution is there any way to do this.

Use SharedPreferences class to pass the data:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("key", "Value");
editor.commit();
Then in the Activity E:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
String value = sharedPref.getString("key", defaultValue);
Hope this helps.

You can indeed pass data back through an intent to an Activity's onActivityResult()
Activity E starting Activity A
final int RESULT_FOR_CLASS_DATA = 12; // pick a number to use
String returnedData;
Intent intent = new Intent(this, ActivityA.class);
startActivityForResult(intent, RESULT_FOR_CLASS_DATA);
Example in A (started from E)
Intent data = new Intent();
data.putExtra("ReturnData", dataToReturn);
setResult(RESULT_OK, data);
finish(); // returning to Activity E
Example in onActivityResult() of E
if (requestCode == RESULT_FOR_CLASS_DATA) {
returnedData = data.getStringExtra("ReturnData"));
}
There's a wide variety of ways to accomplish moving data around though so this is just one example.
To recommend an alternative, use Handler instead of this. Supposed that since the return Activity is paused, handler might require setting data in a separate class or global static variables, etc. and retrieved on Activity restart or something. So its possible to do with little to no code duplication in any class. Just retrieve and use. Whereas Intent requires code duplication in every class. It would also easily allow going from any Activity to any Activity like A->B->E->C instead of requiring E->A->E->B. Just something to think about.

Related

I want to have a variable that shows on the activity 1, if the next activity 2 have already started

I have a few activities, on the Acivity 1 I set a variable active which is true.
Activity 1 => Activity 2 => come back to Activity 1
active=true => active=false => active=false
I got:
Activity 1:
public boolean active = false;
onCreate() {active = true;}
Intent i = new Intent(Activity1.this, Activity2.class);
startActivity(i);
This activity must work in the background.
Activity 2:
public boolean active = false;
Intent intent = new Intent(Activity2.this, Activity1.class);
intent.putExtra("active", active);
then I call method onBackPressed();
But when I come back Activity 1 appears and I obtain active = true:
onResume() and onRestart() here I have:
Intent intent = getIntent();
active = intent.getBooleanExtra("active", active);
When I tried to use
startActivityforResult() method from Activity 1 it doesn't move to the Activity 2 and it's still true.
May be its because I have a main layout in both activities and contents changes.
How to resolve this?
This answer could help you. In short: you can use SharedPreferences to save any variables for coming back to them later thru any activities.
SharedPreferences prefs = getSharedPreferences("preference_file_name", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("variable_key", variable);
editor.commit();
Additionally, even with startActivityForResult you can pass some data.
You can use shared preferences to store the variable as mentioned in above answer but we can do this without using shared preferences as well.
Create global variable active and assign it to True.
Use startActivityforResult() to swittch between Activity 1 => Activity 2
on BackPressed(), OnActivityResult in Activity1 change the global variable value to false. And due to startActivityforResult, Activity1 was in Pause state and on coming back to Activity 1 onResume will be called which won't replace the Global variable.

Navigating from Activity A->B->C - How to pass data from C to A in onBackPressed()?

From Activity A call Activity B
from B to C and while calling Activity C
I call finish for Activity B, (to clear from stack history Activity B)
and in Activity B onBackPressed(), I pass data via setResult() from Activity B to Activity A, but in Activity A the data is null and resultCode 0.
How to get data from Activity B in Activity A?
Don't call finish() from B when opening C. Instead, call C with startActivityforResult() and then pass the data back through B when onActivityResult() in B is triggered. Something like:
ActivityB {
onCreate(Bundle) {
startActivityForResult(ActivityC, 0);
}
onActivityResult(int, int, Intent){
setResult(resultCode, data);
finish();
}
}
Edit:
Apparently adding the flag Intent.FLAG_ACTIVITY_FORWARD_RESULT when calling B should actually achieve your desired result as well.
Learn somethin' new every day...
Where're multiple ways of doing this:
Store the data from Activity C to Application's object and just read it in Activity A:
((MySuperApplication) getApplication()).setMyData(..);
Pass it as Activity Result
Store data to SharedPreference in Activity C and read it in Activity A. If it's a complex data structure - I'd suggest to use gsonto serialize object and store it as a string and then deserialize it in Activity A
Choose the one you like the most.
use shared preference
C ACTIVITY
SharedPreferences sf = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sf.edit();
editor.putString(key, value);
editor.commit();
A ACTIVITY
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String savedPref = sharedPreferences.getString(key, "");
mOutputView.setText(savedPref);

Pass parameters without open activity

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!
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","");
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

Android : SharedPreferences not updated

My 2 android applications communicate throught a AIDL file :
Application A <== AIDL ==> Application B (service)
Application A calls methods of Application B (service) that returns some JSON information. However, If user is not logged in application B, null is returned.
(service in application B)
//first : get info
SharedPreferences mPrefs = getSharedPreferences(Consts.SP_NAME, MODE_PRIVATE);
String userId = mPrefs.getString(Consts.PREFS_USER_ID, "");
String userPass = mPrefs.getString(Consts.PREFS_USER_PASS, "");
//then check is valid (remote server)
if (dao.exist (userId, userPass)){
return "MY_JSON_INFO" ;
}else{
return false;
}
If null is returned, "login" activity in Application B is launched from Application A.
(Aplication A)
if(json == null){
Intent intent = new Intent("jp.app.LOGIN_ACTIVITY");
startActivity(intent);
}
User log in (Application B), data are saved in SharedPreferences (Application B) and activity is closed (back to Application A).
SharedPreferences mPrefs = a.getSharedPreferences(Consts.SP_NAME, MODE_PRIVATE);
Editor prefsEditor = mPrefs.edit();
prefsEditor.putString(Consts.PREFS_USER_ID, id);
prefsEditor.putString(Consts.PREFS_USER_PASS, pass);
prefsEditor.commit();
When re-trying to call methods of the Application B, login information saved few seconds ago are not available and null is returned.
I have tried without success with prefsEditor.apply() .
If I restart application B, login data will be loaded....
Please let me know if further information are needed.
Thank you
After a long struggle, I have at last managed to get my updated preferences.
When calling getSharedPreferences, I use Context.MODE_MULTI_PROCESS flag.
MODE_MULTI_PROCESS
Thank you.
Since you need to access the shared preference of other application.
You should try :: Android: Retrieving shared preferences of other application
By reading your comment i can give you a quick solution:
The easier way is to simply terminate your activity (A) before calling the login activity inside your service.
if(json == null){
Intent intent = new Intent("jp.app.LOGIN_ACTIVITY");
startActivity(intent);
this.finish();
}
So that, when you fill in the login form and call back the activity A it will read the new shared preferences!

How to pass data between activities

My question is how to pass data like String between two activities. Normally I would do this:
Intent i = new Intent(thisclass.this,NextClass.class);
Bundle b = new Bundle();
i.putExtras(b);
b.putString("Name",Name);
StartActivity(i);
But this would make my Activity close and will open the next Activity, no? Is there any way that I can only pass data without opening the other activity?
I think you are looking for something with the SharedPreference see the documentation : SharedPreference
if it is what are looking for.
Try this:
Global:
private SharedPreferences pref;
onCreate:
pref = this.getSharedPreferences("SharedPreference", Context.MODE_PRIVATE);
The place where you gonna save your data:
String data = "yourData"
pref.edit().putString("myData", data).commit();
And the other Activity:
Global:
private SharedPreferences pref;
onCreate:
pref = this.getSharedPreferences("SharedPreference", Context.MODE_PRIVATE);
The place where you gonna take your data:
String dataFromFristActivity = pref.getString("myData", null);
Your calling activity does not close but is paused.
I am with #Egor on this. The called activity does not yet exist. Unless u are trying to send data between activities in two different apps. That is a whole different can of worms.

Categories

Resources