Passing data using Intents - android

I have two activities, Activity A and Activity B. I pass objects from Activity A to Activity B using intents. When i make changes to the Object in Activity B the data changes does not get reflected in Activity A. Have i missed out on something?

You are missing the fact that when you pass Object O from Activity A to Activity B via intents, activity B receives a COPY of object O. The way things work is that The object O gets serialized (converted to a sequence of bytes) and that sequence of bytes is then passed to Activity B. Then activity B recreates a copy of object O at the moment it was serialized. Any changes to the original object after it was serialized are not reflected in it's copy.
If both activities are part of the same application then just use a static field (or singleton) to communicate between them.

If you are passing a String, then it will not change since they are immutable.
Edit: See below for an alternative to Intent extras.

If you wish to use the architecture of passing immutable objects in messages you can create an immutable serializable data class. Pass an immutable instance of the data class in the intent using startActivityForResult. When the second activity is completed, send a different instance of the same immutable data class back to the first activity where it is trapped in onActivityResult. So in code, given an immutable class PasswordState.java with public final fields.
public final class PasswordState implements Serializable {
Create an instance of this immutable class and send it to the second activity as in:
private void launchManagePassword() {
Intent i= new Intent(this, ManagePassword.class); // no param constructor
PasswordState outState= new PasswordState(lengthKey,
timeExpire,
isValidKey,
timeoutType,
password,
model.getIsHashPassword(),
model.getMinimumPasswordLength()); // NOT minimumHashedPasswordLength
Bundle b= new Bundle();
b.putSerializable("jalcomputing.confusetext.PasswordState", outState);
i.putExtras(b);
startActivityForResult(i,REQUEST_MANAGE_PASSWORD); // used for callback
}
The second activity returns a new object when it is done.
PasswordState outPasswordState= new PasswordState(lengthKey,
timeExpire,
isValidKey,
timeoutType,
password,
isHashPassword,
minimumPasswordLength);
Bundle b= new Bundle();
b.putSerializable("jalcomputing.confusetext.PasswordState", outPasswordState);
getIntent().putExtras(b);
setResult(RESULT_OK,getIntent()); // call home with data on success only
finish(); // go back <=== EXITS Here
Where it is trapped in Activity one.
// ON_ACTIVITY_RESULT used for callback from ManageKeys.java
protected void onActivityResult(int request, int result, Intent data)
{
switch (request){
case REQUEST_MANAGE_PASSWORD:
if (result == RESULT_OK) { // Success. New password.
try {
PasswordState inMessage= (PasswordState)data.getSerializableExtra("jalcomputing.confusetext.PasswordState");
password= inMessage.password;
timeExpire= inMessage.timeExpire;
isValidKey= true;
writeToPrefs(); // support first launch and incoming tagged sms, save pw
}
catch(Exception e){ // data == null, extras == null
password= "";
isValidKey= false;
timeExpire= PasswordState.LONG_YEAR_MILLIS;
Log.d(Utilities.TAG,"FailedToGetResult",e); // will be stripped at runtime
}
...
break;
}
}
When you are done prototyping and the data objects are stable, you can refactor the code to use parcels instead of serializing objects. Since a copy is being sent between activities using serialization, it could be argued that the use of an immutable object is overkill. Using a mutable object and serializing a mutable object to and from the second activity would simplify the implementation.
Hope that helps.
JAL

Related

How to retain data between activiites

I have several Activities in a program. Lets say, activities A, B and C.
Activity A is the main activity in this context. It contains object X, that must be accessible for all other activities (Activities: B and C).
Activity A will start activity B and then B will start С. After that both activities A and B are in the background and can be killed by the OS. How should I pass object X to activities B and C in order to be sure that object X will not be killed when A&B are killed?
Why don't you can create your X Object with SingleTon ? You can keep it alive as long as you want and you can get the same Instance from where ever you want.
public class TestObject {
private static TestObject testObjectInstance;
/* put you data here */
private TestObject() {
}
public TestObject getTestObjectInstance() {
if (testObjectInstance != null) {
return testObjectInstance;
} else {
testObjectInstance = new TestObject();
return testObjectInstance;
}
}
public TestObject createNewTestObjectInstance() {
testObjectInstance = new TestObject();
return testObjectInstance;
}
}
The best way will be to save X value in Shared Preferences.The Value of X will be retained even your A and B activities are killed.
Check this Link for How to use Shared Preferences:
How to use SharedPreferences in Android to store, fetch and edit values
There are three possible ways:
Two of them were mentioned here.
Via SharedPreferences. But remember that the SharedPreferences retain the value when the application is closed. This is the best solution if you want the value to be "permanent" on your application.
Creating a singleton object. This is the best solution if you want to manipulate the object in all activities but don't want to save it for another runs.
Sending the data via extras. This is the best solution if you only want the VALUE of the object and don't want to manipulate it.
try the putExtra() function in Intent
You can only use it for primitives.
If your X is contains only primitives, you may write a function in X,public Intent fillIntentWithX(Intent intent) which take the intent object as argument, and fill the intent object with the primitives in X, and return the intent object.
similarly, write another function in X, public X getXFromIntent(Intent intent) which takes an intent as an argument, extracts the primitives residing in it to form a new object X, and return it.
use fillIntentWithX() to fill the intent, which launches B, with the
object X's properties.
use getXFromIntent() to extract X out in
activity B, and so on.

What does bundle mean in Android? [duplicate]

This question already has answers here:
What is a "bundle" in an Android application
(12 answers)
Closed 7 years ago.
I am new to android application development, and can't understand what does bundle actually do for us.
Can anyone explain it for me?
I am new to android application development and can't understand what
does bundle actually do for us. Can anyone explain it for me?
In my own words you can image it like a MAP that stores primitive datatypes and objects as couple key-value
Bundle is most often used for passing data through various Activities. Provides putType() and getType() methods for storing and retrieving data from it.
Also Bundle as parameter of onCreate() Activity's life-cycle method can be used when you want to save data when device orientation is changed (in this case activity is destroyed and created again with non null parameter as Bundle).
More about Bundle at its methods you can read reference at developer.android.com where you should start and then make some demo applications to get experience.
Demonstration examples of usage:
Passing primitive datatypes through Activities:
Intent i = new Intent(ActivityContext, TargetActivity.class);
Bundle dataMap = new Bundle();
dataMap.putString("key", "value");
dataMap.putInt("key", 1);
i.putExtras(dataMap);
startActivity(i);
Passing List of values through Activities:
Bundle dataMap = new Bundle();
ArrayList<String> s = new ArrayList<String>();
s.add("Hello");
dataMap.putStringArrayList("key", s); // also Integer and CharSequence
i.putExtras(dataMap);
startActivity(i);
Passing Serialized objects through Activities:
public class Foo implements Serializable {
private static final long serialVersionUID = 1L;
private ArrayList<FooObject> foos;
public Foo(ArrayList<FooObject> foos) {
this.foos = foos;
}
public ArrayList<FooObject> getFoos() {
return this.foos;
}
}
public class FooObject implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
public FooObject(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
Then:
Bundle dataMap = new Bundle();
ArrayList<FooObject> foos = new ArrayList<FooObject>();
foos.add(new FooObject(1));
dataMap.putSerializable("key", new Foo(foos));
Pass Parcelable objects through Activities:
There is much more code so here is article how to do it:
Parcel data to pass between Activities using Parcelable classes
How to retrieve data in target Activity:
There is one magic method: getIntent() that returns Intent (if there are any data also with extended data) that started Activity from there method is called.
So:
Bundle dataFromIntent = getIntent().getExtras();
if (dataFromIntent != null) {
String stringValue = dataFromIntent.getString("key");
int intValue = dataFromIntent.getInt("key");
Foo fooObject = (Foo) dataFromIntent.getSerializable("key");
// getSerializble returns Serializable so we need to cast to appropriate object.
ArrayList<String> stringArray = dataFromIntent.getStringArrayList("key");
}
Usage of Bundle as parameter of onCreate() method:
You are storing data in onSaveInstanceState() method as below:
#Override
public void onSaveInstanceState(Bundle map) {
map.putString("key", "value");
map.putInt("key", 1);
}
And restore them in onCreate() method (in this case is Bundle as parameter not null) as below:
#Override
public void onCreate(Bundle savedInstanceState) {
if (savedInstanceState != null) {
String stringValue = savedInstanceState.getString("key");
int intValue = savedInstanceState.getString("key");
}
...
}
Note: You can restore data also in onRestoreInstanceState() method but it's not common (its called after onStart() method and onCreate() is called before).
In general english: "It is a collection of things, or a quantity of material, tied or wrapped up together."
same way in Android "It is a collection of keys and its values, which are used to store some sort of data in it."
Bundle is generally used for passing data between various component. Bundle class which can be retrieved from the intent via the getExtras() method.
You can also add data directly to the Bundle via the overloaded putExtra() methods of the Intent objects. Extras are key/value pairs, the key is always of type String. As value you can use the primitive data types.
The receiving component can access this information via the getAction() and getData() methods on the Intent object. This Intent object can be retrieved via the getIntent() method. And
the component which receives the intent can use the getIntent().getExtras() method call to get the extra data.
MainActivity
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
Bundle bundle = new Bundle();
bundle.putString(“Key“, myValue);
intent.putExtras(bundle);
startActivity(intent);
SecondActivity
Bundle bundle = getIntent().getExtras();
String myValue= bundle.getString(“key“);
A collection of things, or a quantity of material, tied or wrapped up together. it is the dictionary meaning...By the same Bundle is a collection of data. The data may be of any type i.e String, int,float , boolean and any serializable data. We can share& save the data of one Activity to another using the bundle Bundle.
Consider it as a Bundle of data, used while passing data from one Activity to another.
The documentation defines it as
"A mapping from String values to various Parcelable types."
You can put data inside the Bundle and then pass this Bundle across several activities. This is handy because you don't need to pass individual data. You put all the data in the Bundle and then just pass the Bundle, instead of sending the data individually.
It's literally a bundle of things; information: You put stuff in there (Strings, Integers, etc), and you pass them as a single parameter (the bundle) when use an intent for instance.
Then your target (activity) can get them out again and read the ID, mode, setting etc.
A mapping from String values to various Parcelable types.Click here
Example:
Intent mIntent = new Intent(this, Example.class);
Bundle mBundle = new Bundle();
mBundle.extras.putString(key, value);
mIntent.putExtras(mBundle);
Send value from one activity to another activity.

How can i pass a list of objects (any object), through bundle, from activity A to Activity B?

This is on the android platform, i have a list of objects of type (FitItem), and i want pass the list from my activity A to another activity B, and on the activity B i want get the list of objects again
Intent yourIntent = new Intent(activityA.this, activityB.class);
Bundle yourBundle = new Bundle();
yourBundle.putString("name", value);
yourIntent.putExtras(yourBundle);
startActivity(yourIntent);
And you get the value in the next Activity (in your onCreate()):
Bundle yourBundle = getIntent().getExtras();
String s = yourBundle.getString("name");
This example is passing a String, but you should be able to grasp how to use it for other objects.
For custom classes:
You will have to have your FitItem class implements Parcelable.
Then in Activity A, from an Intent object, use putParcelableArrayListExtra to pass the list of FitItem to Activity B and in your Activity B, use getParcelableArrayListExtra to retrieve the list of FitItem
If you want to pass list of String, Integer, Float ..., refer to bschultz post
You must serialize your object.
"Seriawhat?"
Ok, first things first: What is object serialization?
"Got it, but how do I do that?"
You can use Parcelable (more code, but faster) or Serializable (less code, but slower). Parcelable vs Serializable.
"Save me some time, show me the code!"
Ok, if you'll use Parcelable, see this.
And if you'll use Serializable, see this and/or this.
Hope that helps!
If they're if the object is serializable, just add them as extras to the intent. I think something like this:
// in Activity A, when starting Activity B
Intent i = new Intent(this, ActivityB.class);
i.putExra("fitItemList", fitItemList);
startActivity(i);
// in Activity B (onCreate)
ArrayList<FitItem> fitItemList = savedInstanceState.getSerializableExtra("fitItemList");
edit:
Just like bschultz already posted :)
Implements Serializable in model class. Then you can pass model class using bundle/intent.

How to pass object to an activity?

I have two activities, NewTransferMyOwn.java and FromAccount.java
When I go from NewTransferMyOwn.java to FromAccount.java, I do write code as following
Intent i = new Intent(NewTransferMyOwn.this, FromAccount.class);
startActivityForResult(i, FROM_ACCOUNT);
When I do come back from FromAccount.java to NewTransferMyOwn.java, then I want to pass a complete object of class Statement
I do write code as
Statement st = ItemArray.get(arg2);//ItemArray is ArrayList<Statement>, arg2 is int
Intent intent = new Intent(FromAccount.this,NewTransferMyOwn.class).putExtra("myCustomerObj",st);
I do get error as following on putExtra,
Change to 'getIntExtra'
as I do, there is again casting st to int, what is issue over here, how can I pass Statement object towards back to acitivity?
You can also implement your custom class by Serializable and pass the custom Object,
public class MyCustomClass implements Serializable
{
// getter and setters
}
And then pass the Custom Object with the Intent.
intent.putExtra("myobj",customObj);
To retrieve your Object
Custom custom = (Custom) data.getSerializableExtra("myobj");
UPDATE:
To pass your custom Object to the previous Activity while you are using startActivityForResult
Intent data = new Intent();
Custom value = new Custom();
value.setName("StackOverflow");
data.putExtra("myobj", value);
setResult(Activity.RESULT_OK, data);
finish();
To retrieve the custom Object on the Previous Activity
if(requestCode == MyRequestCode){
if(resultCode == Activity.RESULT_OK){
Custom custom = (Custom) data.getSerializableExtra("myobj");
Log.d("My data", custom.getName()) ;
finish();
}
}
You can't pass arbitrary objects between activities. The only data you can pass as extras/in a bundle are either fundamental types or Parcelable objects.
And Parcelables are basically objects that can be serialized/deserialized to/from a string.
You can also consider passing only the URI refering to the content and re-fetching it in the other activity.

Transfer data from one Activity to Another Activity Using Intents

I would like to be able to transfer data from one activity to another activity. How can this be done?
Through the below code we can send the values between activities
use the below code in parent activity
Intent myintent=new Intent(Info.this, GraphDiag.class).putExtra("<StringName>", value);
startActivity(myintent);
use the below code in child activity
String s= getIntent().getStringExtra(<StringName>);
There are couple of ways by which you can access variables or object in other classes or Activity.
A. Database
B. shared preferences.
C. Object serialization.
D. A class which can hold common data can be named as Common Utilities it depends on you.
E. Passing data through Intents and Parcelable Interface.
It depend upon your project needs.
A. Database
SQLite is an Open Source Database which is embedded into Android. SQLite supports standard relational database features like SQL syntax, transactions and prepared statements.
Tutorials -- http://www.vogella.com/articles/AndroidSQLite/article.html
B. Shared Preferences
Suppose you want to store username. So there will be now two thing a Key Username, Value Value.
How to store
// Create object of SharedPreferences.
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
//now get Editor
SharedPreferences.Editor editor = sharedPref.edit();
//put your value
editor.putString("userName", "stackoverlow");
//commits your edits
editor.commit();
Using putString(),putBoolean(),putInt(),putFloat(),putLong() you can save your desired dtatype.
How to fetch
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
String userName = sharedPref.getString("userName", "Not Available");
http://developer.android.com/reference/android/content/SharedPreferences.html
C. Object Serialization
Object serlization is used if we want to save an object state to send it over network or you can use it for your purpose also.
Use java beans and store in it as one of his fields and use getters and setter for that
JavaBeans are Java classes that have properties. Think of
properties as private instance variables. Since they're private, the only way
they can be accessed from outside of their class is through methods in the class. The
methods that change a property's value are called setter methods, and the methods
that retrieve a property's value are called getter methods.
public class VariableStorage implements Serializable {
private String inString ;
public String getInString() {
return inString;
}
public void setInString(String inString) {
this.inString = inString;
}
}
Set the variable in you mail method by using
VariableStorage variableStorage = new VariableStorage();
variableStorage.setInString(inString);
Then use object Serialzation to serialize this object and in your other class deserialize this object.
In serialization an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object.
After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.
If you want tutorial for this refer this link
http://javawithswaranga.blogspot.in/2011/08/serialization-in-java.html
Get variable in other classes
D. CommonUtilities
You can make a class by your self which can contain common data which you frequently need in your project.
Sample
public class CommonUtilities {
public static String className = "CommonUtilities";
}
E. Passing Data through Intents
Please refer this tutorial for this option of passing data.
http://shri.blog.kraya.co.uk/2010/04/26/android-parcel-data-to-pass-between-activities-using-parcelable-classes/
When you passing data from one activity to another activity perform like this
In Parent activity:
startActivity(new Intent(presentActivity.this, NextActivity.class).putExtra("KEY_StringName",ValueData));
or like shown below in Parent activity
Intent intent = new Intent(presentActivity.this,NextActivity.class);
intent.putExtra("KEY_StringName", name);
intent.putExtra("KEY_StringName1", name1);
startActivity(intent);
In child Activity perform as shown below
TextView tv = ((TextView)findViewById(R.id.textViewID))
tv.setText(getIntent().getStringExtra("KEY_StringName"));
or do like shown below in child Activity
TextView tv = ((TextView)findViewById(R.id.textViewID));
TextView tv1 = ((TextView)findViewById(R.id.textViewID1))
/* Get values from Intent */
Intent intent = getIntent();
String name = intent.getStringExtra("KEY_StringName");
String name1 = intent.getStringExtra("KEY_StringName1");
tv.setText(name);
tv.setText(name1);
Passing data from one activity to other in android
Intent intent = new Intent(context, YourActivityClass.class);
intent.putExtra(KEY, <your value here>);
startActivity(intent);
Retrieving bundle data from android activity
Intent intent = getIntent();
if (intent!=null) {
String stringData= intent.getStringExtra(KEY);
int numberData = intent.getIntExtra(KEY, defaultValue);
boolean booleanData = intent.getBooleanExtra(KEY, defaultValue);
char charData = intent.getCharExtra(KEY, defaultValue); }
Hopefully you will find the answer from here Send Data to Another Activity - Simple Android Login
You just have to send extras while calling your intent
like this:
Intent intent = new Intent(getApplicationContext(), SecondActivity.class); intent.putExtra("Variable Name","Value you want to pass"); startActivity(intent);
Now on the OnCreate method of your SecondActivity you can fetch the extras like this
If the value u sent was in "long"
long value = getIntent().getLongExtra("Variable Name which you sent as an extra", defaultValue(you can give it anything));
If the value u sent was a "String"
String value = getIntent().getStringExtra("Variable Name which you sent as an extra");
If the value u sent was a "Boolean"
Boolean value = getIntent().getStringExtra("Variable Name which you sent as an extra",defaultValue);
Your Purpose
Suppose You want to Go From Activity A to Activity B.
So We Use an Intent to switch activity
the typical code Looks Like this -
In Activity A [A.class]
//// Create a New Intent object
Intent i = new Intent(getApplicationContext(), B.class);
/// add what you want to pass from activity A to Activity B
i.putExtra("key", "value");
/// start the intent
startActivity(i);
In Activity B [B.class]
And to Get the Data From the Child Activity
Intent i = getIntent();
if (i!=null) {
String stringData= i.getStringExtra("key");
}
This works best:
Through the below code we can send the values between activities
use the below code in parent activity(PARENT CLASS/ VALUE SENDING CLASS)
Intent myintent=new Intent(<PARENTCLASSNAMEHERE>.this,<TARGETCLASSNAMEHERE>.class).putExtra("<StringName>", value);
startActivity(myintent);
use the below code in child activity(TARGET CLASS/ACTIVITY)
String s= getIntent().getStringExtra(<StringName>);
Please see here that "StringName" is the name that the destination/child activity catches while "value" is the variable name, same as in parent/target/sending class.

Categories

Resources