I have to send and receive objects between a smartphone and a remote desktop (running Java) via Bluetooth. The smartphone and desktop both share a series of classes that constitutes the application data model.
I need to implement the Parcelable interface on the smartphone app so that when receiving an object from the desktop app, I can send it back to the main activity via a Handler. Unfortunately, this wouldn't work because it would make the classes unusable on the desktop app.
So my question is : Can I send the objects without the Parcelable interface implemented to the desktop app and then make them Parcelable through a generic class when receiving them.
Something like that :
Object orgObject = new Object();
//Make an object Parcelable
ObjectParcelable objPble = GenericClass.makeParcelable(orgObject);
//Remove the Parcelable implementation
orgObject = GenericClass.undoParcelable(objPble);
My preferred solution for this problem is serializing the object to JSON (for example, using the Gson library) and sending it as a string. Then on the other side you can deserialize the JSON to an object using your preferred library.
You need to convert the object that you would like to send to some intermediate format like json or xml for instance. Then you can send this serialized message from the android side and deserialize it on the java side, and vice versa. You can use for that a library that works the same way on android and java, for instance https://github.com/google/gson. In this way you can use same java class files, for your model in both applications.
Related
Can anybody please tell why we need to serializable object for passing one activity to another activity in android? Android is following Java syntax. In java we can pass object to another class without serializable.
Thanks
In ordinary java programs passing parameters(Object type), is kind of create a new handler to the object and giving to another method (In regular words passing the reference by value).
But when it comes in android, passing object references from activity to activity, where their states have to be persisted, is a serious headache.
One way you can do is create a static object in the first activity and access from the second, though this seems to be a easiest way, there is no guarantee that the system maintains the activity in the memory. Therefore the second activity may loose the object reference.
Other way, and the mostly recommended way is serializing(Kind of flatten the object) the object and pass with the intent as extra. In android there are two ways to serialize.
Implement the java's serializable interface
Implement the android's parcelable interface
However, on the android, there is a serious performance hit that comes with using serializable, the solution is using parcelable.
You can find a pretty good tutorial and explanation on android parcelable implementation here.
We need to understand following concepts before getting to the answer:
Android uses Binder for inter-process process. It is required even for simple app because the OS and the apps run in different processes.
Marshalling:
A procedure for converting higher level application data structures into parcels for purpose of embedding into Binder transaction
Unmarshalling
A procedure for reconstructing higher-level application data-structures from parcels received though binder transactions.
You can consider Intents as higher level abstraction of Binder
Based on the documentation following is the way how intent communication occurs:
Activity A creates an Intent with an action description and passes
it to startActivity().
The Android System searches all apps for an intent filter that
matches the intent. When a match is found,
the system starts the matching activity (Activity B) by invoking
its onCreate() method and passing it the Intent.
Why Parcelable or Serializable
IPC (Inter Process Communication) requires data in Intent to be Marshalled and unMarshalled. Binder provides built-in support for marshalling many common data-types. However when we define custom object, it would impact this process and the final object received might be corrupted during the process.
When you define custom object, you need to be responsible for providing this marshalling and unmarshalling which is achieved through Parcelable and Serializable (Since comparison between these two would be another topic I won't discuss much here). Both of these provide mechanisms to perform marshalling and unmarshalling. This is the reason why you need to use Parcelable or Serializable.
Using Parcelable you write the custom code for marshalling and unmarshalling the object thereby you gain complete control over the process.
Serializable is a marker interface, which implies the user cannot marshall the data according to their requirements and its done on JVM, which doesn't give any control at your side.
Disclaimer: Description above is my understanding for the rationale behind the need for serialization based on some
documentation
There are basically two questions in your question, so let's decouple it.
Why marshall in a Parcelable instead of passing an object reference directly?
It's obvious faster and more memory efficient to reference objects rather than marshall/unmarshall them. So you shouldn't use Parcelable when you can pass the object directly.
However, there are situations where you may not have access to the object reference.
in Intent because the process that handles the Intent may not be the process that emitted the Intent (it's an inter-process communication)
in Activity lifecycle, for instance in onRestoreState(), because the whole app may have been killed by memkiller when the user wants to resume it.
everywhere else where Android frameworks requires
In IPC, why use Parcelable rather than Serializable like Java does?
That's only a performance optimization.
If We want to pass object from Activity to to Another Activity . We need to save the passing state.
//to pass :
intent.putExtra("MyClass", obj);
// to retrieve object in second Activity
getIntent().getSerializableExtra("MyClass");
I am using Retrofit with Gson to get some data from my server in my Splash activity.
Now when the call is complete it writes data to Gson Model Classes automatically,
Right Now I have made static ArrayLists of those model classes and writes data to them from call response but this doesn't sound like a good approach.
I was wondering what is the better approach to solve this problem?
Is there Anyway I can get data from these Model Classes directly in other activities using Gson?
or I would have to send them from one activity to other? if so then how can I send them as they already have Serialized annotation.
Thanks
There're more possible solutions how to solve this:
1) Use EventBus (for example Otto Bus) and pass it via this. You also can use RxJava and Observable pattern, but this requires more work.
2) Create a DataHolder singleton, store data in it and use it everywhere you need
3) Pass it via an Intent to Activity
I personally do prefer 1 and 2, since passing the data through the intent doesn't provide the luxury of shared data. RxJava (+ MVP) also provides many other benefits, but it's not the topic of your question.
I have a GAE backend and an Android client. I have generated the client library successfully and that works fine. Now, I'm trying to send an object via an intent from one activity to another in Android. To my horror I noticed that the generated GAE models are final classes that don't implement parcelable or serializable interfaces. Because of that I decided to try and use gson to parse them to json string and then back to the original object. That however fails on fields like DateTime for some reason. My next try was to just let the classes implement serializable (bad idea to touch generated classes!!) but the issue with that was that since these classes extend AbstractMap the serializable output is a HashMap rather than my original object! Now I'm thinking about letting it implement Parcelable but that's a lot of work and sounds like a very bad idea since these models are generated and could change (thus removing my parcelable work.)
I know that people here love code so here is my problem written in code:
Activity A (MainActivity) is trying to send a "UserScore" object (generated from GAE) to activity B.
Intent intent = new Intent(MainActivity.this, ResultsActivity.class);
intent.putExtra(ResultsActivity.BUNDLE_USERSCORE, userScore);
startActivityForResult(intent, REQUEST_COUNTDOWN);
This would've given my error since userScore isn't parcelable or serializable but in this case I made it serializable. Activity B (ResultsActivity) receives:
Object extra = getIntent().getSerializableExtra(BUNDLE_USERSCORE);
Now you would expect the extra object to be of the type UserScore but since it was sent via intent and is a subclass of AbstractMap it is in fact a HashMap.
So, my question is: has anybody encountered this issue and found a way to properly send GAE models via intents in android?
I have a class in my Android app that I've made Parcelable so that it can be passed between Activities.
I would like to be able to save this object to the filesystem. It seems that since I've already implemented Parcelable, it would make sense to pipe the output of this to the filesystem and read it back later.
Is there a correct way to do this? Or must I implement both Parcelable and Serialiazble if I want to both pass the object between Activities and also save it to the filesystem?
From http://developer.android.com/reference/android/os/Parcel.html
Parcel is not a general-purpose serialization mechanism. This class (and the corresponding Parcelable API for placing arbitrary objects into a Parcel) is designed as a high-performance IPC transport. As such, it is not appropriate to place any Parcel data in to persistent storage: changes in the underlying implementation of any of the data in the Parcel can render older data unreadable.
For this problem, I did the following:
Implemented Serializable in my object
Added a toJSON() method to convert the object to a JSON object
Used a custom JSONSerializer to write the JSON objects to a file
Added a constructor that takes a JSON object as a parameter, used by the custom JSONSerializer
It ended up being pretty simple...I can paste some sample code if needed.
I am writing an android application and I need to have two classes use the same KeyguardLock object but I am experiencing extreme difficulty in sharing (via serialization) that object. I have tried using the serialization stackoverflow example link but that didn't work at all. I get a "not serializable" IO exception trying to save the object. I have also tried using JSONObject.
Any ideas? Has anyone run into a similar problem?
Why are you trying to serialize it? A object can only be serialize if it implements Serializable which KeyguardLock doesn't.
If you're trying to pass it around Activities, either create a custom Application object and store it there. Or use a public static variable in a class and access it via that. The static variable is probably the better option for this.