Intent putextra serializable object array - android

my problem is putextra method with serializable object array. I mean if i try bottom code it throws Caused by: java.io.NotSerializableException:
Here 's the code :
class Example implements Serializable
{
private int ID; // It has getters and setters and also other variables.
}
Intent inte=new Intent(this,OTHERCLASS.class);
Example[] examples=new Example[]; // It's just an example.
Bundle bundle = new Bundle();
bundle.putSerializable("Details", examples);
inte.putExtras(bundle);
startActivity(inte);
Thanks.

this is because you can't serialize a inner class without making its parent class serializable. Which in your case is your Activity. So simply create a new java file for your Example class

Although your class is serializable, an Array of items with your class (Example[]) is not serializable. Edit: Thanks #gomino for pointing out that this was wrong. I just assumed this was the reason for the problem without actually thinking about it.
Also, it would be more efficient to use a Parcelable instead. You can find a tutorial here.

Related

Can not cast an object to parcelable

I have an Intent service. In onHandleIntent I want to put an object of type List<Trends> to an Intent, so that I can send this Intent via sendBroadcast as shown in the code below.
The issue I am facing now is when I put the list object to a Bundle and cast it to Parcelable, I receive the below posted error.
My Code:
Intent intentBroadcast = new Intent();
Bundle bundleList = new Bundle();
bundleList.putParcelable("data", (Parcelable) this.mTrendsList); //java.util.ArrayList cannot be cast to android.os.Parcelable
intentBroadcast.putExtra(TwitterTrendsAPIService.CONST_INTENT_KEY, bundleList);
sendBroadcast(intentBroadcast);
The Error:
java.lang.ClassCastException: java.util.ArrayList cannot be cast to android.os.Parcelable
at com.example.pc_amr.twittertrendsnearlocation.services.TwitterTrendsAPIService.onHandleIntent(TwitterTrendsAPIService.java:86)
at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
at android.os.Handler.dispatchMessage(Handler.java:1
You can only put objects of classes that implement Parcelable.
For more info read this.
The putParcelable() method is being used wrong here. This method can be used to save a single object of a class that implements the Parcelable interface. To save an array, you need to use putParcelableArrayList() method.
If you need to pass an ArrayList then I'd go with implementing Parcelable

Send Data between Activities as done with fragment

I have a data of custom List type (finalHolder.data)
Earlier I had to send this data to a Fragment constructor it is working fine
Fragment fragment;
fragment = new RouteMap(finalHolder.data);
((Activity)getContext()).getFragmentManager().beginTransaction().replace(R.id.content_frame,fragment).commit();
The Fragment constructor code
public RouteMap() {
// Required empty public constructor
}
public RouteMap(MyListEntity data) {
this.data = data;
}
Activity constructor :
public Map() {
}
public Map(MyListEntity data) {
this.data = data;
}
But now I want this same data to reach a Activity (Map2)
I tried putExtra with intent but Intent but it doesnt work
In Short I want the "finalHolder.data" to be send to Activity constructor while calling it .
If it isnt possible then please suggest solution
Thanks
It is not recommended to use Activity constructor. To send data object to activity you can use Intent extras with Parcelable. For that you need to do the follow way.
Implement your data class from Parcelable
Ex: MyListEntity implements Parcelable
Override the following methods in your data class(MyListEntity) writeToParcel(), readFromParcel()
3.Implement the CREATOR class in your data class(MyListEntity)
Reference link for Parcelable example: passing object to activity
Send the data object using Intent as mentioned below
Intent i = new Intent(this,Activity(Map2).class);
i.putExtra("mylistdata",finalHolder.data);
startActivity(i);
And finally get the same data at your Activity(Map2) onCreate() method as mentioned below
MyListEntity listEntry = getIntent().getParcelableExtra("mylistdata");
Now your object is ready at your second activity.
Hope this will help for you.
To send an object in intent the object's class must be serializable so make your
MyListEntity implements serializable then use the Intent's putExtra(String name, Serializable value) and in the other activity use the intent's getSerializableExtra (String name) but don't forget to cast the returned value
One option could be letting your custom class implement the Serializable interface and then you can pass object instances in the intent extra using the putExtra(Serializable..) variant of the Intent#putExtra() method.
Your data should implement Serializable ie
MyListEntity implements Serializable
//Use this to send the data
intent.putExtra("MyClass", finalHolder.data);
// To retrieve object in second Activity
getIntent().getSerializableExtra("MyClass");
Regarding your Fragment: it is not smart to pass data via c-tor to fragments!
Use arguments mechanism:
Fragment f = new SomeFragment();
Bundle args = new Bundle();
args.putExtra("data", someData);
f.setArguments(args);
And retreive them:
getArguments().getParcelableExtra("data")
More info here.
But (to return to your question), for that, your data have to implement Serialisable (Java approach) or, by Google advised Parcelable (Android style)
More info about Parcelable here.
Implementing Parcelable interface can be boring and error prone, so some cool people created this: http://www.parcelabler.com/

When using an android bundle, why does a serialised stack deserialise as an ArrayList?

Serialisation:
Bundle activityArguments = new Bundle();
Stack<Class<? extends WizardStep>> wizardSteps = new Stack<Class<? extends WizardStep>>();
wizardSteps.push(CreateAlarmStep5View.class);
wizardSteps.push(CreateAlarmStep4View.class);
wizardSteps.push(CreateAlarmStep3View.class);
wizardSteps.push(CreateAlarmStep2View.class);
wizardSteps.push(CreateAlarmStep1View.class);
activityArguments.putSerializable("WizardSteps", wizardSteps);
Deserialisation:
Stack<Class<? extends WizardStep>> wizardSteps =
(Stack<Class<? extends WizardStep>>) getIntent().getExtras().getSerializable("WizardSteps");
Exception:
12-20 23:19:45.698: E/AndroidRuntime(12145): Caused by: java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.util.Stack
Its known bug. I surprise that it still exists.
Use generic container like:
public class SerializableHolder implements Serializable {
private Serializable content;
public Serializable get() {
return content;
}
public SerializableHolder(Serializable content) {
this.content = content;
}
}
If you use GSON library, convert your Stack to String and use as single String for Bundle without Serialize. It should work.
Just cast the serializable you retrieved from the bundle to a List, create a new Stack, and then add all the List items to the stack:
Serializable serializable = savedInstanceState.getSerializable("key");
List<Something> list = (List<Something>) serializable;
Stack<Something> stack = new Stack<Something>();
stack.addAll(list);
Why cast to List and not ArrayList you ask? Because if this is fixed in some Android version, you won't have a ClassCastException again.
I hope am not talking any nonsense!
Stack does not implement Serializable but rather just extends the Serializable Vector which is equivalent to ArrayList
I am unaware of the real definition of equivalent and how loose could that be, but it is sufficient to say that the first super class of Stack that is Serializable is Vector.
Since we see this exception, then I would probably assume that casting the Serializable to ArrayList should not throw this exception. Otherwise, I am talking nonsense.

Use Parcelable to pass an object from one android activity to another

I want to do this
class A extends Activity{
private class myClass{
}
myClass obj = new myClass();
intent i = new Intent();
Bundle b = new Bundle();
b.putParcelable(Constants.Settings, obj); //I get the error The method putParcelable(String, Parcelable) in the type Bundle is not applicable for the arguments (int, A.myClass)
i.setClass(getApplicationContext(),B.class);
startActivity(i);
}
How do I use Parcelable to pass obj to activity B?
Create your class and implements Serializable:
private class myClass implements Serializable {
}
And do like:
myClass obj = new myClass();
Intent aActivity = (A.this, B.class);
intent.putExtra("object", obj);
On Receiving side:
myClass myClassObject = getIntent().getSerializableExtra("object");
As the error suggests, you need to make your class (myClass in this case) implement Parcelable. If you look at the documentation for Bundle, all the putParcelable methods take either a Parcelable or a collection of them in some form. (This makes sense, given the name.) So if you want to use that method, you need to have a Parcelable instance to put in the bundle...
Of course you don't have to use putParcelable - you could implement Serializable instead and call putSerializable.
Parcelable is pain in writing code but more cost effective than Serializable. Have a look at the given below link -
Parcelable Vs Serializable

android: problem with Serializable object put into intent

Hi i have problem with a class i want to pass in an intent by putting it into the putExtras()
Its serializable and the code looks like this:
public abstract class ObjectA extends ArrayList<ObjectA> implements java.io.Serializable{...}
public class ObjectB extends ObjectA {...}
...
Bundle extras = new Bundle();
extras.putSerializable("blabla", ObjectB);
intent.putExtras(extras);
...
Object y = getIntent().getExtras().get("blabla");
the problem is, that y now is an ArrayList and no longer an ObjectB so i cant cast it..
if i change the code to
public class ObjectB implements java.io.Serializable {...}
it works fine
By implementing both java.util.List and java.io.Serializable in your class you've triggered this android bug.
I suspect what's happening is that since you aren't declaring ObjectB as serializable it's "falling back" to the most recent parent object that is. So when you put it in to the Bundle you aren't actually putting in ObjectB, but ObjectB cast back to ArrayList.
I think you're going to have to go with the second ("works fine") code.
How are you declaring ObjectB before you pass it into the bundle?
From what I understand of your question you are getting no error when you pass in the bundle, only when removing it.
Try retreiving your ObjectB into an ObjectB type directly like this:
ObjectB y = (ObjectB) getIntent().getExtras().get("blabla");
The ObjectA in ArrayList should implements the interface Parcelable. After that you can put your arraylists in the intent, and get them in another activity.

Categories

Resources