alternative for Bundle.putLongArrayList() - android

I have an ArrayList<Long> object that i would like to retain on orientation change of my fragment. But the Bundle class does not have a putLongArrayList() method. I do see putParcelableArrayList(), putIntegerArrayList() and putStringArrayList().
Is there any reason why the Long version of the method is not defined? Is there a simple workaround for this other than creating wrapper parcelable class for the Long objects and then using putParcelableArrayList()?

I think this is the method you should use for that
You will have to convert the ArrayList to an Array before you're able to put it in the Bundle, though.
When you get the LongArray from the Bundle, you can convert it back to an ArrayList so you can perform list like operations on it again.
Putting in Bundle
long[] array = new long[yourArrayList.size()];
for(int i=0;i<yourArrayList.size();i++){
array[i] = yourArrayList.get(i);
}
Bundle b = new Bundle();
b.putLongArray("longs", array);
Getting from Bundle
long[] array = b.getLongArray("longs");
for(int i=0; i<array.length;i++) arrayList.add(array[i])

Related

How to send an array of objects to a new intent

I am trying to send an array of objects to a new intent, but the problem is that I don't know how to send the whole array at once. The method I managed to get it working is adding object by object, in a for loop, and in the second activity I have to get them one by one, something like this:
Main activity:
Intent newIntent = new Intent(mainA.this, secondA.class);
for(int i=0;i<numberOfObjects;i++)
newIntent.putExtra("object"+i,myObjects[i]);
newIntent.putExtra("length", x);
startActivity(newIntent);
Second activity:
Serializable n = getIntent().getSerializableExtra("length");
int x = Integer.parseInt(n.toString());
myObjects = new objClass[x];
for(int i=0;i<x;i++)
myObjects[i] = (objClass) getIntent().getSerializableExtra("object"+i);
Even if this method works, and gets me the right results, isn't there a better/faster/cleaner solution?(I searched a lot, but haven't found a better way, maybe I don't know what exactly to look for).
Make your object serializable and put all objects in a Arraylist and send it.ArrayList itself implements serializable.
Intent newIntent = new Intent(mainA.this, secondA.class);
newIntent.putExtra("list",listOfObjets);
startActivity(newIntent);
Second Activity:
ArrayList<YourObjects> list = (ArrayList<YourObjects>)getIntent().getSerializableExtra("list");
Hi you can try this as well.. Create setter getter class which will set and get your object. next create the array list of your setter getter class.next add all objects into arraylist using set method in for loop. next add that arraylist object into bundle using setArguments.
Same you can access that bundle using getArguments that's it.

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

Passing Bundle into an AsyncTask

I'm struggling with bundles in an AsyncTask. I have two Strings that I want to pass to a AsyncTask, I want to use bundles to accomplish this task.
The code in the MainActivity:
Bundle adresses = new Bundle();
adresses.putString("to", textField1.getText().toString());
adresses.putString("from", textField2.getText().toString());
new PriceTask(getApplicationContext()).execute(adresses);
And in my AsycTask I do it like this:
protected Integer doInBackground(Bundle... b) {
Bundle result = b[0];
String to = result.getString("to");
String from = result.getString("from");
}
It's worth mentioning that my two strings contains something like this
"Sometext here, and sometext here 1234"
Put I can't retrieve the text, my debugger says that the Bundle contains the right information but my String will not contain the right information. When I debug and set breakpoints where my Strings are, it will just have the value:
[t, o]
What am I doing wrong here? Thanks in advance.
In MAin activity replace the below lines::
Bundle adresses = new Bundle();
adresses.putString("to", textField1.getText().toString());
adresses.putString("from", textField2.getText().toString());
new PriceTask(getApplicationContext()).execute(adresses);
with
new PriceTask(getApplicationContext(),textField1.getText().toString(),textField2.getText().toString()).execute();
And in your AsycTask add constructor like below::
String to;
String from;
Context context;
public YourAsyncTask(Context context, String to,String from) {
// TODO Auto-generated constructor stub
this._activity = _activity;
this.to = to;
this.from = from;
}
What you are doing wrong is the way you retrieve the data in the doInBackground method. The argument that method having is a Array type. Please concern the ... What you are doing in the line Bundle result = b[0]; is only getting the 0th element of that Array and pass it to a Bundle reference.
Your given code and details is not enough to give a perfect answer. If all your given codes in the same Java class, you no need to use a Bundle. Instead you can create a ArrayList of type String to contains your values witch you are getting from the TextFields. Then doInBackground also contains a ArrayList as the method argument. Then get all the List items and separate your "to" and "from" values.
If you are stick with the existing code, first try to find out what is inside the result variable.

