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

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..

Related

ArrayList and Parcelable

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.

Google Analytics deserialization with Gson is returning LinkedTreeMap

I'm trying to pass an object containing Analytics Reporting data in an Intent via a broadcast. The problem is the deserialization which returns a LinkedTreeMap instead of the original serialized object, causing a crash with ClassCastException.
I tried to follow quite all answers found here on SO, from using TypeToken to modify ProGuard rules and nothing worked.
I thought to implement Parcelable interface but the problem is that I have an inner private AsyncTask class where the data is collected and pushed into the intent which will be sent via broadcast.
Here is the code of the helper where data is serialized:
public class AnalyticsHelper
{
...
private class GoogleBatchTask extends AsyncTask<GetReportsRequest,Void,GetReportsResponse>
{
#Override
protected GetReportsResponse doInBackground(#NonNull GetReportsRequest... reports)
{
GetReportsResponse response = null;
try {
if (m_reports == null)
return null;
response = m_reports.reports().batchGet(reports[0]).execute();
} catch (IOException e) {
Console.log(e);
}
return response;
}
#Override
protected void onPostExecute(GetReportsResponse response)
{
Intent intent = new Intent();
intent.setAction("com.keyone.contactpackapp.ANALYTICS_DATA");
intent.putExtra("response", new Gson().toJson(response));
Context context = PackConfig.instance().context();
if (context == null)
return;
context.sendBroadcast(intent);
}
}
}
AnalyticsFragment.java, where the deserialization happens:
public class AnalyticsFragment extends Fragment
{
#Override
public void onResume()
{
super.onResume();
// Listen to custom intent with data
IntentFilter filter = new IntentFilter("com.keyone.contactpackapp.ANALYTICS_DATA");
m_receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent)
{
// Get data from intent and pass it to the right fragment
String szJson = intent.getStringExtra("response");
//m_response = new Gson().fromJson(szJson, GetReportsResponse.class);
Type listType = new TypeToken<GetReportsResponse>(){}.getType();
m_response = new Gson().fromJson(szJson, listType);
Fragment fragment = m_activity.currentFragment();
fragment.updateData();
}
};
if (m_activity != null)
m_activity.registerReceiver(m_receiver, filter);
}
}
There was no way to deserialize object in a correct way using Gson neither using Java Serializable interface or Android Parcelable interface due to the nature of the objects to serialize.
So I opted to call an instance of the recipient class and pass object data through a method in it

How to pass List via intent from one activity to another activity in android using xamarin

i am new to Xamarin. I need to pass List of data as from one activity to another activity via intent .and get those data in another activity screen and process those data's. Please suggest a solution.
Thanks in advance
Use IList of generic type to pass data to the required data from one activity to another.
IList<String> Mon_year = new List<String>();
then pass this List in the intent
i.PutStringArrayListExtra("month_year",Mon_year);
In Another activity(where you want to get the sent data)
IList<String> Mon_year = Intent.GetStringArrayListExtra("month_year") ;// here u get the Ilist of String data...
I approached this a bit differently. I created a base class which inherited from Java.Lang.Object, ISerializable so that I could use Bundle.PutSerializable(string key, ISerializable value) to pass my objects between Activities.
[Flags]
public enum ObjectState
{
Normal = 0,
New = 1,
Modified = 2,
Removed = 4
}
public abstract class ObjectBase : Java.Lang.Object, ISerializable
{
public Guid Id { get; set; }
public ObjectState State { get; set; }
protected ObjectBase(IntPtr handle, JniHandleOwnership transfer) : base(handle, transfer)
{
}
protected ObjectBase()
{
}
[Export("readObject", Throws = new[] { typeof(IOException), typeof(Java.Lang.ClassNotFoundException) })]
private void ReadObject(ObjectInputStream stream)
{
this.Deserialize(stream);
}
[Export("writeObject", Throws = new[] { typeof(IOException), typeof(Java.Lang.ClassNotFoundException) })]
private void WriteObject(ObjectOutputStream stream)
{
this.Serialize(stream);
}
protected virtual void Deserialize(ObjectInputStream stream)
{
this.Id = Guid.Parse(stream.ReadUTF());
this.State = (ObjectState)stream.ReadInt();
}
protected virtual void Serialize(ObjectOutputStream stream)
{
stream.WriteUTF(this.Id.ToString());
stream.WriteInt((int)this.State);
}
}
public class Person : ObjectBase
{
public string Name { get; set; }
public int Age { get; set; }
public bool IsMarried { get; set; }
public DateTime? Anniversary { get; set; }
protected override void Deserialize(ObjectInputStream stream)
{
base.Deserialize(stream);
if (stream.ReadBoolean())
this.Name = stream.ReadUTF();
this.Age = stream.ReadInt();
this.IsMarried = stream.ReadBoolean();
if (stream.ReadBoolean())
this.Anniversary = DateTime.Parse(stream.ReadUTF());
}
protected override void Serialize(ObjectOutputStream stream)
{
base.Serialize(stream);
stream.WriteBoolean(this.Name != null);
if (this.Name != null)
stream.WriteUTF(this.Name);
stream.WriteInt(this.Age);
stream.WriteBoolean(this.IsMarried);
stream.WriteBoolean(this.Anniversary != null);
if (this.Anniversary != null)
stream.WriteUTF(this.Anniversary.Value.ToString(CultureInfo.InvariantCulture));
}
}
I can then pass a list of Person objects to a new Activity by doing:
List<Person> persons = new List<Person>();
var intent = new Intent(this, typeof(MyActivity));
var bundle = new Bundle();
for (int i = 0; i < persons.Count; i++)
{
var p = persons[i];
bundle.PutSerializable("Person" + i, p);
}
intent.PutExtras(bundle);
this.StartActivity(intent);
Then Recieve the objects like so:
protected override void OnCreate(Bundle bundle)
{
List<Person> persons = new List<Person>();
int i = 0;
while (bundle.ContainsKey("Person" + i))
{
var p = (Person) bundle.GetSerializable("Person" + i);
persons.Add(p);
i++;
}
base.OnCreate(bundle);
}
For passing a list of content from one activity to other activity you can use parcelable class. Its a type of bundle in which we can pass any type of content from one activity to other activity. The only thing is you just need to customize the parcelable class according to your need.
Please visit this Link or download this sample project so that you can understand more about passing list of content from one activity to other activity.
Hope this will solve your problem.

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