Android putSerializable vs putString - android

i have a POJO object defined like this:
public class MYPOJO implements Serializable {
int myint;
String mystring;
}
then when im passing the info to an activity i do this:
Intent i = new Intent(this, WearActivity.class);
Bundle b = new Bundle();
MYPojo pojo = new MYPojo();
pojo.mystring="cool";
b.putSerializable("someString", pojo.mystring);//this line is my issue
i.putExtra("coolBundle",b);
startActivityForResult(i, 0);
and to read the 'someString' extra i do:
Bundle b2 = getIntent().getBundleExtra("coolBundle");
b2.getString("someString");
So now onto my question: is there really any difference if i do the following if if at the end im still calling for retrieval b2.getString("someString") :
b.putString("someString",pojo.mystring)
vs
b.putSerializable("someString",pojo.mystring) ?

In practice, there isn't a difference you'll see between passing a string, or passing a serializable string between activities, besides "efficiency" or possible usage of reflection/security. It might be more of a design and principle issue I have with passing a String in as "serializable". Essentially by passing in a String as Serializable, Android/Java will utilize the wrapper of String, which contains a data structure of char[] behind the scenes.
TLDR; If your POJO contained more data, I would highly recommend implementing Parcelable. More information can be found in this SO answer here. But if you are going to be passing just a String, I would use the putString/getString methods that Android provides for us.

Related

How do I set the intent extra dynamically based on the type of variable received in the Json?

I have a Json in a server response which has the entire intent data. I also get extras to be added to the intent.
Now, the extras can vary in data type. int, long, boolean etc.
How do I pass these extra values to the intent which I create in the necessary type?
The putExtra method has string as a key and a few overloads based upon the type of value.
How do I decide which one to use?
Parse the json using gson library http://www.java2s.com/Code/Jar/g/Downloadgson222jar.htm
create the model class and implements serializable.
Example:-
public class TemplateCommonMetaData implements Serializable {
#SerializedName("code")
public boolean sCode;
#SerializedName("message")
public String message; }
and set serializable objet in intent
in.putExtra("key", serializableobject);
It depends on contracts of json parser, Intent receiver.
If protocol is undefined - heuristically (switch, if/else).
Also you can try gson, it doesn't solve problem with types, but transit can be easier.

SharedPreferences - Android (different data types)

I have a problem with with sharing data between two different activities. I have data like :
int number
String name
int number_2
int time
int total
I'm trying to make something like order list with this set of data . So it will take one set of data , then back to previous activity , move forward and again add data to it .
I have an idea of making it in array of object - but data inside was cleared after changing activity.
How can I make it ?
I don't know if and how to add Array of object to SharedPreferences , and get value of one element from there.
You should have a look at the documentation of the Intent(s) if you want to do that on the fly associating a key to the value(s) that you want to pass to your second activity.
Anyway, you can think any(sharedpref, database,...) way to pass your parameters but for those kind of things it's a convention and a good practice to follow that.
Don't used share preferences for this...Use the singleton pattern, extend Application, or just make a class with static variables and update them...
You can use .putExtra but since you are communicating with more than one activity the above suggestions are probably the best.
public class ShareData {
private String s;
private int s;
private static ShareData shareData = new ShareData();
private ShareData(){}
public static ShareData getInstance(){ return shareData}
//create getters and setters;
}
Why not to use Intents
Intent intent = new Intent(FirstActivity.this, (destination activity)SecondActivity.class);
intent.putExtra("some_key", value);
intent.putExtra("some_other_key", "a value");
startActivity(intent);
in the second activity
Bundle bundle = getIntent().getExtras();
int value = bundle.getInt("some_key");
String value2 = bundle.getString("some_other_key");
EDIT if you want to read more about adding array to shared preferences check this
Is it possible to add an array or object to SharedPreferences on Android
also this
http://www.sherif.mobi/2012/05/string-arrays-and-object-arrays-in.html

Passing a custom Object from one Activity to another Parcelable vs Bundle

