Android. Passing this custom object to next Activity? - java

I have this custom object which I want to pass to a different Activity:
public class FindRouteOutputForDisplay {
public ArrayList<VertexDisplay> vertexDisplayArrayList;
public ArrayList<Integer> integerArrayList;
}
I tried this, but doesn't work.
Intent newIntent = new Intent(FirstActivity.this, SecondActivity.class);
FindRouteOutputForDisplay data = getMyData();
newIntent.putExtra("data", data); // Error
startActivity(newIntent);
Should I pass
public ArrayList<VertexDisplay> vertexDisplayArrayList;
public ArrayList<Integer> integerArrayList;
separately one-by-one? Any way to pass all of them at once?

You can try this solution.
public class FindRouteOutputForDisplay implements Serializable{
public ArrayList<VertexDisplay> vertexDisplayArrayList;
public ArrayList<Integer> integerArrayList;
}
Intent newIntent = new Intent(FirstActivity.this, SecondActivity.class);
FindRouteOutputForDisplay data = getMyData();
newIntent.putSerializable("data", data);
startActivity(newIntent);
If you have any errors on "putSerializable" so you can cast your object to Serializable in this way.
newIntent.putSerializable("data", (Serializable)data);
And in your activity just get your data by this
FindRouteOutputForDisplay data = getIntent().getSerializable("data");
Hope it helps.

Save your data in your application context class. Since this class is available across your application instance, you can get or set the variables defined inside this class from all activities. More info here

Change this :
startActivity(routeDetailIntent);
To :
startActivity(newIntent);

You should make the custom objects implement the Parcelable interface:
public class MyParcelable implements Parcelable {
private int mData;
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeInt(mData);
}
public static final Parcelable.Creator<MyParcelable> CREATOR
= new Parcelable.Creator<MyParcelable>() {
public MyParcelable createFromParcel(Parcel in) {
return new MyParcelable(in);
}
public MyParcelable[] newArray(int size) {
return new MyParcelable[size];
}
};
private MyParcelable(Parcel in) {
mData = in.readInt();
}
}
You can also have a look here if you want other solutions.

I have a trick for you. Add Gson to your dependencies.
repositories {
mavenCentral()
}
dependencies {
compile 'com.google.code.gson:gson:2.2.4'
}
Convert your object to Json and ship it as a String.
String data = new Gson().toJson(getMyData())
Convert it back from String in a new Activity
FindRouteOutputForDisplay data = new Gson(stringData, FindRouteOutputForDisplay.class).

You can make the class static and use it anywhere in your app.

you have passed wrong intent to start activity.
Intent newIntent = new Intent(FirstActivity.this, SecondActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable("value", data );
newIntent.putExtras(bundle);
startActivity(newIntent );

I also face this problem so I'm trying this below code:
Pass the object with intent
In starting activity we can set the parcelable object to an intent
User user = new User("1", "u", "u", "u");
ArrayList<User> userList = new ArrayList<User>();
Sensor sensor = new Sensor("1", "s", "s", true, user, userList);
intent.putExtra("com.score.senzors.pojos.Sensor", sensor);
In destination activity we can get the parcelable object from intent extras(bundle)
Bundle bundle = getIntent().getExtras();
Sensor sensor = bundle.getParcelable("com.score.senzors.pojos.Sensor")
Hope it Helps you

Related

Send an Arraylist of an object from one activity to another

I need to duplicate an ArrayList from one activity from another.
This is an ArrayList of an object that I named Dias, and it contains a String and a boolean:
Arraylist {Dias} // Dias contains(String Dias, boolean estado)
And I have to pass this ArrayList to other activity.
My Dias class:
public class Dias {
private String Dia;
private boolean estado;
//CONSTRUCTOR DE LA CLASE//
public Dias(String Dia, boolean estado) {
this.Dia = Dia;
this.estado = estado;
}
//GETTERS Y SETTERS DE LA CLASE//
public String getDia() {
return Dia;
}
public void setDia(String dia) {
Dia = dia;
}
public boolean isChekeado() {
return estado;
}
public void setChekeado(boolean chekeado) {
estado = chekeado;
}
}
My Primary Class:
public class Primera extends Activity {
ArrayList<Dias> dias = new ArrayList<Dias>();
//OnClick Method
public void lanzar2(View view){
dias.add(new Dias("Lu", false));
dias.add(new Dias("MAr", false));
Intent i = new Intent();
Bundle b = new Bundle();
b.putParcelableArrayList("arreglo", (ArrayList<? extends Parcelable>) dias);
i.putExtras(b);
i.setClass(this, ListasActivity.class);
startActivity(i);
}
}
How can I send my Arraylist to another activity?, I just don't understand how does it work(parcelable) and also I don't know the syntax to use it.
Thank you!
Another simple method is to serialize it in your own way.
For example:
If you have 5 elements in your arraylist like "hello", "how" , "are", "you", "brother". You can loop through the arraylist and make a string as hello,how,are,you,brother
String serializedString = "";
for(String anElement:arrayList)
serilaizedString = serializedString + "," +anElement;
and send it to another activity using putExtra method of Intent.
And in the receiving end, you can split the text using split(",") then you will get an array which you can change to array list again if needed.
String[] myArray = recievedString.split(",");
List<String> myList = new List<String>();
for(String anElement:myList)
myList.add(anElement);
Now you have myList as the array list.
P.S. Your strings shouldn't contain any comma though. So for cases with comma, you can use something like $ or % or what ever is comfortable for case.
You have to implement the interface Parcelable in the object Dias. You can see more about how to do it here: http://developer.android.com/reference/android/os/Parcelable.html
Besides that you would send through an Intent that you use to start the other activity the ArrayList using the method:
)">intent.putParcelableArrayListExtra(nameToSaveAs, yourList)
Then you startActivity(intent) and you can receive the data in the other activity with getIntent().getParcelableArrayListExtra(nameToSaveAs); You will probably have to cast it, but that is the basic steps to pass ArrayLists.
You can pass it either using Serialization or by using Parcelable interface. Refer to this for Parcelable interface http://developer.android.com/reference/android/os/Parcelable.html.