Bundle of array of arraylist

How can I put an array of arrayList into a Bundle?
ArrayList < myObjects >[] mElements;
Make YourObject implement the Parcelable interface, then use bundle.putParcelableArraylist(theParcelableArraylist).
Edit: whoops misread the question. Why do you want to save an array of arraylist? If its for persisting in an orientation change, maybe you want to use onRetainNonConfigurationInstance instead?
Edit 2: Ok, here goes. Create a new Wrapper class that implements Parcelable (note that myObjects also have to be parcelable). The writeToParcel method will look something like this:
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(mElements.length);
for(ArrayList<MyObject> element : mElements) {
dest.writeParcelableArray(element.toArray(new MyObject[0]), flags);
}
}
And the constructor:
private Wrapper(Parcel in) {
int length = in.readInt();
//Declare list
for (int i = 0; i < length; i++) {
MyObject[] read = in.readParcelableArray(Wrapper.class.getClassLoader());
//add to list
}
}
Not possible using bundle, as bundle allows arraylist of primitives only...
Try to use parcleable or application level data or static variable (bad practice).
If your objects support serialization, marked with the Serializable interface, then you should be able to use bundle.putSerializable.
ArrayList supports Serializable , but I'm not sure about a plain array.
I just use putSerializable(myarraylistofstuff) and then I get back with a cast using get(), you just need to silence the unchecked warning. I suspect (correct me if wrong) you can pass any object faking it as Serializable, as long you stay in the same process it will pass the object reference. This approach obviously does not work when passing data to another application.
EDIT: Currently android passes the reference only between fragment, I've tried to pass an arbitrary object to an Activity, it worked but the object was different, same test using arguments of Fragment showed same Object instead.
Anyway it deserializes and serializes fine my Object, if you have a lot of objects it's better to use Parcel instead

Bundle does not fully received

I am facing a problem with sending data through the bundle.
Intent toAudio = new Intent(TourDescription.this, Audio.class);
toAudio.putParcelableArrayListExtra("poi", arraypoi);
startActivity(toAudio);
here am sending arraypoi which is an ArrayList. This ArrayList contains a set of values.
And in the receiving class, I have like this
listOfPOI = getIntent().getParcelableArrayListExtra("poi");
Collections.sort(listOfPOI);
where listOfPOI is also an array list.
The problem am facing is, I am not able to receive values for 3 particular variables in listOfPOI (coming as null), rest all values are coming proper.
While sending the bundle, I mean in arraypoi also I am able to send all the values correctly but the problem is while receiving it.
Note: My class is implemented as parcelable only.
Any answer for this?
There are two workarounds in my point of view.
First:
You need to make YourOwnArrayList as subclass of ArrayList<YourObject> and implements Parcelable.
Tutorial Here
Second:
pass your Object using for() loop. like this.
Intent toAudio = new Intent(TourDescription.this, Audio.class);
toAudio.putExtra("SIZE", arraypoi.size());
for(int i=0; i<arraypoi.size(); i++)
toAudio.putExtra("POI"+i, arraypoi.get(i));
startActivity(toAudio);
and while getting in other class
Bundle data = getIntent().getExtras();
int size=data.getInt("SIZE");
for(int i=0; i<size; i++)
listOfPOI.add((YOUR_OBJECT) data.getParcelable("POI"+i));
YOUR_OBJECT is the class name of your Object.

Categories

Resources