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

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

Related

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/

Pass an interface from class to activity

If i have an object form interface in my class, how i can pass it to activity?
My solution was to change it as static object, it's work fine but sometimes it create a memory leaks because of all the old references which the garbage collector cannot collect, and i cannot implement 'Serializable' on my interface.
public class MyClass {
protected OnStringSetListener onstringPicked;
public interface OnStringSetListener {
void OnStringSet(String path);
}
//......//
public void startActivity(){
Intent intent=new Intent(context,Secound.class);
// ?! intent.putExtra("TAG", inter);
context.startActivity(intent);
}
}
In my opinion, using Bundles would be a nice choice. Actually bundles internally use Parcelables. So, this approach would be a good way to go with.
Suppose you would like to pass an object of type class MyClass to another Activity, all you need is adding two methods for compressing/uncompressing to/from a bundle.
To Bundle:
public Bundle toBundle(){
Bundle bundle = new Bundle();
// Add the class properties to the bundle
return bundle;
}
From Bundle:
public static MyClass fromBundle(Bundle bundle){
MyClass obj = new MyClass();
// populate properties here
return obj;
}
Note: Then you can simply pass bundles to another activities using putExtra. Note that handling bundles is much simpler than Parcelables.
Passing in custom objects is a little more complicated. You could just mark the class as Serializable
and let Java take care of this. However, on the android, there is a serious performance hit that comes with using Serializable. The solution is to use Parcelable.
Extra info

Pass 3D-array to Activity in Android

I am trying to pass a 3D-doublearray to another activity. I don know why I get NullpointerException? What is missing?
MainActivity
Intent intent = new Intent(this, DataActivity.class);
Bundle mBundle = new Bundle();
mBundle.putSerializable("list", output_data);
intent.putExtras(mBundle);
startActivity(intent);
DataActivity (reveiver)
Intent intent = new Intent();
double[][][] params = (double[][][]) intent.getExtras().getSerializable("list");
And I know for certain that the 3d-array already is allocated in the MainActivity. I have tested that!
Would be glad if someone has any solution to this and could answer why I get a NullPointerException.
(Edit: NullpointerException at the line double[][][] params = ...)
I'm pretty sure double[][][] doesn't implement Serializable. What you can do is make your own class like so:
public class MyArrayWrapper implements Serializable {
private double[][][] arr;
public MyArrayWrapper(double[][][] value) {
arr = value;
}
public double[][][] getArray() {
return arr;
}
}
You then instantiate that wrapper class and put it as a serializable instead. Then when getting the serializable you do it like this:
MyArrayWrapper wrap = (MyArrayWrapper) intent.getExtras().getSerializable("list");
double[][]][] myArray = wrap.getArray();
Hope this helps!
Maybe you need a class that implements serializable?
Passing data through intent using Serializable
In this example, they are using custom class and List<> to serialize in a bundle. You can create a class with the 3D array inside?

How to pass any object from activity to service?

I want to pass object of "BluetoothDevice" class from an activity to service. I am getting syntaxes for passing Strings or any primitive types but not passing objects. Please Help. Thanx in advance.
you should create a class containing your data to be passed and extend that from Serializable or Parcelable and then you can put an object of that class as an Extra to your Intent and use it in your Service
EDIT :
as rom4ek mentioned, BluetoothDevice is already implements Parcelable and all you have to do is :
Bundle b = new Bundle();
b.putParcelable("data", yourBluetoothDeviceObject);
yourIntent.putExtra(b);
and for retrieving data :
Bundle b = yourIntent.getExtra();
BluetoothDevice device = (BluetoothDevice) b.getParcelable("data");
You can make your complex object implement Serializable or Parcelable and then you can pass it to Service using putExtra(String name, Serializable value) or putExtra(String name, Parcelable value)
Bundle b = new Bundle();
b.putParcelable("key", yourObject);
yourIntent.putExtra(b);
other hand
Bundle b = yourIntent.getExtra();
YourObjectType OBJ = (YourObjectType ) b.getParcelable("key");

Intent putextra serializable object array

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.

Categories

Resources