Passing object from one activity from another activity - android

I like to pass object from one activity from another activity. I implemented Serializable.
But somehow, the object is not passed and at the receiver side I get NULL.
Can pls check where is wrong?
public class TrackerInfo implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
String Idnumber;
String Simcardnumber;
String Description;
String Model;
String time;
public String getSimcardnumber() {
return Simcardnumber;
}
public String getDescription() {
return Description;
}
public String getModel() {
return Model;
}
public void setModel(String model) {
this.Model = model;
}
public String getTime() {
return time;
}
public void setInforFromCursor(Cursor cursor){
this.Idnumber = cursor.getString(1);
this.Simcardnumber = cursor.getString(2);
this.Description = cursor.getString(3);
this.Model = cursor.getString(4);
this.time = cursor.getString(5);
}}
At sender side,
#Override
public void itemSelected(String id) {
//get Tracker info
dbHelper = new TrackerDBAdapter(this);
dbHelper.open();
Cursor cursor = dbHelper.fetchListByIDNum(id);
TrackerInfo tracker = new TrackerInfo();
tracker.setInforFromCursor(cursor);
dbHelper.close();
LinkedHashMap<String, Object> obj = new LinkedHashMap<String, Object>();
obj.put("TRAKCER", tracker);
Bundle b = new Bundle();
b.putSerializable("bundleobj", obj);
Intent intent = new Intent(this, DetailMapView.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("bundleobj", b);
startActivity(intent);
}
At receiver side,
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_detail_map_view);
try { setContentView(R.layout.activity_detail_map_view);
Bundle bn = new Bundle();
bn = getIntent().getExtras();
HashMap<String, Object> getobj = new HashMap<String, Object>();
getobj = (HashMap<String, Object>) bn.getSerializable("bundleobj");
trackerinfo = (TrackerInfo) getobj.get("TRACKER");
} catch (Exception e) {
Log.e("Err", e.getMessage());
}}

