I have custom class that implements Parcelable and I use it as custom arraylist.
When I use putParcelableArrayListExtra and 400 rows it works fine, but 1000 rows it does not. I have black screen and app locks up. What is wrong?
EDIT:
I sent it here and I don't use it in another Activity.
Intent intent = new Intent().setClass(getApplicationContext(), ArtActivity.class);
intent.putParcelableArrayListExtra ("mylist", list);
startActivityForResult(intent, SECONDARY_ACTIVITY_REQUEST_CODE);
My array:
ArrayList<Piece> list = new ArrayList<Piece>();
It is my Class:
public class Piece implements Parcelable {
private String id;
private String name;
private int type;
private String text;
private String mp3;
public Piece (String id,String name,int type)
{
this.id=id;
this.name=name;
this.type=type;
}
public Piece(Piece ele)
{
this.id=ele.id;
this.name=ele.name;
this.type=ele.type;
this.text=ele.text;
}
public Piece (Parcel in)
{
id = in.readString ();
name = in.readString ();
type = in.readInt();
text= in.readString();
mp3=in.readString();
}
public static final Parcelable.Creator<Piece> CREATOR
= new Parcelable.Creator<Piece>()
{
public Piece createFromParcel(Parcel in)
{
return new Piece(in);
}
public Piece[] newArray (int size)
{
return new Piece[size];
}
};
public void makeText(String text)
{
this.text=text;
}
public void makeMp3(String mp3)
{
this.mp3= mp3;
}
public String getMp3()
{
return this.mp3;
}
public String getId()
{
return id;
}
public String getName()
{
return name;
}
public int getType()
{
return type;
}
public String getText()
{
return text;
}
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
dest.writeString (id);
dest.writeString (name);
dest.writeInt(type);
dest.writeString (text);
dest.writeString (mp3);
}
}
I do not believe you should be using parcelable in this case. I would either access the data statically (if you only intend to have one persistent instance of the data), or use a caching system to hold onto the data.
This is an example of a publicly available static variable:
public static List<Piece> list;
It is accessible from everywhere in your app that has visibility of the class.
However, doing this is very messy and is considered a bad practice. Alternatively, you can create an object to manage the data for you as a static class or singleton:
public class MyListManager {
private static List<Piece> mList;
public static List<Piece> getMyList() {
return mList;
}
public static void setList(List<Piece> list) {
mList = list;
}
}
Alternatively, you can implement some kind of a caching system to manage your data.
Related
Im pretty new in Android Studio.
I'm trying to pass an ArrayList from one activity to another using parcelable. Within the class Recipe I declare another ArrayList which I cannot get a hold of when starting the other activity.
Recipe.java:
public class Recipe implements Parcelable {
String name;
ArrayList<Ingredient> ingredients;
public Recipe(String name){
this.name = name;
this.ingredients = new ArrayList<>();
}
protected Recipe(Parcel in) {
name = in.readString();
}
public static final Creator<Recipe> CREATOR = new Creator<Recipe>() {
#Override
public Recipe createFromParcel(Parcel in) {
return new Recipe(in);
}
#Override
public Recipe[] newArray(int size) {
return new Recipe[size];
}
};
public void addIngredients(String[] amountList, String[] ingredientList, String[] unitList) {
for (int i = 0; i < ingredientList.length; i++) {
ingredients.add(new Ingredient(ingredientList[i], Double.parseDouble(amountList[i]), unitList[i]));
}
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(name);
}
}
Ingredient.java:
public class Ingredient implements Parcelable {
private String ingrdnt;
private double amount;
private String unit;
private String cat;
private boolean checkedItem;
public Ingredient(String ingrdnt, double amount, String unit) {
this.ingrdnt = ingrdnt;
this.amount = amount;
this.unit = unit;
//this.cat = category;
this.checkedItem = false;
}
protected Ingredient(Parcel in) {
ingrdnt = in.readString();
amount = in.readDouble();
unit = in.readString();
cat = in.readString();
checkedItem = in.readByte() != 0;
}
public static final Creator<Ingredient> CREATOR = new Creator<Ingredient>() {
#Override
public Ingredient createFromParcel(Parcel in) {
return new Ingredient(in);
}
#Override
public Ingredient[] newArray(int size) {
return new Ingredient[size];
}
};
public double getAmount() {
return amount;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(ingrdnt);
parcel.writeDouble(amount);
parcel.writeString(unit);
parcel.writeString(cat);
parcel.writeByte((byte) (checkedItem ? 1 : 0));
}
}
In main:
private ArrayList<Recipe> recipes = new ArrayList<>();
//recipes obviously holds a bunch of recipes so it's not empty.
intent.putExtra("recipes", recipes);
System.out.println(recipes.get(0).ingredients.get(0).getAmount());
System.out: 2.0
In second activity:
recipes = this.getIntent().getParcelableArrayListExtra("recipes");
//Same print as above
System.out.println(recipes.get(0).ingredients.get(0).getAmount());
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
Have I implemented the parcelable in a wrong way or why can I not get a hold of the Ingredient objects?
I've read about other ways to pass objects between activities but it seems like parcelable might be the best way to do it.
Yes, you basically forgot to write the ingredients of the Recipe to the output Parcel which is given to the Recipe.writeToParcel method.
You can write the ArrayList<Parcelable> with writeTypedList and read it back with readTypedList.
So your Recipe constructor which accepts a Parcel should be like:
protected Recipe(Parcel in) {
name = in.readString();
ingredients = new ArrayList<>();
in.readTypedList(ingredients, Ingredient.CREATOR);
}
while your writeToParcel of the Recipe should become:
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(name);
parcel.writeTypedList(ingredients);
}
The NullPointerException you are seeing is caused by the fact that you do not allocate a new ArrayList in the constructor of Recipe which accepts a Parcel, so when you call recipes.get(0).ingredients.get(0).getAmount() in the second Activity the ingredients ArrayList is null, thus the Exception.
Also note (but not related to the problem) that there exist a writeBoolean and a readBoolean with which you can write and read values of type boolean (I am saying this for the Ingredient class implementation).
Try those out and let us know if it worked properly.
I've got a Class named as FilterData which implements Parcelable. I had a member variable private ArrayList<String> listPropertyType; When implementing the parcelable interface in my class, parcel.readArrayList(null) ,the parameter is shown as ClassLoader object. With this member variable the FilterData class works as intended. But I wanted to implement a scenario where ClassLoader object is passed to readArrayList() method.
So what I've gathered from the documentation which is unclear about the public ArrayList readArrayList (ClassLoader loader) that if the ArrayList contains non primitive class ,we have to use ClassLoader.
What's the use case in this scenerio of using a ClassLoader and how to use it? I wanted to use the ClassLoader in the following matter. Added a member variable private ArrayList<RandomClass> listRandom; RandomClass randomClass; to implement this.
My FilterData class holds :
public FilterData(Parcel parcel)
{
listPropertyType=parcel.readArrayList(null);
listRandom=parcel.readArrayList(randomClass);
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeList(listPropertyType);
parcel.writeList(listRandom);
}
And my RandomClass is :
public class RandomClass extends ClassLoader{
//this class is for testing classloader in ArrayList in parcelable .readArrayList()
String name;
int age;
public RandomClass(String name, int age) {
this.name = name;
this.age = age;
}
}
This implementation doesn't work. So how to use this?
First of all, if we want to get a class Parcelable, we can use a website www.parcelabler.com. It will generate the syntax of the class. Secondly If we wanted to use an ArrayList of a class of our own. Making a Parcelable class containing the ArrayList won't work. We need to make the custom class Parcelable as well.
If a class that needs to be parcelable contains a member variable ArrayList<String> list; , the class which is generated from the website, should be :
public class MyParcelable implements Parcelable {
ArrayList<String> list;
public MyParcelable(ArrayList<String> list) {
this.list = list;
}
protected MyParcelable(Parcel in) {
if (in.readByte() == 0x01) {
list = new ArrayList<String>();
in.readList(list, String.class.getClassLoader());
} else {
list = null;
}
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
if (list == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeList(list);
}
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<MyParcelable> CREATOR = new Parcelable.Creator<MyParcelable>() {
#Override
public MyParcelable createFromParcel(Parcel in) {
return new MyParcelable(in);
}
#Override
public MyParcelable[] newArray(int size) {
return new MyParcelable[size];
}
};
}
And if the Class contains an ArrayList of a class made by us like this ArrayList<DummyClass> list; , the code should be:
public class MyComplexParcelable implements Parcelable {
ArrayList<DummyClass> list;
public MyComplexParcelable(ArrayList<DummyClass> list) {
this.list = list;
}
#Override
public String toString() {
return "MyComplexParcelable{" +
"list=" + list +
'}';
}
protected MyComplexParcelable(Parcel in) {
if (in.readByte() == 0x01) {
list = new ArrayList<DummyClass>();
in.readList(list, DummyClass.class.getClassLoader());
} else {
list = null;
}
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
if (list == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeList(list);
}
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<MyComplexParcelable> CREATOR = new Parcelable.Creator<MyComplexParcelable>() {
#Override
public MyComplexParcelable createFromParcel(Parcel in) {
return new MyComplexParcelable(in);
}
#Override
public MyComplexParcelable[] newArray(int size) {
return new MyComplexParcelable[size];
}
};
}
If we compare both cases , there is no difference in the syntax. Both class uses in.readList(list, String.class.getClassLoader()); and in.readList(list, DummyClass.class.getClassLoader()); which uses ClassLoader object of the correspondent classes.
But in the latter case, we need to make the DummyClass parcelable. Like this:
public class DummyClass implements Parcelable {
int age;
String name;
public DummyClass(int age, String name) {
this.age = age;
this.name = name;
}
#Override
public String toString() {
return "DummyClass{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
protected DummyClass(Parcel in) {
age = in.readInt();
name = in.readString();
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(age);
dest.writeString(name);
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<DummyClass> CREATOR = new Parcelable.Creator<DummyClass>() {
#Override
public DummyClass createFromParcel(Parcel in) {
return new DummyClass(in);
}
#Override
public DummyClass[] newArray(int size) {
return new DummyClass[size];
}
};
}
If the array list you're reading from the parcel is subclass you've made, and not a standard java list subclass, or if it contains non-primitive types, you need to pass MyCustomList.class.getClassLoader().
You need to do it this way because parcelables can be inflated everywhere, anytime, so the code must know the ClassLoader required to load it. Most of the time you won't need it because you will be parcelling stuff inside your own app, but it is a good practice.
In fact, you said the list is a simple ArrayList<String>, so you don't need to do anything. It would be different if it was a MyListSubclass<String>, a ArrayList<MyObject>, or an ArrayList<HashMap<Object, Object>> that may contain other subclassed objects. You get the idea.
I am trying to pass array of objects from one activity to another activity using parcelable. Here i faced this problem Class not found when unmarshalling:
First Activity code
intent.setExtrasClassLoader(MenueItemDetails.class.getClassLoader());
intent.putExtra("menue",myArray);
Second Activity code
myArray = (MenueItemDetails[])getIntent().getParcelableArrayExtra("menue");
it's my class which is parceable
public class MenueItemDetails implements Parcelable {
private int id = 0, menueId = 0, type = 0, typeId = 0, styleId = 0, lineBefore = 0;
private String webSite = "", title = "", icon = "";
#Override
public int describeContents() {
return 0;
}
// write your object's data to the passed-in Parcel
#Override
public void writeToParcel(Parcel out, int flags) {
out.writeInt(id);
out.writeInt(menueId);
out.writeInt(type);
out.writeInt(typeId);
out.writeInt(styleId);
out.writeInt(lineBefore);
out.writeString(webSite);
out.writeString(title);
out.writeString(icon);
}
private MenueItemDetails(Parcel in) {
id = in.readInt();
menueId = in.readInt();
type = in.readInt();
typeId = in.readInt();
styleId= in.readInt();
lineBefore= in.readInt();
webSite=in.readString();
title= in.readString();
icon=in.readString();
}
public MenueItemDetails() {
id = 0;
menueId = 0;
type = 0;
styleId= 0;
lineBefore= 0;
webSite="";
title= "";
icon="";
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public MenueItemDetails createFromParcel(Parcel in) {
return new MenueItemDetails(in);
}
public MenueItemDetails[] newArray(int size) {
return new MenueItemDetails[size];
}
};
public int getLineBefore() {
return lineBefore;
}
public void setLineBefore(int lineBefore) {
this.lineBefore = lineBefore;
}
public void setId(int id) {
this.id = id;
}
public void setMenueId(int menueId) {
this.menueId = menueId;
}
public void setTitle(String title) {
this.title = title;
}
public void setIcon(String icon) {
this.icon = icon;
}
public void setType(int type) {
this.type = type;
}
public void setTypeId(int typeId) {
this.typeId = typeId;
}
public void setStyleId(int styleId) {
this.styleId = styleId;
}
public int getId() {
return id;
}
public String getWebSite() {
return webSite;
}
public void setWebSite(String webSite) {
this.webSite = webSite;
}
public int getMenueId() {
return menueId;
}
public String getTitle() {
return title;
}
public String getIcon() {
return icon;
}
public int getType() {
return type;
}
public int getTypeId() {
return typeId;
}
public int getStyleId() {
return styleId;
}
}
Your Second Activity must be like this:
Intent intent = getIntent();
intent.setExtrasClassLoader(MenueItemDetails.class.getClassLoader());
myArray = (MenueItemDetails[]) intent.getParcelableArrayExtra("menue");
Your code to pass the arraylist in first activity code is not correct.Send the arraylist in your activities as below:
First Activity Code
intent.setExtrasClassLoader(MenueItemDetails.class.getClassLoader());
intent.putParcelableArrayListExtra("menue",myArray);
And receive the arraylist as below in Second activity.
Second Activity Code
ArrayList<MenueItemDetails> myarray=getIntent().getParcelableArrayListExtra("menue");
The problem with your code is that it is used to send and receive single Object,not the arraylist.If you still have problems in using Parceable object,make sure to use Android Parceable Code generator plugin for Android Studio.
If your task is Pass data from activity to activity or Fragment
Than instead of Using Parcelable you can use Serializable object and pass it to intent it take very less time to implement and code than Parcelable
https://stackoverflow.com/a/39631604/4741746
implement serializable in your class
public class Place implements Serializable{
private int id;
private String name;
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Then you can pass this object in intent
Intent intent = new Intent(this, SecondAct.class);
intent.putExtra("PLACE", Place);
startActivity();
int the second activity you can get data like this
Place place= (Place) getIntent().getSerializableExtra("PLACE");
When i want to add item to favorite .. i write this code my program and access everywhere: Favorite.add(itemid);
When i want to add item to message i write this code my program and access everywhere: Message.add(itemid);
Two class have some methods. So how i can design this useful?
For example;
AbstractData.addFavorite(itemid);
AbstractData.addMessage(itemid);
or
AbstractData<Fav>.add(itemid);
AbstractData<SMS>.add(itemid);
or
Your opinion?
Thank for help and sory for my little english...
Favorite.class
public class Favorite {
static SparseArray<Fav> LIST = new SparseArray<>();
public static boolean add(int ID){
if(!check(ID)){
LIST.put(ID, new Fav(ID, DateFormat.getDateTimeInstance().format(new Date())));
return true;
}
return false;
}
public static void remove(int ID){
if(LIST.indexOfKey(ID) >= 0 )
LIST.remove(ID);
}
public static boolean check(int ID){return LIST.get(ID) != null;}
public static Fav get(int ID){return LIST.get(ID);}
public static void saveALL(){
AsyncTask.execute(new Runnable() {
#Override
public void run() {
Fav favorite;
for (int i = 0; i < LISTE.size(); i++) {
favorite = get(LISTE.keyAt(i));
if (favorite != null)
//Saving data to xml
}
}
});
Log.d("DONE", "Favorite LIST Saving");
}
}
Fav.class
public class Fav implements IModel{
private int ID;
private String DATE;
public Fav(int ID, String DATE) {
this.ID = ID;
this.DATE = DATE;
}
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
public String getDate() {
return DATE;
}
public void setDate(String DATE) {
this.DATE = DATE;
}
}
Message.class
public class Message{
static SparseArray<SMS> LIST = new SparseArray<>();
public static boolean add(int ID){
if(!check(ID)){
LIST.put(ID, new SMS(ID, DateFormat.getDateTimeInstance().format(new Date())));
return true;
}
return false;
}
public static void remove(int ID){
if(LIST.indexOfKey(ID) >= 0 )
LIST.remove(ID);
}
public static boolean check(int ID){return LIST.get(ID) != null;}
public static SMS get(int ID){return LIST.get(ID);}
public static void saveALL(){
AsyncTask.execute(new Runnable() {
#Override
public void run() {
SMS message;
for (int i = 0; i < LISTE.size(); i++) {
message = get(LISTE.keyAt(i));
if (message != null)
//Saving data to xml
}
}
});
Log.d("DONE", "Message LIST Saving");
}
}
SMS.class
public class SMS implements IModel{
private int ID;
private String DATE;
public SMS(int ID, String DATE) {
this.ID = ID;
this.DATE = DATE;
}
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
public String getDate() {
return DATE;
}
public void setDate(String DATE) {
this.DATE = DATE;
}
}
IModel.class
public interface IModel {
int getID();
void setID(int ID);
String getDate();
void setDate(String DATE);
}
In my opinion...
Don't over-design your models.
Don't make your add and remove methods static, it will eventually leave you with headaches. You want your constructor to initialize your object.
Either use a Singleton Pattern to get a single instance of your manager object, or
Keep your manager class as a local variable in your Application class, make an access method for it, initialize it in onCreate().
Personally I've started to ditch the getter/setter pattern in favour of public fields, particularly if they're final like in enums. I know this is supposed to be ugly but... I don't care as long as it's convenient =)
So...
public class MyApplication extends Application
{
private static MyApplication instance;
private FavouritesManager favouritesManager;
public static getMyApplicationInstance ()
{
return instance;
}
public void onCreate ()
{
instance = this;
favouritesManager = new FavouritesManager(this); // You may want it to have a Context...
}
}
public class FavouritesManager
{
private Map<Integer,Favourites> favorites;
public FavouritesManager ()
{
load();
}
public void add ( Favourite favourite )
{
favourites.put(favourite.id, favourite);
}
public boolean contains ( int favouriteId )
{
favourites.contaisKey(favouriteId);
}
private void load ()
{
favourites = new HashMap<>();
// Maybe deserialize json from SharedPreferenecs?
}
public List<Favorite> getAll ()
{
// Return all Favourites, sorted by their SortOrder.
}
public Favorite create ( String name )
{
// Maybe a factory method that generates an unused id and returns a new Favourite instance?
}
}
public Favourite
{
public final int id;
public final Date createDate;
public String name;
public int sortOrder;
public Favorite ( int id, String name, int sortOrder )
{
this.id = id;
this.createDate = Date();
this.name = name;
this.sortOrder = sortOrder;
}
}
public class MyActivity extend Activity
{
protected void onCreate ( Bundle savedInstanceState )
{
FavouritesManager favmanager = MyApplication.getMyApplicationInstance().getFavoritesManager();
}
{
}
Make your classes Message and SMS implement the same interface IModel. Then, when you implement your methods (e.g. add()) and want them to accept both Message and SMS objects, use the base interface in your method signature:
public class AbstractData {
public static void add(final IModel data) { // <- Use interface here!
// ...
}
}
Now you can add objects this way:
Message msg = new Message();
AbstractData.add(msg);
SMS sms = new SMS();
AbstractData.add(sms);
I tried to send a parcel from the mainActivity to a fragment and i noticed a strange effect.
When you implement parcelable, android require to implement "writeToParcel" and "describeContents".
The strange effect is, if you write something inside "writeToParcel" or nothing, it doesn't matter. Android never call it.
Why these functions are required ?
Here is a working source code :
public class Movie implements Parcelable {
private String title;
private Float score;
public Movie(String title, float score) {
this.title = title;
this.score = score;
}
...... Getter and Setter......
//Parcelable Methods
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
// Don't need to write anything in this area
/*
dest.writeString(title);
dest.writeFloat(score);
*/
}
public static final Parcelable.Creator<Movie> CREATOR = new Parcelable.Creator<Movie>() {
//--------------> You can return null, it's never called and work perfectly!
public Movie createFromParcel(Parcel in) {
return null;//new Movie(in);
}
public Movie[] newArray(int size) {
return null;//new Movie[size];
}
};
}
Any idear ?
Regards,