Creating and passing object to activity fails - android

I want to create and pass an object through intent to another activity, so I can process the object details in this activity and show it to the user.
This object is being identified by a value long.
I have an arraylist (releaseIds) which holds several long values of this object, so I just want to pass these values through an intent to the other activity.
The user can select the desired object from a alertdialog presenting this list, once he/she selects an item from this list the correct long ID is identified and a new object created and passed through intent.
But creating the new object somehow failes, because the object ReleaseModel is null in the receiving acitivity.
What I am doing wrong?
Creating and passing the object (ReleaseModel):
...
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
// Do something with the selection
for (int i = 0; i < releaseIds.size(); i++) {
if (i == item) {
long ID = releaseIds.get(i);
final ReleaseModel releaseModel = new ReleaseModel(ID);
ReleaseActivtiy_.intent(MyAppsMain.this).extra("releaseModel",
releaseModel).start();
}
}
}
});
...
The object itself:
public class ReleaseModel extends BaseModel {
private List<String> url = new ArrayList<>();
private boolean liked;
...
public ReleaseModel() {
}
public ReleaseModel(long id) {
super(id);
}
...
public void writeToParcel(Parcel parcel, int flags) {
super.writeToParcel(parcel, flags);
parcel.writeInt(liked ? 1 : 0);
...
}
public static final Parcelable.Creator<ReleaseModel> CREATOR = new Parcelable.Creator<ReleaseModel>() {
public ReleaseModel createFromParcel(Parcel in) {
return new ReleaseModel(in);
}
public ReleaseModel[] newArray(int size) {
return new ReleaseModel[size];
}
};
private ReleaseModel(Parcel parcel) {
super(parcel);
setLiked(parcel.readInt() == 1);
...
}
}
The basemodel:
public class BaseModel implements Parcelable {
private long id;
private long date;
...
public BaseModel() {
}
public BaseModel(long id) {
this.id = id;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
...
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeLong(id);
parcel.writeLong(date);
...
}
public static final Parcelable.Creator<BaseModel> CREATOR = new Parcelable.Creator<BaseModel>() {
public BaseModel createFromParcel(Parcel in) {
return new BaseModel(in);
}
public BaseModel[] newArray(int size) {
return new BaseModel[size];
}
};
public BaseModel(Parcel parcel) {
setId(parcel.readLong());
setDate(parcel.readLong());
...
}
}
Receiving activity:
#EActivity(R.layout.release_activity)
public class ReleaseActivtiy extends BaseActivity implements LoaderManager
.LoaderCallbacks<BaseResponse>, NotificationCenter.NotificationCenterDelegate {
...
#Extra("releaseModel")
ReleaseModel releaseModel;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
}
#AfterViews
public void init() {
// Nullpointer exception on this line for releaseModel
String temp = releaseModel.getSubject().replaceAll("[^a-zA-Z]", "");
}
}

To pass ReleaseModel object to another Activity(ActivityPassedTo).
Do the Following Steps:
1.You Need to make ReleaseModel implements Serializable
2.To pass it to an Intent you need to have a Unique Key to identify the object passed in both the activities
Eg. you can create a Key:
static final String RELEASE_MODEL = "RELEASE_MODEL";
Now pass it to the activity in intent
Intent intent = new Intent(this,ActivityPassedTo.class);
intent.putExtra(RELEASE_MODEL,releaseModelObject);
startActivity(intent);
Now Retrieve the object in Activity (ActivityPassedTo)
Intent intent = getIntent()
ReleaseModel releaseModel = (ReleaseModel)intent.getSerializableExtra(RELEASE_MODEL);

Related

parse arraylist form one fragment to another fragment in android