I think that your problem is here:
obj.put("TRAKCER", tracker);
You are adding tracker to HashMap with key TRAKCER
But here:
getobj.get("TRACKER");
You are trying to get object with key TRACKER but keys are not equal and this is reason of NPE. You need to fix
obj.put("TRACKER", tracker);
Now keys are equal so it should works.
Update:
As #Sam pointed out you wrapped your HashMap into Bundle and Bundle into Intent. So if your approach had work you need to do following:
LinkedHashMap<String, Object> obj = new LinkedHashMap<String, Object>();
obj.put("TRACKER", tracker);
Bundle b = new Bundle();
b.putSerializable("trackerObj", obj);
Intent intent = new Intent(this, DetailMapView.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("bundleObj", b);
And for retrieving HashMap:
Bundle wrapper = getIntent().getBundleExtra("bundleObj"); // this Bundle contains HashMap
HashMap<String, Object> obj = (HashMap<String, Object>) wrapper.getSerializable("trackerObj");
Recommendation:
How #Sam pointed out again, better and cleaner way is to wrap directly your HashMap as Serializable into Intent with putExtra("trackerObj", obj) method and then easily retrieve it as
HashMap<String, Object> o = (HashMap<String, Object>) getIntent().getSerializableExtra("trackerObj");

You have a few mistakes, please read Sajmon's answer, but you are also putting a Bundle in a Bundle, but only reading from the outer Bundle. Remove code like this:
Bundle b = new Bundle();
b.putSerializable("bundleobj", obj);
And put the data directly into the Intent:
Intent intent = new Intent(this, DetailMapView.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("bundleobj", obj);
// You may need to help the compiler by casting it to a Serializable
//intent.putExtra("bundleobj", (Serializable) obj);
In order to use your double Bundle method you need to fetch both "bundleobj" tags:
bn = getIntent().getExtras().getBundle("bundleobj");
HashMap<String, Object> getobj = (HashMap<String, Object>) bn.getSerializable("bundleobj");

Related

Pass ArrayList from to Activity

I have an ArrayList of CustomInput objects and DataWrapper class with getter and setter for the ArrayList. I want to pass DataWrapper from Non-Activity class to Activity class. I have tried implementing Serializable, but I get Parcelable encountered ioexception writing serializable object cause by NotSerializableException.
DataWrapper.java
public class DataWrapper implements Serializable {
private static final long serialVersionUID = 1L;
private ArrayList<CustomInput> customInputs;
public void setFields(ArrayList<CustomInput> data) {
this.customInputs = data;
}
public ArrayList<CustomInput> getFields() {
return this.customInputs;
}
}
Non-Activiy class
public void showActivity() {
Intent intent = new Intent(request, ActivityKorak.class);
intent.putExtra("title", title);
DataWrapper dw = new DataWrapper();
dw.setFields(fields);
intent.putExtra("data", dw);
request.startActivity(intent);
}
ActivityKorak.class->onCreate()
Intent intent = getIntent();
String title = intent.getStringExtra("title");
DataWrapper dw = (DataWrapper) intent.getSerializableExtra("data");
ArrayList<CustomInput> fields = dw.getFields();
No need to create new class DataWrapper.java. Because ArrayList is serializable.
Non-Activiy class
public void showActivity() {
Intent intent = new Intent(request, ActivityKorak.class);
intent.putExtra("title", title);
intent.putExtra("data", fields);
request.startActivity(intent);
}
ActivityKorak.class->onCreate()
Intent intent = getIntent();
String title = intent.getStringExtra("title");
DataWrapper dw = (DataWrapper) intent.getSerializableExtra("data");
ArrayList<CustomInput> fields = dw.getFields();
hi please check how we can send arraylist in intent
ArrayList<HashMap<String, String>> aldata = new ArrayList<HashMap<String, String>>();
i assumed here data is already added in your arraylist, please check
Send data and start other activity,
Intent intent = new Intent(this,AbcActivity.class);
intent.putExtra("aldata", aldata_TaxiLine);
startActivity(intent);
Get data in your next activity,
ArrayList<HashMap<String, String>> aldata1;
and call this in your oncreate
aldata = (ArrayList<HashMap<String, String>>) getIntent()
.getSerializableExtra("aldata");
hope this will help you.

how to pass Json data in Android Adapter

Hello I am trying to pass Json Data from Adapter to another Activity
playb = (ImageButton) row.findViewById(R.id.playbtn);
playb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Song newitem = getItem(position);
//long itemId = getItemId(position);
app = (myapplication) getContext().getApplicationContext();
app.setSong(item);
Intent intent1 = new Intent(getContext(), SongDetailedActivity.class);
intent1.putExtra("SongID", item.toString());
getContext().startActivity(intent1);
}
});
and my activity
Intent i = getActivity().getIntent();
hello = i.getIntExtra("SongID", 5);
Song event = app.getSongID(hello);
event.setSongID(hello);
In your activity,
Bundle bundle = getIntent().getExtras();
if(bundle != null && bundle.containsKey("SongID")){
String json = bundle.getString("SongID");
JSONObject jsonObject = new JSONObject(json);
//parse json from here...don't forget to handle JSONException
}
You can whether pass an integer value and catch it using i.getIntExtra()
or pass a String and catch using i.getStringExtra()
You can't put a string in intent and get it as integer, should has the same type.

How to pass ArrayList of Objects from one to another activity using Intent in android?

