ArrayList and Parcelable - android

I need to "transfer" an ArrayList of custom class from one entity to another. I know that I need to implement Parcelable interface.
This is my custom class.
public class cSportsList implements Parcelable {
boolean checked;
String name;
cSportsList(boolean check, String name_) {
checked = check;
name = name_;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
//Non posso passare un booleano e non posso fare il cast boolean -> int
if (checked) {
dest.writeInt(1);
}
else dest.writeInt(0);
dest.writeString(name);
}
public static final Parcelable.Creator<cSportsList> CREATOR = new Parcelable.Creator<cSportsList>() {
public cSportsList createFromParcel(Parcel in) {
return new cSportsList(in);
}
public cSportsList[] newArray(int size) {
return new cSportsList[size];
}
};
private cSportsList(Parcel in) {
if (in.readInt() == 1) {
checked = true;
}
else {
checked = false;
}
name = in.readString();
}
}
And this is the code in entity "from"
//This is sportsMap: ArrayList<cSportsList> sportsMap = new ArrayList<cSportsList>();
Intent intent = new Intent(getApplicationContext(),WhatSportActivity.class);
intent.putParcelableArrayListExtra("sportsMap", (ArrayList<? extends Parcelable>) sportsMap); //I have tried with ArrayList<cSportsList> too.
this.startActivity(intent);
And this is the code in entity "to"
final Intent srcIntent = getIntent();
ArrayList<cSportsList> sportsMap = srcIntent.getParcelableExtra("sportsMap");
The problem is: in entity "To" sportsMap is null.
If I set "breakpoint" in "writeToParcel" and "cSportsList(Parcelable in)" functions I see that the code is executed for both functions.
Where is my error ?
Thanks. M.

While reading you need to use
srcIntent.getParcelableArrayListExtra("sportsMap");
To put into Intent use below code
intent.putParcelableArrayListExtra("sportsMap", sportsMap);
and to read it from intent, use
ArrayList<cSportsList> sportsMap = srcIntent.getParcelableArrayListExtra("sportsMap");
Read similar solution at Pass ArrayList<? implements Parcelable> to Activity

Use the below code
sportsMap = srcIntent.getParcelableArrayListExtra("sportsMap");

You should use :
ArrayList<cSportsList> sportsMap = srcIntent.getParcelableArrayListExtra("sportsMap");

You can also use Serialization for the same.
public class cSportsList implements Serializable
for put:
intent.putExtra("LIST",list);
for get:
(ArrayList<>)intent.getSerializableExtra("LIST");

Try passing Arraylist instead of casting it like this:
Intent intent = new Intent(getApplicationContext(),WhatSportActivity.class);
intent.putParcelableArrayListExtra("sportsMap", sportsMap);
startActivity(intent);
In WhatSportActivity,
final Intent srcIntent = getIntent();
ArrayList<cSportsList> sportsMap = srcIntent.getParcelableExtra("sportsMap");
In case you still have problems,please try implementing Parceable by using "Parceable"plugin as It reduces the error in using Parceable lists.

Related

Parcelable how to use the 'KEY' value when receiving all the information?

I'm making an Android application and I would like to send an ArrayList to the next Activity, but I don't know how to do this with Parcelable.
For example: I got an int named as ID and a String named as Names. I use JSON for getting all informations from PHP and MySQL.
In the for-loop I add all those Names and ID to a class. But then I don't know how to write all these Names and ID into a bundle.putParcelableArrayList(KEY, ArrayList...);, because I don't know how to do this with the KEY value. Do I need to give the KEY value numbers or is there automatically one KEY?
class alleDeelnemers implements Parcelable {
int id;
String name;
/* GETTER AND SETTER */
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeString(volgnummer);
}
public alleDeelnemers(Parcel in) {
volgnummer = in.readString();
id = in.readInt();
}
// Creator
public static final Parcelable.Creator CREATOR
= new Parcelable.Creator() {
public alleDeelnemers createFromParcel(Parcel in) {
return new alleDeelnemers(in);
}
public alleDeelnemers[] newArray(int size) {
return new alleDeelnemers[size];
}
};
}
Receiving data:
ArrayList<alleDeelnemers> deelnemers = new ArrayList<>();
for(int i=0; i < jArrayDeelnemer.length(); i++)
{
JSONObject json_data = jArrayDeelnemer.getJSONObject(i);
//class alleDeelnemers
deelnemer = new alleDeelnemers();
//ID
int ID = json_data.getInt("ID");
deelnemer.setId(ID);
//alle deelnemers
String name = json_data.getString("name ");
deelnemer.setName(name );
//toevoegen in de class
deelnemers.add(deelnemer);
}
error this line: deelnemer = new alleDeelnemers(); need to build a constructor.
The key is any name you would use to reference your ArrayList. Further in the started activity, you will use this key to retrieve the ArrayList. For example, in the initial activity, do
bundle.putParcelableArrayList("MY_ARRAY_LIST", deelnemers);
and then in the started activity, to retrieve it later
Bundle b = getIntent().getExtras();
ArrayList<alleDeelnemers> list = b.getParcelableArrayList("MY_ARRAY_LIST");
Note that the KEY used here is "MY_ARRAY_LIST". It is a better practice to use xml string constants or an interface for storing constant KEYS.
1.First create your alleDeelnemers class as Parcelable using plug-in
2 Sender Activity
Intent intent = new Intent(this, YourActivity.class);
intent.putExtra("mData", myArrayList);
3 Receiver Activity
myArrayList = getIntent().getParcelableExtra("mData")

