Send Data between Activities as done with fragment - android

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/

Related

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

can not send existing objects using serialization android

I'm trying to transfer an object from one activity to another using intent and serialization android. here i'm not able to send already existing objects(received as null) but when sending new object it works properly.
here's the snippet :
private void someMethod(TPackage tpackageObj) {
Intent intent = new Intent(obj, my.tatasky.ChannelActivity.class);
intent.putExtra("parcel", new TPackage()); // it works
intent.putExtra("parcel", tpackageObj); // doesn't work
}
your custom class implement Serializable interface and then you can pass object instances in intent extra using putExtra(Serializable..) variant of the Intent#putExtra() method.
PSEUDO code:
//to pass :
intent.putExtra("MyClass", obj);
// to retrieve object in second Activity
getIntent().getSerializableExtra("MyClass");

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: Intent with parameters

To pass parameters from one activity to another is used the method "intent.putExtra()"
Does this method only allows to add primitive data or I can add a parameter that is a java bean?
if you can not, how I can send a java bean from one activity to another?
Thanks!!
Look at the API entry for Intent. You've got a load of possible data types you can enter, not the least of which is Parcebles, Bundles, and Serializable. If you really want simple object marshalling I would convert your beans to JSON and put it as a String, then convert it back to a POJO on the receiving end.
You can send objects if they implements serializable.
//At your entity Object:
public class Objeto implements Serializable{
}
//At the sender Activity:
//create an instance of the object
Objeto object = new Objeto();
//creates an intent from the current activity to the destiny activity with the data to be transferred.
Intent proximo = new Intent(this,TelaDestino.class);
//transfers the object as a bundle to the next activity
proximo.putExtra("OBJETO",objeto);
startActivity(proximo);
//At the destine activity:
private Objeto objeto;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
objeto = (Objeto)getIntent().getSerializableExtra("OBJETO");
}
//You can use that and be happy :D
If your object is is Serializable you can add it with putExtra like this.
i.putExtra(String key, Serializable value);
Another way to share data between activities is extend the application class.
My answer explains how to use it.
getApplicaiton return which object among applicaitons

Regarding Intents

According to what i have learnt from passing data using Intents is 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.
I would like to know if it would be efficient if one extends the Intent class to create a custom Intent and have references to the objects that are required by the other activities and pass the data to the other activities. For example:
public class CustomIntent extends Intent {
private Object o;
public CustomIntent() {
super();
// TODO Auto-generated constructor stub
}
public Object getObject () {
return o;
}
public void setObject(Object object) {
this.o = object;
}
}
In the receiving activity i get the intent and cast the intent to the CustomIntent type and retrieve the object required by the activity. Would this improve the efficiency by reducing the need for Serialization? Kindly throw some light on this. Thanks in advance.
No. Intents are dispatched by the Android system and are always serialized as they can be sent to any activity, service, etc in the system.
For your problem you could probably workaround this issue by creating an Application class and storing your data in it:
class CustomApplication extends Application {
private Object data;
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
You activate it by updating AndroindManifest.xml setting the android:name property on the application tag you your class name.
To use in your activities:
CustomApplication app = (CustomApplication) getApplicationContext();
app.setData(yourDataObject);
I think it would be better if you let the android handle everything for you. Do not customize it, if it is not very essential.
If you want to have the reference of the object in another activity then there are other ways too.
You can make your object static and directly access it from other activity.
You can make a new object of same type and replace it after coming again back to the first activity(in onActivitResult() method.).
or there may be many more ways to do it.
Thanks.

Categories

Resources