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.
Related
I'm trying to transfer ArrayList between activities, but nothing I've tried works as well.
This was my best shot, but this didn't work either.
I'm calling the external action here:
getComics getComicInfo = new getComics(charName, pageNum);
getComicInfo.execute();
getIntentData()
and here i'm trying to put data, but the problem is due the fact that this is an external action, so I can't shift through activits.
if(counter == comicInfoObject.length()){
Log.v("check arr length =>" , Integer.toString(comicList.size()));
Intent i = new Intent();
i.putExtra("comicArrayList", (ArrayList<Comics>)comicList);
}
and here i'm tring to retrive the data, but it doesn't get inside the "if"
public void getIntentData(){
Intent i = getIntent();
if(i != null && i.hasExtra("comicArrayList")){
comicList2 = i.getParcelableExtra("comicArrayList");
int size = comicList2.size();
}
}
first code is where I call an external class that using api and in the bottom line creates the arrayList
second code is inside the external class, where I'm trying to pass the arrayList with putExtra
third code is where i'm tring to retrive the data after getIntentData().
Pack at the sender Activity
intent.putParcelableArrayListExtra(<KEY>, ArrayList<Comics extends Parcelable> list);
startActivity(intent);
Extract at the receiver Activity
getIntent().getParcelableArrayListExtra(<KEY>);
You need make a Comics class that implements Parcelable, then use put ParcelableArrayListExtrato pass arraylist.
Here is a sample link for Pass data between activities implements Parcelable
However be careful if your array list too big, you could get intent exception, for this case you could think about a static reference to store your array list.
I have a Child Activity which is returning an ArrayList to Parent Activity
Child Activity
ArrayList<Users> selectedMembers = new ArrayList<Users>();
//And then
Intent returnIntent = new Intent();
returnIntent.putExtra("ArrayOfUsers",selectedMembers);
setResult(RESULT_OK,returnIntent);
finish();
Parent Activity
Now how to get this ArrayList<Users> on parent Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if (resultCode == RESULT_OK) {
//how to get ArrayList<Users> here
}
}
I did something like this but i gives error
selectedMembers.addAll((data.getParcelableArrayListExtra("ArrayOfUsers"));
error:
The method addAll(Collection<? extends Users>) in the type ArrayList<Users> is not applicable for the arguments (ArrayList<Parcelable>)
You are using different methods for serialization and deserialization. When you call returnIntent.putExtra actually this overloaded method in Intent class is called. So your list of users is actually treated as single Serializableobject. In this case putExtra at child side should be used in conjunction with getSerializableExtra getter at parent side.
If you want to use getParcelableArrayListExtra at parent side as getter method you should use it in conjunction with putParcelableArrayListExtra at child side and you Users class should be Parcelable.
Is your Users class implementing the Parcelable interface? If not, this is why you are getting the message.
The ArrayList class implements Serializable, and that is how it is being taken for when you add your array list to the intent.
In order to retrieve the array list, you have to retrieve the serializable object and cast it back to ArrayList in the following manner:
// Check that the result is successful and that the intent is valid (not null)
if ( resultCode == RESULT_OK && data != null ) {
ArrayList<Users> selectedMembers = (ArrayList<Users>) data.getSerializableExtra ( "ArrayOfUsers" );
// Your logic goes here ...
}
This casting process will trigger a warning in Eclipse IDE saying :
Type safety: Unchecked cast from Serializable to ArrayList < Users >
Do not worry about this, you can just ignore the warning or simply add the following statement before your method :
#SuppressWarnings("unchecked")
UPDATE :
The object that you are storing in the array list must be serializable too, meaning that your class should implement serializable, which in your case, the class Users should in the following manner :
class Users implements Serializable {
// ...
}
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.
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.
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