2017-03-07 64 views
0

我需要将自定义类的ArrayList从一个实体“转移”到另一个实体。我知道我需要实现Parcelable接口。ArrayList和Parcelable

这是我的自定义类。

public class cSportsList implements Parcelable { 
    boolean checked; 
    String name; 

    cSportsList(boolean check, String name_) { 
     checked = check; 
     name = name_; 
    } 

    @Override 
    public int describeContents() { 
     return 0; 
    } 

    @Override 
    public void writeToParcel(Parcel dest, int flags) { 
     //Non posso passare un booleano e non posso fare il cast boolean -> int 
     if (checked) { 
      dest.writeInt(1); 
     } 
     else dest.writeInt(0); 
     dest.writeString(name); 
    } 

    public static final Parcelable.Creator<cSportsList> CREATOR = new Parcelable.Creator<cSportsList>() { 
     public cSportsList createFromParcel(Parcel in) { 
      return new cSportsList(in); 
     } 

     public cSportsList[] newArray(int size) { 
      return new cSportsList[size]; 
     } 
    }; 

    private cSportsList(Parcel in) { 
     if (in.readInt() == 1) { 
      checked = true; 
     } 
     else { 
      checked = false; 
     } 
     name = in.readString(); 


    } 
} 

这就是“从”

//This is sportsMap: ArrayList<cSportsList> sportsMap = new ArrayList<cSportsList>(); 
Intent intent = new Intent(getApplicationContext(),WhatSportActivity.class); 
intent.putParcelableArrayListExtra("sportsMap", (ArrayList<? extends Parcelable>) sportsMap); //I have tried with ArrayList<cSportsList> too. 
this.startActivity(intent); 

在实体代码而这是实体代码“到”

final Intent srcIntent = getIntent(); 
ArrayList<cSportsList> sportsMap = srcIntent.getParcelableExtra("sportsMap"); 

的问题是:在实体“到” sportsMap为null。 如果我在“writeToParcel”和“cSportsList(Parcelable in)”函数中设置了“断点”,我发现这两个函数都执行了代码。

我的错误在哪里?

谢谢。 M.

+0

用** getParcelableArrayListExtra **替换** getParcelableExtra **。 –

回答

0

使用下面的代码

sportsMap = srcIntent.g etParcelableArrayListExtra( “sportsMap”);

1

在阅读你需要使用

srcIntent.getParcelableArrayListExtra("sportsMap"); 

要投入使用意向下面的代码

intent.putParcelableArrayListExtra("sportsMap", sportsMap); 

,并从意向读它,使用

ArrayList<cSportsList> sportsMap = srcIntent.getParcelableArrayListExtra("sportsMap"); 

Pass ArrayList<? implements Parcelable> to Activity

0

阅读类似的解决方案,您应该使用:

ArrayList<cSportsList> sportsMap = srcIntent.getParcelableArrayListExtra("sportsMap"); 
0

您还可以使用序列化一样。

public class cSportsList implements Serializable

认沽:

intent.putExtra("LIST",list);

对于GET:

(ArrayList<>)intent.getSerializableExtra("LIST");

+0

我读过Parcelable比Serialize更好。但是:谢谢。 – ZioBudda

0

尝试通过的ArrayList,而不是铸像这样的:

Intent intent = new Intent(getApplicationContext(),WhatSportActivity.class); 
intent.putParcelableArrayListExtra("sportsMap", sportsMap); 
     startActivity(intent); 

在WhatSportActivity,

final Intent srcIntent = getIntent(); 
ArrayList<cSportsList> sportsMap = srcIntent.getParcelableExtra("sportsMap"); 

如果你还有问题,请尝试使用 “Parceable” 插件,因为它实现Parceable减少使用Parceable列表中的错误。