Best way to pass objects from one activity to another - android

I have read about global static technique in which we create a class with static fields which can be accessed in any activity. Is there any other way to pass large data sets like ArrayList<Drawables> or HashMaps ?
I have also read about Serializable but have no idea how to use it. Any example code is welcome...

Intent intent = new Intent(getBaseContext(), NextActivity.class);
intent.putExtra("arraylist", new ArrayList<String>());
If your ArrayList contains another Object that you have created yourself, for instance Friend.class, you can implement the Friend.class with Serializable and then:
Intent intent = new Intent(getBaseContext(), NextActivity.class);
intent.putExtra("friendlist", new ArrayList<Friend>());
And for receiving it on NextActivity.class:
Bundle extras = getIntent().getExtras();
if(extras != null){
ArrayList<Friend> friends = extras.getSerializable("friendlist");
}
Well, instead of passing an empty ArrayList, you'll have to put values into the ArrayList and then pass it, but you get the idea.

You should pack your information into the Intent object you create to call your next Activity. There is a extras Bundle object.
You can use either the Serializable interface or the Android-specific Parcelable interface to pass non-primitive objects.
The Android Developer site has a handy Notepad Tutorial with an example of putting information into the intent.
From their tutorial:
super.onListItemClick(l, v, position, id);
Cursor c = mNotesCursor;
c.moveToPosition(position);
Intent i = new Intent(this, NoteEdit.class);
i.putExtra(NotesDbAdapter.KEY_ROWID, id);
i.putExtra(NotesDbAdapter.KEY_TITLE, c.getString(
c.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)));
i.putExtra(NotesDbAdapter.KEY_BODY, c.getString(
c.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY)));
startActivityForResult(i, ACTIVITY_EDIT);

As long as you stay in the same application( speak: same JVM ) you do not need to bother with intents, parcelables, serialisation etc - all objects are on same heap and can be passed via singletons, DI containers like roboguice or whatever you see fit.
If you like to push data to an other application, best technique would be to pass it as JSON/XML serialized stuff.

Passing Hashmap is pretty simple, All Collections objects implement Serializable (sp?) interface which means they can be passed as Extras inside Intent
Use putExtra(String key, Serializable obj) to insert the HashMap and on the other acitivity use getIntent().getSerializableExtra(String key), You will need to Cast the return value as a HashMap though.

Related

Android putSerializable vs putString

i have a POJO object defined like this:
public class MYPOJO implements Serializable {
int myint;
String mystring;
}
then when im passing the info to an activity i do this:
Intent i = new Intent(this, WearActivity.class);
Bundle b = new Bundle();
MYPojo pojo = new MYPojo();
pojo.mystring="cool";
b.putSerializable("someString", pojo.mystring);//this line is my issue
i.putExtra("coolBundle",b);
startActivityForResult(i, 0);
and to read the 'someString' extra i do:
Bundle b2 = getIntent().getBundleExtra("coolBundle");
b2.getString("someString");
So now onto my question: is there really any difference if i do the following if if at the end im still calling for retrieval b2.getString("someString") :
b.putString("someString",pojo.mystring)
vs
b.putSerializable("someString",pojo.mystring) ?
In practice, there isn't a difference you'll see between passing a string, or passing a serializable string between activities, besides "efficiency" or possible usage of reflection/security. It might be more of a design and principle issue I have with passing a String in as "serializable". Essentially by passing in a String as Serializable, Android/Java will utilize the wrapper of String, which contains a data structure of char[] behind the scenes.
TLDR; If your POJO contained more data, I would highly recommend implementing Parcelable. More information can be found in this SO answer here. But if you are going to be passing just a String, I would use the putString/getString methods that Android provides for us.

How to send an array of objects to a new intent

I am trying to send an array of objects to a new intent, but the problem is that I don't know how to send the whole array at once. The method I managed to get it working is adding object by object, in a for loop, and in the second activity I have to get them one by one, something like this:
Main activity:
Intent newIntent = new Intent(mainA.this, secondA.class);
for(int i=0;i<numberOfObjects;i++)
newIntent.putExtra("object"+i,myObjects[i]);
newIntent.putExtra("length", x);
startActivity(newIntent);
Second activity:
Serializable n = getIntent().getSerializableExtra("length");
int x = Integer.parseInt(n.toString());
myObjects = new objClass[x];
for(int i=0;i<x;i++)
myObjects[i] = (objClass) getIntent().getSerializableExtra("object"+i);
Even if this method works, and gets me the right results, isn't there a better/faster/cleaner solution?(I searched a lot, but haven't found a better way, maybe I don't know what exactly to look for).
Make your object serializable and put all objects in a Arraylist and send it.ArrayList itself implements serializable.
Intent newIntent = new Intent(mainA.this, secondA.class);
newIntent.putExtra("list",listOfObjets);
startActivity(newIntent);
Second Activity:
ArrayList<YourObjects> list = (ArrayList<YourObjects>)getIntent().getSerializableExtra("list");
Hi you can try this as well.. Create setter getter class which will set and get your object. next create the array list of your setter getter class.next add all objects into arraylist using set method in for loop. next add that arraylist object into bundle using setArguments.
Same you can access that bundle using getArguments that's it.

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