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");
Related
How to pass origin object from one activity to another on Android?
For sure, we can serialized (Serializable, Parcelable, to/from JSON) and pass a copy of the object's data and a new object having the same data could be created; but it will NOT have the same references.
Here is some solution:
Code for the first activity:
final Object objSent = new Object();
final Bundle bundle = new Bundle();
bundle.putBinder(OBJECT_KEY, new ObjectWrapperForBinder(objSent));
startActivity(new Intent(this, SecondActivity.class).putExtras(bundle));
Code for the second activity:
final Object objReceived = ((ObjectWrapperForBinder)getIntent().getExtras().getBinder(OBJECT_KEY)).getData();
but the minimum API Level required 18
Are there other ways?
SOLUTION:
BundleCompat allows to use putBinder/getBinder for all Android versions.
ActivityA:
final Bundle bundle = new Bundle();
BundleCompat.putBinder(bundle,KEY, new ObjectWrapperForBinder(callback));
intent.putExtras(bundle);
ActivityB:
object = ((ObjectWrapperForBinder)BundleCompat.getBinder(intent.getExtras(),KEY)).getData();
It depends on your goals.
If you're going to work inside one process, you can just simply use Singleton pattern.
But if you want to pass your real object to, for example Service, which has attribute android:isolatedProcess="true" :
<service
android:name=".service.SomeService"
android:enabled="true"
android:exported="false"
android:isolatedProcess="true"/>
Then you can't pass your origin object to another process.
You can't. Apps in one process cannot hold objects from another
process, let alone "invoke operations" upon them.
Source: Passing Objects in IPC using Messenger in Android
So, as I can see you are're trying to pass your origin object using Intent mechanism. In my opinion, it's impossible to do it through the Intent's, because Bundle, which contained in Intent doesn't store references to real objects. So, it's impossible.
In such case,EventBus will be a great choice.It's something like global Subscribe-Observer and it can help to pass origin object between any objects.
Do this in the activity where you want to pass an object:
EventBus.getDefault().register(this);
EventBus.getDefault().post(new MessageEvent());
Do this in the activity where you want to receive the object:
First,register the activity:
EventBus.getDefault().register(this);
Second,define an method with #Subscriber to receive the object:
#Subscribe
public void onMessageEvent(MessageEvent event)
Hope this will help.
Sample object should be Parcelable.
SampleObject objSent=new SampleObject();
Intent intent=new Intent(mContext,NewActivity.class);
intent.putExtra(objSent);
startActivity(intent);
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/
I am making a boolean variable value in one class and accessing the status of that variable in another class , on the basis of the boolean variable status my list view shows items,
So my question is
how to create a global boolean varible
how to pass it to another class
how the second class check it
1. Variable in class A
public class A{
public String aClassVar="hello";
}
Using it in Class B
A obj=new A();
String inBClass=obj.aClassVar;
2. To pass data from one Activity to Another Activity you can use Intent remember your Class should extends Activity only than you will be able to pass data by using Intent
Example
Send Data From First Activity using :
Intent i = new Intent(this, SecondClassName.class);
i.putExtra("key", "Value");// key is used to get value in Second Activiyt
startActivity(i);
Receive Data on Second Activity using:
Intent intent = getIntent();
String temp = intent.getStringExtra("key");// usr getStringExtra() If your extra data is represented as strings:
And you Must set Activity Name inside AndroidManifest.xml
like:
<activity android:name="yourPackageName.SecondClassName" />
Let me suggest 3 options.
Do you want to pass a boolean variable between Android Activities? If so, You may want to use a Bundle. Yes, those little things given to Activities on onCreate(). You can pass variables of your own into these, in your case a boolean, with putBoolean() and getBoolean()
Would you prefer using Android's SharedPref? It's an interface for sharing small preferences, like boolean flags, between parts of your app and storing it for later.
Or, you could just implement a singleton class that has the boolean variable and other variables you need to store and check by different classes within your app.
If you just want to access the value of an object or variable in another class, make it Static and then when you need its value, do like
public class tempClass {
public void tempMethod() {
boolean status = myClass.myVariable ; // where myVariable is static boolean varaible of myClass
}
}
But make sure to access the variable after some value is stored in it.
If you want to send the value to another activity then send the value by using intent.
Eg.
Bundle myBund = new Bundle();
myBund.putBoolean(myBool);
Intent intent = new Intent(myClass.this, tempClass.class);
intent.putExtras("myKey",myBund);
startActivity(myBund);
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
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.