How I can parse Arraylist of JSON from one Fragment to another fragment here is my arraylist code where I am getting arraylist from my model:
private void setListOffers(JSONArray categoryArray) {
for (int i = 0; i < categoryArray.length(); i++) {
try {
JSONObject object = categoryArray.getJSONObject(i);
hotDealID = object.getInt("ID");
deals.add(new ListOffers(hotDealID));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Here I am sending data from fraggment:
private ArrayList<ListOffers> deals = new ArrayList<>();
Fragment fragment = new HotDealFragment();
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("dealsId", deals);
fragment.setArguments(bundle);
When I put this code then deals gives exception that wrong second argument and ListOffers is my model where I am fetching data
and here is my model list Offers:
private int Id;
public ListOffers(int Id){
this.Id = Id;
}
public void setId(int id) {
Id = id;
}
public int getId() {
return Id;
}
One possible problem:
Your ListOffers model does not implement parcelable. Your model should implement parcelable. You can get help from this link
https://github.com/codepath/android_guides/wiki/Using-Parcelable
import android.os.Parcel;
import android.os.Parcelable;
public class ListOffers implements Parcelable {
private int Id;
public ListOffers(int Id) {
this.Id = Id;
}
public void setId(int id) {
Id = id;
}
public int getId() {
return Id;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(Id);
}
protected ListOffers(Parcel in) {
Id = in.readInt();
}
public static final Creator<ListOffers> CREATOR = new Creator<ListOffers>() {
#Override
public ListOffers createFromParcel(Parcel in) {
return new ListOffers(in);
}
#Override
public ListOffers[] newArray(int size) {
return new ListOffers[size];
}
};
}
Using hashmap you can pass
HashMap <String,ArrayList<ListOffers>> hashMap;
Bundle extras = new Bundle();
extras.putSerializable("HashMap",hashMap);
intent.putExtras(extras);
And get it using below code
Intent intent = getIntent();
hasMap= intent.getSerializableExtra("hashMap");
your datamodel ListOffers should be implement the Parcelable then only you can pass as ParcelableArrayList.
refer
Help passing an ArrayList of Objects to a new Activity
Using Parcelable your model will be
public class ListOffers implements Parcelable {
private int Id;
/**
* Constructs a Model from a Parcel
*
* #param parcel Source Parcel
*/
public ListOffers(Parcel parcel) {
this.Id = parcel.readInt();
}
public ListOffers(int Id) {
this.Id = Id;
}
public void setId(int id) {
Id = id;
}
public int getId() {
return Id;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeInt(Id);
}
// Method to recreate a Model from a Parcel
public static Creator<ListOffers> CREATOR = new Creator<ListOffers>() {
#Override
public ListOffers createFromParcel(Parcel source) {
return new ListOffers(source);
}
#Override
public ListOffers[] newArray(int size) {
return new ListOffers[size];
}
};
}
Sending ParcelableArrayList from one fragment to other -
private ArrayList<ListOffers> deals = new ArrayList<>();
setListOffers(categoryArray);
Fragment fragment = new HotDealFragment();
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("dealsId", deals);
fragment.setArguments(bundle);
Fetching it into other Fragment in it's onCreate -
ArrayList<ListOffers> deals = new ArrayList<>();
if (getArguments() != null) {
deals = getArguments().getParcelableArrayList("dealsId");
}
Hope this will help you :)
Here is an easier approach.
Most times when one wants to send this data is because they want it to be accessed in the new class for just a short time. Instead of sending the data every time, go to the fragment that contains the data and make it public and static.
public static ArrayList<ListOffers> deals;
Access it in your desired activity
MainFragment.deals
Make your ListOffer implements Serializable and then use
private ArrayList<ListOffers> deals = new ArrayList<>();
Fragment fragment = new HotDealFragment();
Bundle bundle = new Bundle();
bundle.putSerializable("dealsId", deals);
fragment.setArguments(bundle);
Here is how to get that
if (getArguments() != null) {
mdealsId = (ListOffers)getArguments().getSerializable("dealsId");
}

Parcelable String Array via Intent

I've a custom parcelable (simplified) that contains a string array:
public class MyClass implements Parcelable {
public static final Creator<MyClass> CREATOR = new Creator<MyClass>() {
public MyClass createFromParcel(Parcel in) {
return new MyClass(in);
}
public MyClass[] newArray(int size) {
return new MyClass[size];
}
};
#SerializedName(“tips”)
private List<String> Tips;
public MyClass() {
Tips = new ArrayList<>();
}
protected Category(Parcel in) {
Tips = in.createStringArrayList();
}
public List<String> getTips() {
return Tips;
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeStringList(Tips);
}
}
I'm trying to pass this parcelable via Intent to another activity. The process is VERY slow and sometimes I get an OOM exception...I don't understand why, I just want to pass a string array...
Save your array into database and pass id of that record.

get ArrayList<MyClass> with getIntent().getExtras()

in an activity from my app I have an Intent to start a new Activity and I want to pass an ArrayList i.e. an ArrayList where each item is an instance of a own class ... how can I make this?
I have been seeing possible getExtras() like getStringArrayList() or getParcelableArrayList() and it doesn't work, I haven't found any valid type.
Can anyone help me? Thanks.
This is my class:
public class ItemFile {
protected long id;
protected String nombre;
protected String rutaImagen;
protected boolean checked;
public ItemFile(long id, String nombre, String rutaImagen, boolean check) {
this.id = id;
this.nombre = nombre;
this.rutaImagen = rutaImagen;
this.checked = check;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getRutaImagen() {
return rutaImagen;
}
public void setRutaImagen(String rutaImagen) {
this.rutaImagen = rutaImagen;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked){
this.checked = checked;
}
}
How I must change it to set Parcelable?
First make sure MyClass class implements Parcelable interface then use this code for getting ArrayList in other Activity :
In your first activity do something like this:
ArrayList<MyClass> myClassList= new ArrayList<MyClass>();
Intent intent = new Intent(<YOUR ACTIVITY CONTEX>, <NEXT ACTIVITY>);
intent.putExtra("myClassList", myClassList);
startActivity(intent);
In your next activity do something like this:
ArrayList<MyClass> list = (ArrayList<MyClass>)getIntent().getExtras()getSerializable("myClassList");
Make MyClass Parcelable. See example below.
public class MyClass 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();
}
}
// Send it using
ArrayList<MyClass> list;
intent.putParcelableArrayListExtra("list", list);
In First activity
ArrayList<MyClass> fileList = new ArrayList<MyClass>();
Intent intent = new Intent(MainActivity.this, secondActivity.class);
intent.putExtra("FILES_TO_SEND", fileList);
startActivity(intent);
In Secand
activity:ArrayList<MyClass> filelist =(ArrayList<MyClass>)getIntent().getSerializableExtra("FILES_TO_SEND");
I had been struggling with this myself but I found a fairly simple solution on tutorialspoint that worked well for me.
In the source activity, use
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("key", numbers);
startActivity(intent);
Then in the destination activity, use
ArrayList<String> numbersList = (ArrayList<String>) getIntent().getSerializableExtra("key");
A link to the full tutorial is: https://www.tutorialspoint.com/how-to-pass-an-arraylist-to-another-activity-using-intents-in-android

Passing Parcelable item between activities

I'm having trouble passing an object via an Intent. I keep getting a null pointer error. here it is:
In my ListActivity:
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Intent intent = new Intent(MyListActivity.this, DetailsActivity.class);
intent.putExtra("this_item", my_array.get(position));
startActivity(intent);
}
In the onCreate() of the DetailsActivity class:
thisItem = (MyObject) getIntent().getExtras().getParcelable("this_item");
System.err.println(thisItem.getDescription()); //<--Null pointer error!
The MyObject class does implement Parcelable. Why can't I pass this object over? I'm confused. Thanks for any help.
EDIT: Here is that class:
public class MyObject implements Comparable<MyObject>, Parcelable {
private Date date;
private MyType my_type;
private String description;
private int flags;
public MyObject(Date date, MyType type, String desc) {
this.date = date;
this.my_type = type;
this.description = desc;
}
public Date getDate() {return date;}
public MyType getMyType() {return my_type;}
public String getDescription() {return description;}
public int compareTo(MyObject another) {
if (getDate() == null || another.getDate() == null) {return 0;}
return getDate().compareTo(another.getDate());
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(flags);
}
public static final Parcelable.Creator<MyObject> CREATOR = new Parcelable.Creator<MyObject>() {
public MyObject createFromParcel(Parcel in) {
return new MyObject(in);
}
public MyObject[] newArray(int size) {
return new MyObject[size];
}
};
private MyObject (Parcel in) {
flags = in.readInt();
}
}
If you want to pass the data from one activity to another actiivty via intent the object must be parcelable or serializable in android..for parcelable you have to implement the serializable interface..for parcelable you must implement parcelable interface..
Write parcelable class like this..
parcel example

How to implement parcelable for List<Long>

I'm trying to pass a List in my parcelable doing:
public class MetaDados implements Parcelable {
private List<Long> sizeImages;
public MetaDados(List<Long> sizeImages){
this.sizeImages = sizeImages;
}
public List<Long> getSizeImages() {
return sizeImages;
}
public void setSizeImages(List<Long> sizeImages) {
this.sizeImages = sizeImages;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeList(sizeImages);
}
public static final Parcelable.Creator<MetaDados> CREATOR = new Parcelable.Creator<MetaDados>() {
#Override
public MetaDados createFromParcel(Parcel in) {
return new MetaDados(in);
}
#Override
public MetaDados[] newArray(int size) {
return new MetaDados[size];
}
};
private MetaDados(Parcel in) {
//HERE IS THE PROBLEM, I'VE tried this:
sizeImages = in.readList(sizeImages, Long.class.getClassLoader());
//but what i got: Type mismatch: cannot convert from void to List<Long>
}
}
Try this instead:
sizeImages = new ArrayList<Long>(); // or any other type of List
in.readList(sizeImages, null);
The Android documentation for Parcel.readList says:
Read into an existing List object from the parcel
and thus, you need to first create the List.

Categories

Resources