我想通过ArrayList<Palatte_Model>
从一个 Activity 到另一个 fragment 。我正在使用 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];
}
};
}
我在这里附上了我的 Activity 类(class)代码。将数组列表发送到 fragment
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();
这里我提到了我的 fragment 类代码:
我取 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
.
最佳答案
我遇到了类似的问题。经过一些研究,我在我的代码中的某个地方发现了 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");
}
因此,如果检索到的数据为空,则不会将空指针附加到 ArrayList。
检查这个link有关NullPointerException
的更多信息关于java - ParcelableArraylist 可能会在 fragment 中产生空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51532110/