当Activty在Android上停止时保存自定义对象

时间:2014-06-26 15:24:07

标签: android android-activity storage

我写了一个小的andorid应用程序。此应用程序使用自定义对象的矢量并在列表视图中显示它们。我想在活动发送到后台时保存这些对象。什么是最好的方法。在向量中约有25个对象。每个对象都有一个布尔值,两个长和两个字符串。

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

当应用关闭时或活动进入后台时,您是否需要保存它们?

如果您的对象是parcelables,则可以使用保存和恢复实例状态方法:

    @Override
    protected void onSaveInstanceState(Bundle outState) {

        super.onSaveInstanceState(outState);
        outState.putParcelableArrayList("objectsArray", myObjects); // if its an array of parceleble objects

    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
            myObjects= savedInstanceState.getParcelableArrayList("objectsArray");
    }

这是一个parcelable对象的例子

公共类KNUserSketch实现了Parcelable {

public int id;
public int user;
public String url;
public int views;
public int locations;


public KNUserSketch(JSONObject obj)
{
    id = KNSafeJSonUtilties.safeGetInteger(obj, "id");
    user = KNSafeJSonUtilties.safeGetInteger(obj, "user");
    views = KNSafeJSonUtilties.safeGetInteger(obj, "views"); 
    locations = KNSafeJSonUtilties.safeGetInteger(obj, "locations");
    url =  KNSafeJSonUtilties.safeGetString(obj, "url");
    Log.v("JSON","jsonObject: "+obj.toString());
    url.replace("https:", "http:");
}

public KNUserSketch(){
    id=-1;
    user=-1;
    views = 0;
    url ="";
}

public KNUserSketch(Parcel p){
    id= p.readInt();
    user = p.readInt();
    url = p.readString();
    views = p.readInt();
    locations = p.readInt();
}

@Override
public int describeContents() {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    // TODO Auto-generated method stub
    dest.writeInt(id);
    dest.writeInt(user);
    dest.writeString(url);
    dest.writeInt(views);
    dest.writeInt(locations);
}

public static final Parcelable.Creator<KNUserSketch> CREATOR = new Creator<KNUserSketch>() {

    public KNUserSketch createFromParcel(Parcel source) {
        return new KNUserSketch(source);
    }

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

};

}

答案 1 :(得分:0)

您可以使用SharedPreferences将对象放在安全的地方,但是objets必须实现Parcelable协议。