Get an object result from an activity in Xamarin with Visual Studio

I want to receive an object back from a child activity in Xamarin with Visual Studio 2015:
[Serializable]
class MyObj
{
public string value { get; }
public MyObj(string v)
{
value = v;
}
}
Child Activity
Intent myIntent = new Intent (this, typeof(FirstActivity));
MyObj obj = new MyObj("message");
myIntent.PutExtra ("obj", obj); // cannot convert "obj" to Bundle
SetResult (Result.Ok, myIntent);
Finish();
FirstActivity
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (requestCode == 0)
if (resultCode == Result.Ok) {
var helloLabel = FindViewById<TextView> (Resource.Id.helloLabel);
MyObj obj = data.GetSerializableExtra("obj") as MyObj;
helloLabel.Text = obj.Text.ToString();
}
}
}
This code causes an error cannot convert obj to Bundle. I've also tried to implement Java.IO.ISerializable is MyObj but I couldn't get a right implementation. It always throws System.NotSupportedException: Unable to activate instance of type MyApp.MyObj from native handle 0x10001d (key_handle 0x1a027cb)
class Object1 : Java.Lang.Object, Java.IO.ISerializable
{
public string value { get; }
public Object1(string v)
{
value = v;
}
}
I would like to get some advice. I'm new in Xamarin and I'm working with Visual Studio 2015
I'd always go for Parcelable. It's very fast! (10x faster) http://www.developerphil.com/parcelable-vs-serializable/
Here is how you implement it in Xamarin:
public class MyObj : Java.Lang.Object, IParcelable
{
public string Value { get; set; }
public MyObj()
{
}
private MyObj(Parcel parcel)
{
// read your values in order
Value = parcel.ReadString();
}
public void WriteToParcel(Parcel dest, ParcelableWriteFlags flags)
{
// read your values in order
dest.WriteString(Value);
}
// -- stuff below here is needed from the parcel interfaces/mechanism --
[ExportField("CREATOR")]
public static MyObjCreator InitializeCreator()
{
return new MyObjCreator();
}
public class MyObjCreator : Java.Lang.Object, IParcelableCreator
{
public Java.Lang.Object CreateFromParcel(Parcel source)
{
return new MyObj(source);
}
public Java.Lang.Object[] NewArray(int size)
{
return new MyObj[size];
}
}
public int DescribeContents()
{
return 0;
}
}
SetResult
Intent myIntent = new Intent(this, typeof(FirstActivity));
MyObj obj = new MyObj {Value = "Hello"};
myIntent.PutExtra("obj", obj);
SetResult(Result.Ok, myIntent);
Finish();
OnActivityResult
var x = (MyObj)data.GetParcelableExtra("obj");
Passing complex objects is a bit tricky. You can use libraries like Json.Net to serialize to string before sending, and then deserialize on the other end.
myIntent.PutExtra ("obj", JsonConvert.SerializeObject(obj));
//in your receiving activity OnActivityResult...
var objectAsString = intent.GetStringExtra("obj")
var result = JsonConvert.DeserializeObject<MyObject>(objectAsString)
Nice and easy solution and well performing too..

How to pass ArrayList<CustomeObject> from one activity to another? [duplicate]

