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

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

Related

Creating and passing object to activity fails

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);

Click on ListView item not opening new Activity

I have a ListView "resultList", but clicking on an item is not opening the new (detailed) Activity. What's my mistake?
Thank you!
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.resultList = (ListView) findViewById(R.id.resultList) ;
this.dataSource = MyExpenseOpenHandler.getInstance(this).readAllExpenses();
this.adapter = new ExpenseOverviewAdapter(this, dataSource);
this.resultList.setAdapter(adapter);
this.resultList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(final AdapterView<?> adapterView, View view, final int i, final long l) {
Object element = adapterView.getAdapter().getItem(i);
if (element instanceof Expense) {
Expense expense = (Expense) element;
Intent intent = new Intent(MainActivity.this, ExpenseDetailActivity.class);
intent.putExtra(ExpenseDetailActivity.EXPENSE_KEY, expense);
startActivity(intent);
}
Log.e("Click on List: ", element.toString());
}
});
}
Your code seems alright .I think the problem is that your if condition may be returning false and the code inside the if statement is not being executed.You can put a log message inside the if statement to check if the code is being executed.
if (element instanceof Expense) {
Log.d(YOUR_LOG_TAG,"The if condition not executed")
Expense expense = (Expense) element;
Intent intent = new Intent(MainActivity.this, ExpenseDetailActivity.class);
intent.putExtra(ExpenseDetailActivity.EXPENSE_KEY, expense);
startActivity(intent);
}
If you see the log message in your android monitor you can be sure that the code inside your if condition is not executed and hence your activity is not starting.
Did you implement Parcelable on your class Expense ?
Something like this
public class Expense implements Parcelable{
private String id;
private String name;
private String grade;
// Constructor
public Expense(String id, String name, String grade){
this.id = id;
this.name = name;
this.grade = grade;
}
// Getter and setter methods
.........
.........
// Parcelling part
public Expense(Parcel in){
String[] data = new String[3];
in.readStringArray(data);
// the order needs to be the same as in writeToParcel() method
this.id = data[0];
this.name = data[1];
this.grade = data[2];
}
#Оverride
public int describeContents(){
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeStringArray(new String[] {this.id,
this.name,
this.grade});
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public Expense createFromParcel(Parcel in) {
return new Expense(in);
}
public Expense[] newArray(int size) {
return new Expense[size];
}
};
}
what kind of view in the list, if the child view get the focus like button may lead to item click not work well.
you can try to add android:descendantFocusability="beforeDescendants" in you listview.

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.

Starting new activity gives: Class not found when unmarshalling

I'm facing a problem when passing a list of parcelable objects to the intent of one new activity.
Here's what I do:
Intent intent = new Intent(context, CurriculumCorsesActivity.class);
intent.setExtrasClassLoader(CurriculumCourseCard.class.getClassLoader());
intent.putParcelableArrayListExtra("courses", card.getCourses());
context.startActivity(intent);
And when I call the startActivity I get the following error:
E/Parcel﹕ Class not found when unmarshalling: pt.tecnico.fenixmobile.person.CurriculumCourseCard, e: java.lang.ClassNotFoundException: pt.tecnico.fenixmobile.person.CurriculumCourseCard
CurriculumCourseCard implements the Parcelable interface. Here's is the implementation:
public class CurriculumCourseCard implements Serializable, Parcelable{
private static final long serialVersionUID = 765578940083L;
private String courseName;
private String finalGrade;
private String ects;
public CurriculumCourseCard(Parcel in) {
this.courseName = in.readString();
this.finalGrade = in.readString();
this.ects = in.readString();
}
public String getCourseName() {
return courseName;
}
public String getFinalGrade() {
return finalGrade;
}
public String getEcts() {
return ects;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(this.courseName);
parcel.writeString(this.finalGrade);
parcel.writeString(this.ects);
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public CurriculumCourseCard createFromParcel(Parcel in) {
return new CurriculumCourseCard(in);
}
public CurriculumCourseCard[] newArray(int size) {
return new CurriculumCourseCard[size];
}
};}
And this is how I'm getting the list in the new activity:
Intent intent = getIntent();
intent.setExtrasClassLoader(CurriculumCourseCard.class.getClassLoader());
ArrayList<CurriculumCourseCard> courses = intent.getParcelableArrayListExtra("courses");
In the new activity I see as much items as there are in the list, but no content at all. And the only error is the one described before.
Hope you can help me.

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

Categories

Resources