I'd like to pass a custom Object from one activity to another, the Object consists of a String and a List of another custom Object which consists of an array of strings and an array of ints. I've read https://stackoverflow.com/a/2141166/830104, but then I've found this answer https://stackoverflow.com/a/7842273/830104. Which is better to use Bundle or Parcelable? What is the difference? When should I use this each? Thanks for your replies, Dan
Parcelable and Bundle are not exclusive concepts; you can even deploy both on your app at a time.
[1] Term Parcelable comes with Serialization concept in Java (and other high-level language such as C#, Python,...). It ensures that an object - which remains in RAM store - of such Parcelable class can be saved in file stream such as text or memory (offline status) then can be reconstructed to be used in program at runtime (online status).
In an Android application, within 2 independent activities (exclusively running - one starts then other will have to stop):
There will be NO pointer from current activity to refer to previous one and its members - because previous activity is stopped and cleared out form memory; so that to maintain object's value passed to next activity (called from Intent) the object need to be parcelable (serializable).
[2] While Bundle is normally the Android concept, denotes that a variable or group of variables. If look into lower level, it can be considered as HashMap with key-value pairs.
Conclusion:
Bundle is to store many objects with related keys, it can save any object in native types, but it doesn't know how to save a complex object (which contains an ArrayList for example)
Parcelable class is to ensure a complex instance of it can be serialized and de-serialized during runtime. This object can contains complex types such as ArrayList, HashMap, array, or struct,...
[UPDATED] - Example:
//Class without implementing Parcelable will cause error
//if passing though activities via Intent
public class NoneParcelable
{
private ArrayList<String> nameList = new ArrayList<String>();
public NoneParcelable()
{
nameList.add("abc");
nameList.add("xyz");
}
}
//Parcelable Class's objects can be exchanged
public class GoodParcelable implements Parcelable
{
private ArrayList<String> nameList = new ArrayList<String>();
public GoodParcelable()
{
nameList.add("Can");
nameList.add("be parsed");
}
#Override
public int describeContents()
{
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags)
{
// Serialize ArrayList name here
}
}
In source activity:
NoneParcelable nonePcl = new NoneParcelable();
GoodParcelable goodPcl = new GoodParcelable();
int count = 100;
Intent i = new Intent(...);
i.putExtra("NONE_P",nonePcl);
i.putExtra("GOOD_P",goodPcl);
i.putExtra("COUNT", count);
In destination activity:
Intent i = getIntent();
//this is BAD:
NoneParcelable nP = (NoneParcelable)i.getExtra("NONE_P"); //BAD code
//these are OK:
int count = (int)i.getExtra("COUNT");//OK
GoodParcelable myParcelableObject=(GoodParcelable)i.getParcelableExtra("GOOD_P");// OK

How can i pass a list of objects (any object), through bundle, from activity A to Activity B?

This is on the android platform, i have a list of objects of type (FitItem), and i want pass the list from my activity A to another activity B, and on the activity B i want get the list of objects again
Intent yourIntent = new Intent(activityA.this, activityB.class);
Bundle yourBundle = new Bundle();
yourBundle.putString("name", value);
yourIntent.putExtras(yourBundle);
startActivity(yourIntent);
And you get the value in the next Activity (in your onCreate()):
Bundle yourBundle = getIntent().getExtras();
String s = yourBundle.getString("name");
This example is passing a String, but you should be able to grasp how to use it for other objects.
For custom classes:
You will have to have your FitItem class implements Parcelable.
Then in Activity A, from an Intent object, use putParcelableArrayListExtra to pass the list of FitItem to Activity B and in your Activity B, use getParcelableArrayListExtra to retrieve the list of FitItem
If you want to pass list of String, Integer, Float ..., refer to bschultz post
You must serialize your object.
"Seriawhat?"
Ok, first things first: What is object serialization?
"Got it, but how do I do that?"
You can use Parcelable (more code, but faster) or Serializable (less code, but slower). Parcelable vs Serializable.
"Save me some time, show me the code!"
Ok, if you'll use Parcelable, see this.
And if you'll use Serializable, see this and/or this.
Hope that helps!
If they're if the object is serializable, just add them as extras to the intent. I think something like this:
// in Activity A, when starting Activity B
Intent i = new Intent(this, ActivityB.class);
i.putExra("fitItemList", fitItemList);
startActivity(i);
// in Activity B (onCreate)
ArrayList<FitItem> fitItemList = savedInstanceState.getSerializableExtra("fitItemList");
edit:
Just like bschultz already posted :)
Implements Serializable in model class. Then you can pass model class using bundle/intent.

Best way to pass objects from one activity to another

I have read about global static technique in which we create a class with static fields which can be accessed in any activity. Is there any other way to pass large data sets like ArrayList<Drawables> or HashMaps ?
I have also read about Serializable but have no idea how to use it. Any example code is welcome...
Intent intent = new Intent(getBaseContext(), NextActivity.class);
intent.putExtra("arraylist", new ArrayList<String>());
If your ArrayList contains another Object that you have created yourself, for instance Friend.class, you can implement the Friend.class with Serializable and then:
Intent intent = new Intent(getBaseContext(), NextActivity.class);
intent.putExtra("friendlist", new ArrayList<Friend>());
And for receiving it on NextActivity.class:
Bundle extras = getIntent().getExtras();
if(extras != null){
ArrayList<Friend> friends = extras.getSerializable("friendlist");
}
Well, instead of passing an empty ArrayList, you'll have to put values into the ArrayList and then pass it, but you get the idea.
You should pack your information into the Intent object you create to call your next Activity. There is a extras Bundle object.
You can use either the Serializable interface or the Android-specific Parcelable interface to pass non-primitive objects.
The Android Developer site has a handy Notepad Tutorial with an example of putting information into the intent.
From their tutorial:
super.onListItemClick(l, v, position, id);
Cursor c = mNotesCursor;
c.moveToPosition(position);
Intent i = new Intent(this, NoteEdit.class);
i.putExtra(NotesDbAdapter.KEY_ROWID, id);
i.putExtra(NotesDbAdapter.KEY_TITLE, c.getString(
c.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)));
i.putExtra(NotesDbAdapter.KEY_BODY, c.getString(
c.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY)));
startActivityForResult(i, ACTIVITY_EDIT);
As long as you stay in the same application( speak: same JVM ) you do not need to bother with intents, parcelables, serialisation etc - all objects are on same heap and can be passed via singletons, DI containers like roboguice or whatever you see fit.
If you like to push data to an other application, best technique would be to pass it as JSON/XML serialized stuff.
Passing Hashmap is pretty simple, All Collections objects implement Serializable (sp?) interface which means they can be passed as Extras inside Intent
Use putExtra(String key, Serializable obj) to insert the HashMap and on the other acitivity use getIntent().getSerializableExtra(String key), You will need to Cast the return value as a HashMap though.

Categories

Resources