This question already has answers here:
Passing arraylist of objects between activities
(6 answers)
Passing a List from one Activity to another
(6 answers)
Closed 9 years ago.
I want to send Following ArrayList from one activity to another please help.
ContactBean m_objUserDetails = new ContactBean();
ArrayList<ContactBean> ContactLis = new ArrayList<ContactBean>();
I am sending the above arraylist after adding data in it as follows
Intent i = new Intent(this,DisplayContact.class);
i.putExtra("Contact_list", ContactLis);
startActivity(i);
But I am getting problem while recovering it.
ArrayList<ContactBean> l1 = new ArrayList<ContactBean>();
Bundle wrapedReceivedList = getIntent().getExtras();
l1= wrapedReceivedList.getCharSequenceArrayList("Contact_list");
At this point I am getting this error:
Type mismatch: cannot convert from ArrayList<CharSequence> to ArrayList<ContactBean>
My ContactBean class implements Serializable please also tell why we have to implement serializable interface.
In First activity:
ArrayList<ContactBean> fileList = new ArrayList<ContactBean>();
Intent intent = new Intent(MainActivity.this, secondActivity.class);
intent.putExtra("FILES_TO_SEND", fileList);
startActivity(intent);
In receiver activity:
ArrayList<ContactBean> filelist = (ArrayList<ContactBean>)getIntent().getSerializableExtra("FILES_TO_SEND");`
you need implements Parcelable in your ContactBean class, I put one example for you:
public class ContactClass implements Parcelable {
private String id;
private String photo;
private String firstname;
private String lastname;
public ContactClass()
{
}
private ContactClass(Parcel in) {
firstname = in.readString();
lastname = in.readString();
photo = in.readString();
id = in.readString();
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(firstname);
dest.writeString(lastname);
dest.writeString(photo);
dest.writeString(id);
}
public static final Parcelable.Creator<ContactClass> CREATOR = new Parcelable.Creator<ContactClass>() {
public ContactClass createFromParcel(Parcel in) {
return new ContactClass(in);
}
public ContactClass[] newArray(int size) {
return new ContactClass[size];
}
};
// all get , set method
}
and this get and set for your code:
Intent intent = new Intent(this,DisplayContact.class);
intent.putExtra("Contact_list", ContactLis);
startActivity(intent);
second class:
ArrayList<ContactClass> myList = getIntent().getParcelableExtra("Contact_list");
Use this code to pass arraylist<customobj> to anthother Activity
firstly serialize our contact bean
public class ContactBean implements Serializable {
//do intialization here
}
Now pass your arraylist
Intent intent = new Intent(this,name of activity.class);
contactBean=(ConactBean)_arraylist.get(position);
intent.putExtra("contactBeanObj",conactBean);
_activity.startActivity(intent);

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.

Broadcast not received when intent contains parcelable extra

I have an IntentService that is making a network call and receiving back some JSON data. I package this response data in custom object that implements parcelable. If I add this parcelable object to an intent as an extra and then launch an activity using that intent, everything seems to work as expected, i.e. I can retrieve the parcelable from the intent in the newly created activity. However, if I create the intent from within the onHandleIntent() method of my IntentService and then use sendBroadcast(), the broadcast receiver's onReceive() method never fires. If I don't add the parcelable to the intent, though, the onReceive() method fires as expected. Following are some relevant code snippets:
Parcelable Object:
public class JsonResponse implements Parcelable {
private int responseCode;
private String responseMessage;
private String errorMessage;
public JsonResponse() {
}
/*
/ Property Methods
*/
public void setResponseCode(int code) {
this.responseCode = code;
}
public void setResponseMessage(String msg) {
this.responseMessage = msg;
}
public void setErrorMessage(String msg) {
this.errorMessage = msg;
}
/*
/ Parcelable Methods
*/
public static final Creator<JsonResponse> CREATOR = new Creator<JsonResponse>() {
#Override
public JsonResponse createFromParcel(Parcel parcel) {
return new JsonResponse(parcel);
}
#Override
public JsonResponse[] newArray(int i) {
return new JsonResponse[i];
}
};
private JsonResponse(Parcel parcel) {
responseCode = parcel.readInt();
responseMessage = parcel.readString();
errorMessage = parcel.readString();
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeInt(responseCode);
parcel.writeString(responseMessage);
parcel.writeString(errorMessage);
}
#Override
public int describeContents() {
return 0;
}
}
onHandle() of IntentService:
protected void onHandleIntent(Intent intent) {
service = new LoginService();
service.login("whoever", "whatever");
JsonResponse response = new JsonResponse();
response.setResponseCode(service.responseCode);
response.setResponseMessage(service.responseMessage);
response.setErrorMessage(service.errorMessage);
Intent i = new Intent();
i.putExtra("jsonResponse", response);
i.setAction(ResultsReceiver.ACTION);
i.addCategory(Intent.CATEGORY_DEFAULT);
sendBroadcast(i);
}
Any ideas? Any insight would be greatly appreciated.
It appears that the problem has to do with the size of the object being added as an extra. When one of the string properties of the response object grows too large, the broadcast apparently fails. I have no sources to confirm this, only some trial and error in manipulating one of the strings while leaving all other variables of the equation constant.

Categories

Resources