I have the following in code in my onClick() method as
List<Question> mQuestionsList = QuestionBank.getQuestions();
Now I have the intent after this line, as follows :
Intent resultIntent = new Intent(this, ResultActivity.class);
resultIntent.putParcelableArrayListExtra("QuestionsExtra", (ArrayList<? extends Parcelable>) mQuestionsList);
startActivity(resultIntent);
I don't know how to pass this question lists in the intent from one activity to another activity
My Question class
public class Question {
private int[] operands;
private int[] choices;
private int userAnswerIndex;
public Question(int[] operands, int[] choices) {
this.operands = operands;
this.choices = choices;
this.userAnswerIndex = -1;
}
public int[] getChoices() {
return choices;
}
public void setChoices(int[] choices) {
this.choices = choices;
}
public int[] getOperands() {
return operands;
}
public void setOperands(int[] operands) {
this.operands = operands;
}
public int getUserAnswerIndex() {
return userAnswerIndex;
}
public void setUserAnswerIndex(int userAnswerIndex) {
this.userAnswerIndex = userAnswerIndex;
}
public int getAnswer() {
int answer = 0;
for (int operand : operands) {
answer += operand;
}
return answer;
}
public boolean isCorrect() {
return getAnswer() == choices[this.userAnswerIndex];
}
public boolean hasAnswered() {
return userAnswerIndex != -1;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
// Question
builder.append("Question: ");
for(int operand : operands) {
builder.append(String.format("%d ", operand));
}
builder.append(System.getProperty("line.separator"));
// Choices
int answer = getAnswer();
for (int choice : choices) {
if (choice == answer) {
builder.append(String.format("%d (A) ", choice));
} else {
builder.append(String.format("%d ", choice));
}
}
return builder.toString();
}
}
Between Activity: Worked for me
ArrayList<Object> object = new ArrayList<Object>();
Intent intent = new Intent(Current.class, Transfer.class);
Bundle args = new Bundle();
args.putSerializable("ARRAYLIST",(Serializable)object);
intent.putExtra("BUNDLE",args);
startActivity(intent);
In the Transfer.class
Intent intent = getIntent();
Bundle args = intent.getBundleExtra("BUNDLE");
ArrayList<Object> object = (ArrayList<Object>) args.getSerializable("ARRAYLIST");
Hope this help's someone.
Using Parcelable to pass data between Activity
This usually works when you have created DataModel
e.g. Suppose we have a json of type
{
"bird": [{
"id": 1,
"name": "Chicken"
}, {
"id": 2,
"name": "Eagle"
}]
}
Here bird is a List and it contains two elements so
we will create the models using jsonschema2pojo
Now we have the model class Name BirdModel and Bird
BirdModel consist of List of Bird
and Bird contains name and id
Go to the bird class and add interface "implements Parcelable"
add implemets method in android studio by Alt+Enter
Note: A dialog box will appear saying Add implements method
press Enter
The add Parcelable implementation by pressing the Alt + Enter
Note: A dialog box will appear saying Add Parcelable implementation
and Enter again
Now to pass it to the intent.
List<Bird> birds = birdModel.getBird();
Intent intent = new Intent(Current.this, Transfer.class);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("Birds", birds);
intent.putExtras(bundle);
startActivity(intent);
And on Transfer Activity onCreate
List<Bird> challenge = this.getIntent().getExtras().getParcelableArrayList("Birds");
Thanks
If there is any problem please let me know.
Steps:
Implements your object class to serializable
public class Question implements Serializable`
Put this in your Source Activity
ArrayList<Question> mQuestionList = new ArrayList<Question>;
mQuestionsList = QuestionBank.getQuestions();
mQuestionList.add(new Question(ops1, choices1));
Intent intent = new Intent(SourceActivity.this, TargetActivity.class);
intent.putExtra("QuestionListExtra", mQuestionList);
Put this in your Target Activity
ArrayList<Question> questions = new ArrayList<Question>();
questions = (ArrayList<Questions>) getIntent().getSerializableExtra("QuestionListExtra");
It works well,
public class Question implements Serializable {
private int[] operands;
private int[] choices;
private int userAnswerIndex;
public Question(int[] operands, int[] choices) {
this.operands = operands;
this.choices = choices;
this.userAnswerIndex = -1;
}
public int[] getChoices() {
return choices;
}
public void setChoices(int[] choices) {
this.choices = choices;
}
public int[] getOperands() {
return operands;
}
public void setOperands(int[] operands) {
this.operands = operands;
}
public int getUserAnswerIndex() {
return userAnswerIndex;
}
public void setUserAnswerIndex(int userAnswerIndex) {
this.userAnswerIndex = userAnswerIndex;
}
public int getAnswer() {
int answer = 0;
for (int operand : operands) {
answer += operand;
}
return answer;
}
public boolean isCorrect() {
return getAnswer() == choices[this.userAnswerIndex];
}
public boolean hasAnswered() {
return userAnswerIndex != -1;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
// Question
builder.append("Question: ");
for(int operand : operands) {
builder.append(String.format("%d ", operand));
}
builder.append(System.getProperty("line.separator"));
// Choices
int answer = getAnswer();
for (int choice : choices) {
if (choice == answer) {
builder.append(String.format("%d (A) ", choice));
} else {
builder.append(String.format("%d ", choice));
}
}
return builder.toString();
}
}
In your Source Activity, use this :
List<Question> mQuestionList = new ArrayList<Question>;
mQuestionsList = QuestionBank.getQuestions();
mQuestionList.add(new Question(ops1, choices1));
Intent intent = new Intent(SourceActivity.this, TargetActivity.class);
intent.putExtra("QuestionListExtra", ArrayList<Question>mQuestionList);
In your Target Activity, use this :
List<Question> questions = new ArrayList<Question>();
questions = (ArrayList<Question>)getIntent().getSerializableExtra("QuestionListExtra");
Your bean or pojo class should implements parcelable interface.
For example:
public class BeanClass implements Parcelable{
String name;
int age;
String sex;
public BeanClass(String name, int age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
public static final Creator<BeanClass> CREATOR = new Creator<BeanClass>() {
#Override
public BeanClass createFromParcel(Parcel in) {
return new BeanClass(in);
}
#Override
public BeanClass[] newArray(int size) {
return new BeanClass[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeInt(age);
dest.writeString(sex);
}
}
Consider a scenario that you want to send the arraylist of beanclass type from Activity1 to Activity2.
Use the following code
Activity1:
ArrayList<BeanClass> list=new ArrayList<BeanClass>();
private ArrayList<BeanClass> getList() {
for(int i=0;i<5;i++) {
list.add(new BeanClass("xyz", 25, "M"));
}
return list;
}
private void gotoNextActivity() {
Intent intent=new Intent(this,Activity2.class);
/* Bundle args = new Bundle();
args.putSerializable("ARRAYLIST",(Serializable)list);
intent.putExtra("BUNDLE",args);*/
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("StudentDetails", list);
intent.putExtras(bundle);
startActivity(intent);
}
Activity2:
ArrayList<BeanClass> listFromActivity1=new ArrayList<>();
listFromActivity1=this.getIntent().getExtras().getParcelableArrayList("StudentDetails");
if (listFromActivity1 != null) {
Log.d("listis",""+listFromActivity1.toString());
}
I think this basic to understand the concept.
Pass your object via Parcelable.
And here is a good tutorial to get you started.
First Question should implements Parcelable like this and add the those lines:
public class Question implements Parcelable{
public Question(Parcel in) {
// put your data using = in.readString();
this.operands = in.readString();;
this.choices = in.readString();;
this.userAnswerIndex = in.readString();;
}
public Question() {
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(operands);
dest.writeString(choices);
dest.writeString(userAnswerIndex);
}
public static final Parcelable.Creator<Question> CREATOR = new Parcelable.Creator<Question>() {
#Override
public Question[] newArray(int size) {
return new Question[size];
}
#Override
public Question createFromParcel(Parcel source) {
return new Question(source);
}
};
}
Then pass your data like this:
Question question = new Question();
// put your data
Intent resultIntent = new Intent(this, ResultActivity.class);
resultIntent.putExtra("QuestionsExtra", question);
startActivity(resultIntent);
And get your data like this:
Question question = new Question();
Bundle extras = getIntent().getExtras();
if(extras != null){
question = extras.getParcelable("QuestionsExtra");
}
This will do!
The easiest way to pass ArrayList using intent
Add this line in dependencies block build.gradle.
implementation 'com.google.code.gson:gson:2.2.4'
pass arraylist
ArrayList<String> listPrivate = new ArrayList<>();
Intent intent = new Intent(MainActivity.this, ListActivity.class);
intent.putExtra("private_list", new Gson().toJson(listPrivate));
startActivity(intent);
retrieve list in another activity
ArrayList<String> listPrivate = new ArrayList<>();
Type type = new TypeToken<List<String>>() {
}.getType();
listPrivate = new Gson().fromJson(getIntent().getStringExtra("private_list"), type);
You can use object also instead of String in type
Works for me..
Simple as that !! worked for me
From activity
Intent intent = new Intent(Viewhirings.this, Informaall.class);
intent.putStringArrayListExtra("list",nselectedfromadapter);
startActivity(intent);
TO activity
Bundle bundle = getIntent().getExtras();
nselectedfromadapter= bundle.getStringArrayList("list");
If your class Question contains only primitives, Serializeble or String fields you can implement him Serializable. ArrayList is implement Serializable, that's why you can put it like Bundle.putSerializable(key, value) and send it to another Activity.
IMHO, Parcelable - it's very long way.
I do one of two things in this scenario
Implement a serialize/deserialize system for my objects and pass them as Strings (in JSON format usually, but you can serialize them any way you'd like)
Implement a container that lives outside of the activities so that all my activities can read and write to this container. You can make this container static or use some kind of dependency injection to retrieve the same instance in each activity.
Parcelable works just fine, but I always found it to be an ugly looking pattern and doesn't really add any value that isn't there if you write your own serialization code outside of the model.
You must need to also implement Parcelable interface and must add writeToParcel method to your Questions class with Parcel argument in Constructor in addition to Serializable. otherwise app will crash.
Your arrayList:
ArrayList<String> yourArray = new ArrayList<>();
Write this code from where you want intent:
Intent newIntent = new Intent(this, NextActivity.class);
newIntent.putExtra("name",yourArray);
startActivity(newIntent);
In Next Activity:
ArrayList<String> myArray = new ArrayList<>();
Write this code in onCreate:
myArray =(ArrayList<String>)getIntent().getSerializableExtra("name");
To set the data in kotlin
val offerIds = ArrayList<Offer>()
offerIds.add(Offer(1))
retrunIntent.putExtra(C.OFFER_IDS, offerIds)
To get the data
val offerIds = data.getSerializableExtra(C.OFFER_IDS) as ArrayList<Offer>?
Now access the arraylist
Implements Parcelable and send arraylist as putParcelableArrayListExtra and get it from next activity getParcelableArrayListExtra
example:
Implement parcelable on your custom class -(Alt +enter) Implement its methods
public class Model implements Parcelable {
private String Id;
public Model() {
}
protected Model(Parcel in) {
Id= in.readString();
}
public static final Creator<Model> CREATOR = new Creator<Model>() {
#Override
public ModelcreateFromParcel(Parcel in) {
return new Model(in);
}
#Override
public Model[] newArray(int size) {
return new Model[size];
}
};
public String getId() {
return Id;
}
public void setId(String Id) {
this.Id = Id;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(Id);
}
}
Pass class object from activity 1
Intent intent = new Intent(Activity1.this, Activity2.class);
intent.putParcelableArrayListExtra("model", modelArrayList);
startActivity(intent);
Get extra from Activity2
if (getIntent().hasExtra("model")) {
Intent intent = getIntent();
cartArrayList = intent.getParcelableArrayListExtra("model");
}
Your intent creation seems correct if your Question implements Parcelable.
In the next activity you can retrieve your list of questions like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(getIntent() != null && getIntent().hasExtra("QuestionsExtra")) {
List<Question> mQuestionsList = getIntent().getParcelableArrayListExtra("QuestionsExtra");
}
}
You can pass the arraylist from one activity to another by using bundle with intent.
Use the code below
This is the shortest and most suitable way to pass arraylist
bundle.putStringArrayList("keyword",arraylist);
I found that most of the answers work but with a warning. So I have a tricky way to achieve this without any warning.
ArrayList<Question> questionList = new ArrayList<>();
...
Intent intent = new Intent(CurrentActivity.this, ToOpenActivity.class);
for (int i = 0; i < questionList.size(); i++) {
Question question = questionList.get(i);
intent.putExtra("question" + i, question);
}
startActivity(intent);
And now in Second Activity
ArrayList<Question> questionList = new ArrayList<>();
Intent intent = getIntent();
int i = 0;
while (intent.hasExtra("question" + i)){
Question model = (Question) intent.getSerializableExtra("question" + i);
questionList.add(model);
i++;
}
Note:
implements Serializable in your Question class.
You can use parcelable for object passing which is more efficient than Serializable .
Kindly refer the link which i am share contains complete parcelable sample.
Click download ParcelableSample.zip
You can Pass Arraylist/Pojo using bundle like this ,
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
Bundle args = new Bundle();
args.putSerializable("imageSliders",(Serializable)allStoriesPojo.getImageSliderPojos());
intent.putExtra("BUNDLE",args);
startActivity(intent);
Get those values in SecondActivity like this
Intent intent = getIntent();
Bundle args = intent.getBundleExtra("BUNDLE");
String filter = bundle.getString("imageSliders");
You can try this. I think it will help you.
Don't fotget to Initialize value into ArrayList
ArrayList<String> imageList = new ArrayList<>();
Send data using intent.putStringArrayListExtra()....
Intent intent = new Intent(this, NextActivity.class);
intent.putStringArrayListExtra("IMAGE_LIST", imageList);
startActivity(intent);
Receive data using intent.getStringArrayListExtra()...
ArrayList<String> imageList = new ArrayList<>();
Intent intent = getIntent();
imageList = intent.getStringArrayListExtra("IMAGE_LIST");
As we know getSerializable() is deprecated so we can use other easy way to transfer array between activities or between fragment to activities:
First initialize Array of Cars:
private var carsList = ArrayList<Cars>()
On sending Activity/Fragment side:
val intent = Intent(mContext, SearchActivity::class.java)
intent.putExtra("cars_list", Gson().toJson(carsList))
startActivity(intent)
On Receiving Activity:
val type: Type = object : TypeToken<List<CarsModel?>?>() {}.type
categoryList = Gson().fromJson(intent.getStringExtra("cars_list"), type)
I had the exact same question and while still hassling with the Parcelable, I found out that the static variables are not such a bad idea for the task.
You can simply create a
public static ArrayList<Parliament> myObjects = ..
and use it from elsewhere via MyRefActivity.myObjects
I was not sure about what public static variables imply in the context of an application with activities. If you also have doubts about either this or on performance aspects of this approach, refer to:
What's the best way to share data between activities?
Using static variables in Android
Cheers.

How to store a value in HashMap (Android)?

im worked in soap message, using SAXparser to retrieve the value(from Webservice) stored in ArrayList and the ArrayList working fine, but i want to store in HashMap, because Using key to identify a each name has certain SystemId, Please any one help me
Thanks
I tried the code:
public class SitesList
{
private ArrayList<String> name = new ArrayList<String>();
private ArrayList<String> systemid = new ArrayList<String>();
//Map <String,String> map = new HashMap<String,String>();
public ArrayList<String> getName()
{
return name;
}
public void setName(String nameString)
{
this.name.add(nameString);
System.out.println("name "+ name);
}
public ArrayList<String> getSystemId()
{
return systemid;
}
public void setSystemId(String systemidString)
{
this.systemid.add(systemidString);
System.out.println("systemid "+systemid);
}
you can store like this way
you arraylist for name
private ArrayList<String> name = new ArrayList<String>();
and HashMap like this way
HashMap<String, ArrayList<String>>h = new HashMap<String, ArrayList<String>>();
and you can store your arraylist like this way
h.put("name", name);
If you don't need to preserve the order of entries, you can do something like this:
public class SitesList {
private final Map <String,String> map = new HashMap<String,String>();
public Set<String> getNames() {
return map.keySet();
}
public void add(String nameString, String systemidString) {
map.put(nameString, systemidString);
}
public Collection<String> getSystemIds() {
return map.values(); // may contain duplicates
}
}

How to reuse the Parcelable object in Android?

I have the class that implements Parcelable interface. That contain HashMap, this HashMap contains bitmap images. I need this HashMap for all my activities. So I used Parcelable. Look on my Parcelable code.
private HashMap<String, Bitmap> map;
public ParcelFullData() {
map = new HashMap();
}
public ParcelFullData(Parcel in) {
map = new HashMap();
readFromParcel(in);
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public ParcelFullData createFromParcel(Parcel in) {
return new ParcelFullData(in);
}
public ParcelFullData[] newArray(int size) {
return new ParcelFullData[size];
}
};
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(map.size());
for (String s: map.keySet()) {
dest.writeString(s);
dest.writeValue(map.get(s));
}
}
public void readFromParcel(Parcel in) {
int count = in.readInt();
for (int i = 0; i < count; i++) {
map.put(in.readString(), (Bitmap)in.readValue(Bitmap.class.getClassLoader()));
}
}
public Bitmap get(String key) {
return map.get(key);
}
public String[] getKeys() {
Set<String> mapset = map.keySet();
String[] photoName = new String[mapset.size()];
Iterator<String> itr = mapset.iterator();
int index = 0;
while (itr.hasNext()) {
String name = itr.next();
photoName[index] = name;
index++;
}
return photoName;
}
public void put(String key, Bitmap value) {
map.put(key, value);
}
public HashMap<String, Bitmap> getHashMap() {
return map;
}
This will working fine when i pass the one Activity to another Activity.( For example Activity A to Activity B.) But If I pass this to another Activity( For example Activity B to Activity C.) means that HashMap contains no elements. That size is 0.
In Activity_A,
Intent setIntent = new Intent(activity_a, Activity_B.class);
ParcelFullData parcelData = new ParcelFullData();
Bundle b = new Bundle();
b.putParcelable("parcelData", parcelData);
startActivity(setIntent);
In Activity_B
ParcelFullData parcelData = (ParcelFullData)bundle.getParcelable("parcelData");
Parcel parcel = Parcel.obtain();
parcel.writeParcelable(parcelData , 0);
parcelData.writeToParcel(parcel, 0);
Intent setIntent = new Intent(activity_a, Activity_B.class);
Bundle b = new Bundle();
b.putParcelable("parcelData", parcelData);
startActivity(setIntent);
I'm doing the same in Activity C.
How to use resolve this?
Why do you use bundle? You don't add this bundle to intent. Use Intent.putExtra(String, Parcelable) and everything will be OK. I pass one Parcelable object through all activities in my app and it works fine.
In first activity:
Intent i = new Intent(activity_a, Activity_B.class);
i.putExtra("parcelData", parcelData);
In second activity:
parcelData = getIntent().getParcelableExtra("parcelData");
// ... do anything with parcelData here
Intent i = new Intent(activity_b, Activity_C.class);
i.putExtra("parcelData", parcelData);

Categories

Resources