我想将ArrayList<Palatte_Model>
从一个活动传递到另一个片段。我正在使用ParcelableArraylist
。在这里,我附上了我的代码
public class Palette_Model implements Parcelable{
public String data_format_value;
public int data_format_id;
public Palette_Model(String data_format_value, int data_format_id) {
this.data_format_value = data_format_value;
this.data_format_id = data_format_id;
}
public String getData_format_value() {
return data_format_value;
}
public void setData_format_value(String data_format_value) {
this.data_format_value = data_format_value;
}
public int getData_format_id() {
return data_format_id;
}
public void setData_format_id(int data_format_id) {
this.data_format_id = data_format_id;
}
protected Palette_Model(Parcel in) {
data_format_value = in.readString();
data_format_id = in.readInt();
}
@Override
public int describeContents() {
return this.hashCode();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(data_format_value);
dest.writeInt(data_format_id);
}
public void readfromParcel(Parcel source){
data_format_id = source.readInt();
data_format_value = source.readString();
}
public static final Creator<Palette_Model> CREATOR = new Creator<Palette_Model>() {
@Override
public Palette_Model createFromParcel(Parcel in) {
return new Palette_Model(in);
}
@Override
public Palette_Model[] newArray(int size) {
return new Palette_Model[size];
}
};
}
在这里,我附上了我的活动课程代码。将arraylist发送到片段
Platte_fragment dFragment = new Platte_fragment();
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("arraylist", strQuestion);
dFragment.setArguments(bundle);
// dFragment.show(fragmentManager, "array list");
FragmentTransaction fts = getSupportFragmentManager().beginTransaction();
fts.replace(R.id.questContFragId, dFragment);
fts.addToBackStack(dFragment.getClass().getSimpleName());
fts.commit();
在这里我提到了我的片段类代码:
我从ArrayList
获取了Activity
。它显示一个空值
ArrayList<Palette_Model> strQuestion ;
strQuestion = new ArrayList<>();
try {
Bundle bundle = this.getArguments();
strQuestion = bundle.getParcelableArrayList("arraylist");
}catch (NullPointerException e){
Log.e("er",e.getMessage());
}
所示方法可能会产生NullpointerException
。
答案 0 :(得分:0)
我有类似的问题。经过一番研究,我发现我的代码ArrayList<Type> list
中的某处什么都没有指向(NullpointerException)。
帮助我的是检查Bundle extras是否为null
:
ArrayList<Category> categories = new ArrayList<Category>(); // you initialize it here
Bundle extras = getIntent().getExtras();
if (extras != null) {
categories = extras.getParcelableArrayList("categories");
}
因此,如果检索到的数据为null,则不会将null指针附加到ArrayList。
选中此link,以获取有关 NullPointerException
的更多信息