Sane way to go from ArrayList<Long> through an Intent

I'm currently writing an app that pulls an array of longs from a server via json, and then passes that list from one activity into another. The basic skeleton looks like this:
public void onResponse(Map result)
{
ArrayList handles= (ArrayList)result.get("fileHandles");
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("handles", handles);
}
So the first problem becomes evident, the only methods for putExtra are putIntegerArrayListExtra, putStringArrayListExtra, putCharSequenceArrayListExtra, and putParcelableArrayListExtra. Thinking Long would probably be parcelable, I was wrong it doesn't work (even if I use ArrayList<Long>). Next I thought I'd just pass a long [], however I see no straight-forward conversion to go from ArrayList<Long> to long [] that intent.putExtra will accept. This was the solution I finally ended up with:
ArrayList handles= (ArrayList)result.get("fileHandles");
long [] handleArray = new long[handles.size()];
for (int i = 0; i < handles.size(); i++)
{
handleArray[i] = Long.parseLong(handles.get(i).toString());
}
Obviously this seemed a little bit ridiculous to me, but every other conversion I tried seemed to complain for one reason or another. I've thought about re-thinking my serialization to have the problem taken care of before I get to this point, but I find it odd that passing ArrayList<Long> from activity to activity could be so difficult. Is there a more obvious solution I'm missing?
You can use it as a Serializable extra. ArrayList is Serializable and Long extends Number which also implements Serializable:
// Put as Serializable
i.putExtra("handles", handles);
// Unfortunately you'll get an unsafe cast warning here, but it's safe to use
ArrayList<Long> handles = (ArrayList<Long>) i.getSerializableExtra("handles");
Two options: Use Parcelable or Serializable
in:
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("handles", new FileHandles(handles));
out:
FileHandles handles = intent.getParcelableExtra("handles");
object:
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
import java.util.List;
public class FileHandles implements Parcelable {
private final List<Long> fileHandles;
public FileHandles(List<Long> fileHandles) {
this.fileHandles = fileHandles;
}
public FileHandles(Parcel in) {
int size = in.readInt();
long[] parcelFileHandles = new long[size];
in.readLongArray(parcelFileHandles);
this.fileHandles = toObjects(size, parcelFileHandles);
}
private List<Long> toObjects(int size, long[] parcelFileHandles) {
List<Long> primitiveConv = new ArrayList<Long>();
for (int i = 0; i < size; i++) {
primitiveConv.add(parcelFileHandles[i]);
}
return primitiveConv;
}
public List<Long> asList() { // Prefer you didn't use this method & added domain login here, but stackoverflow can only teach so much..
return fileHandles;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(fileHandles.size());
dest.writeLongArray(toPrimitives(fileHandles));
}
private static long[] toPrimitives(List<Long> list) {
return toPrimitives(list.toArray(new Long[list.size()]));
}
public static long[] toPrimitives(Long... objects) {
long[] primitives = new long[objects.length];
for (int i = 0; i < objects.length; i++)
primitives[i] = objects[i];
return primitives;
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
#Override
public FileHandles createFromParcel(Parcel in) {
return new FileHandles(in);
}
#Override
public FileHandles[] newArray(int size) {
return new FileHandles[size];
}
};
}
Serializable (forced to use ArrayList which implements Serializable (List does not)
in:
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("handles", new ArrayList<Long>());
out:
ArrayList handles = (ArrayList) intent.getSerializableExtra("handles");

pass Object to another activity

I have found this way to do this
Student student = new Student (18,"Z r");
Intent i = new Intent(this, B.class);
i.putExtra("studentObject", student);
startActivity(i);
The problem is that if the object changed in the first activity No change took place in the another activity.
I thought how to make it like a constructor that no copy of the object is pass but the object it self.
Thanks
How about if you configure the "object" as a singleton of the entire application? This way, everybody (your app) sees the changes... See some insights here: http://developer.android.com/guide/faq/framework.html#3
For example, in some other file (Student.java):
public class Student {
public String Name;
}
Create a custom application class:
public MyApp extends Application {
private Student obj = new Student();
public Student getMyObject() {
return obj;
}
}
Anywhere in your application (e.g. SomeActivity.java):
Student appStudent = ((MyApp) getActivity().getApplicationContext()).getMyObject();
appStudent.Name = "New Name"; // "global" update
You could also look into a BroadcastReceiver. With a BroadcastReceiver you can send a message from one Activity to another and with an interface you can pass the object from one Activity to the other.
I think this is a great example, where a BroadcastReceiver is created to check the internet connection of the device. But you can easily convert this in a BroadcastReceiver with your own custom action to send the object.
Implement parcelable in your student class and you can copy the student into the intent.
How can I make my custom objects Parcelable?
Code works with parcelable classes
> Student student = new Student (18,"Zar E Ahmer"); Intent i = new
> Intent(this, B.class); i.putExtra("studentObject", student);
> startActivity(i);
Below is an example of bean class I use that implements parcelable. Here you would replace KmlMarkerOptions with Student
#SuppressLint("ParcelCreator")
public class KmlMarkerOptions implements Parcelable {
public MarkerOptions markeroptions = new MarkerOptions();
public String href = "";
public int hrefhash =-1;
public String id = "";
public long imageId = -1;
public int locationId = -1;
public int markerSize = -1;
public KmlMarkerOptions(){
}
public KmlMarkerOptions(Parcel in) {
this.markeroptions = in.readParcelable(null);
this.href = in.readString();
this.hrefhash = in.readInt();
this.id = in.readString();
this.imageId = in.readLong();
this.locationId = in.readInt();
this.markerSize = in.readInt();
}
#SuppressWarnings("rawtypes")
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public KmlSummary createFromParcel(Parcel in) {
return new KmlSummary(in);
}
public KmlSummary[] newArray(int size) {
return new KmlSummary[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeParcelable(markeroptions, 0);
dest.writeString(href);
dest.writeInt(hrefhash);
dest.writeString(id);
dest.writeLong(imageId);
dest.writeInt(locationId);
dest.writeInt(markerSize);
}
}

Reading ArrayList in Parcelable

I have a class called SuperMedia that implements Parcelable. One of the fields of the class is an ArrayList children. When I create a Bundle and try to pass a "SuperMedia" object from one activity to another, all the fields get passed fine with the exception of the ArrayList "children" which just shows up as being empty every time.
In my first Activity I do:
Bundle a = new Bundle();
a.putParcelable("media",media); //media is an object of type "SuperMedia" and all the "children" have been initialized and added to the array
final Intent i = new Intent("com.tv.video.subcategories");
i.putExtra("subcategories", a);
On my Second Activity I do:
Intent i = getIntent();
Bundle secondBun = i.getBundleExtra("subcategories");
SuperMedia media = secondBun.getParcelable("media"); //For some reason the ArrayList"children" field shows up as empty.
Im not sure why this is happening. If anybody can guide me on the right path that would be greatly appreciated. Below is my SuperMedia class btw.
public class SuperMedia implements Parcelable{
public URI mthumb;
public String mTitle;
public ArrayList<SuperMedia> children = new ArrayList();
public SuperMedia(URI thumb, String title) {
this.mthumb = thumb;
this.mTitle = title;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
dest.writeString(mTitle);
dest.writeString(mthumb.toString());
dest.writeTypedList(children);
}
public static final Parcelable.Creator<SuperMedia> CREATOR = new Parcelable.Creator<SuperMedia>() {
public SuperMedia createFromParcel(Parcel in) {
return new SuperMedia(in);
}
public SuperMedia[] newArray(int size) {
return new SuperMedia[size];
}
};
private SuperMedia(Parcel in) {
mTitle = in.readString();
try {
mthumb = new URI(in.readString());
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
in.readTypedList(children, SuperMedia.CREATOR);
}
public SuperMedia(){
}
}
If you want simply pass object through intent then you can make SuperMedia Serializable no need to Parcelable.
public class SuperMedia implements Serializable{...}
put it as
Bundle a = new Bundle();
a.putSerializable("media",media);
and we get it as.
Intent i = getIntent();
Bundle secondBun = i.getBundleExtra("subcategories");
SuperMedia media = (SuperMedia)secondBun.getSerializable("media");
if you really needed Parcelable then may it help you.
Arraylist in parcelable object
Use Bundle's putParcellableArrayList for storing SuperMedia object
Bundle args = new Bundle();
args.putParcelableArrayList("media", "media");
and for restroring
getArguments().getParcelableArrayList("media");
This way will ensure bundle save your list objects as implemented in parcelable instance.
Also, be aware of using only ArrayList, other List subclasses not supported.

How to pass Parcelable array to fragment and Activity

I'm working with custom parcelable class. I need to pass this class as array to another activity and new fragments. I googled, but I found arrayList but not arrays. Please mind that I need to pass arrays not Array lists. How to achieve that? Please mind again, performance is a big issue. So any solutions with less performance consumption is very welcome.
Any helps would be very appreciated.
You can pass your arrayList as below snipts.
TestFragment testFragment = new TestFragment();
Bundle args = new Bundle();
args.putSerializable("parsedData", (Serializable)mTestModelList);
testFragment.setArguments(args);
And Get these parcable data in Model as like below:
mTestModelList = (List<TestModel>)getArguments().get("parsedData");
YES, Serialisation is slow bit than Parcelable.
And you can implement that using parceler
Of course, the ParcelWrapper can be added to an Android Bundle to transfer from Activity to Activity using this:
Bundle bundle = new Bundle();
bundle.putParcelable("example", Parcels.wrap(example));
And dereferenced in the onCreate() method:
Example example = Parcels.unwrap(getIntent().getParcelableExtra("example"));
You can get more detail of performance related to Parcelable vs Serializable here.
Here is the write answer
// write parcelable array
final Bundle arguments = new Bundle();
MyParcelable[] myArray = new MyParcelable[10];
arguments.putParcelableArray("key"myArray);
// read parcelable array
MyParcelable[] myArray = (MyParcelable[])getArguments().getParcelableArray("key");
use like following class of your parcealble array
public class ParcelableLaptop implements Parcelable {
private Laptop laptop;
public Laptop getLaptop() {
return laptop;
}
public ParcelableLaptop(Laptop laptop) {
super();
this.laptop = laptop;
}
private ParcelableLaptop(Parcel in) {
laptop = new Laptop();
laptop.setId(in.readInt());
laptop.setBrand(in.readString());
laptop.setPrice(in.readDouble());
laptop.setImageBitmap((Bitmap) in.readParcelable(Bitmap.class
.getClassLoader()));
}
/*
* you can use hashCode() here.
*/
#Override
public int describeContents() {
return 0;
}
/*
* Actual object Serialization/flattening happens here. You need to
* individually Parcel each property of your object.
*/
#Override
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeInt(laptop.getId());
parcel.writeString(laptop.getBrand());
parcel.writeDouble(laptop.getPrice());
parcel.writeParcelable(laptop.getImageBitmap(),
PARCELABLE_WRITE_RETURN_VALUE);
}
/*
* Parcelable interface must also have a static field called CREATOR,
* which is an object implementing the Parcelable.Creator interface.
* Used to un-marshal or de-serialize object from Parcel.
*/
public static final Parcelable.Creator<ParcelableLaptop> CREATOR =
new Parcelable.Creator<ParcelableLaptop>() {
public ParcelableLaptop createFromParcel(Parcel in) {
return new ParcelableLaptop(in);
}
public ParcelableLaptop[] newArray(int size) {
return new ParcelableLaptop[size];
}
};
}
now make Arraylist of ParcelableLaptop and put in the bUndle with argument
intent.putParcelableArrayListExtra("laptop", parcelableLaptopArray);
Where parcelableLaptop is your Arraylist of the Model. And to get the List:
Intent intent = getIntent();
ArrayList<ParcelableLaptop> parcelableLaptop = (ParcelableLaptop) intent
.getParcelableArrayListExtra("laptop");

Categories