我正在使用这个库https://github.com/stepstone-tech/android-material-stepper
用于在单个活动中容纳多个片段。在其中一个片段中,我试图在onSaveInstanceState()
方法中保存片段recyclelerview中的项目对象,它工作得很好但是当应用程序失去焦点时(例如按下主页按钮),应用程序崩溃(它的工作原理)当我按下后退按钮退出应用程序时)。
这是片段
public class StylesFragment extends Fragment implements Step {
private static final String STATE_ITEMS = "items";
RecyclerView recyclerView;
private TAASService mService;
public ArrayList<CustomStyles> styles;
public StylesFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
}
@SuppressWarnings("unchecked")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View v=inflater.inflate(R.layout.fragment_styles, container, false);
recyclerView=(RecyclerView) v.findViewById(R.id.recycler);
//recyclerView.setAdapter(adapter);
mService = ApiUtils.getTAASService();
if (savedInstanceState==null) {
loadCustomStyles();
}else{
styles = (ArrayList<CustomStyles>) savedInstanceState.getSerializable(STATE_ITEMS);
StylesListAdapter adapter = new StylesListAdapter(styles);
//do more things
}
return v;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable(STATE_ITEMS,styles);
}
public void loadCustomStyles() {
//load from network
}
所以我注意到删除outState.putSerializable();
。当应用程序失去焦点时,它不会使应用程序崩溃,任何人都知道这里发生了什么以及我如何纠正它?谢谢
更新
public class CustomStyles implements Serializable{
@SerializedName("pk")
@Expose
private Integer pk;
@SerializedName("name")
@Expose
private String name;
@SerializedName("gender")
@Expose
private String gender;
@SerializedName("photo1")
@Expose
private String photo1;
@SerializedName("custom_price")
@Expose
private Integer customPrice;
@SerializedName("designer")
@Expose
private Designer designer;
public Integer getPk() {
return pk;
}
public void setPk(Integer pk) {
this.pk = pk;
}
public String getName() {
return name;
}
@Override
public String toString() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getPhoto1() {
return photo1;
}
public void setPhoto1(String photo1) {
this.photo1 = photo1;
}
public Integer getCustomPrice() {
return customPrice;
}
public void setCustomPrice(Integer customPrice) {
this.customPrice = customPrice;
}
public Designer getDesigner() {
return designer;
}
public void setDesigner(Designer designer) {
this.designer = designer;
}
}
答案 0 :(得分:1)
您的 CustomStyles 类不可序列化
在您的CustomStyles类中实现serializable(以及在CustomStyles类中使用的所有自定义类)
public class CustomStyles implements Serializable {
.
.
.
.
}