0
我有一個使用一個DTO類MyAppData
21個屬性的應用程式是DTO-s可以使用Intent/Parcable/Bundle/SharedPreferences的較少的鍋爐代碼?
- 經由Parcable經由意圖轉移活動之間,
- 保存/通過捆綁在旋轉的情況下,恢復和
- 經由SharedPreferences持續(.Editor)如果應用程序稍後重新啓動
我不得不寫很多鍋爐代碼才能實現此功能。
我的問題:是否有一個更簡單的方法,以較少的鍋爐代碼來實現我的目標?
爲什麼這個鍋爐代碼?
- 實施界面
Parcelable
需要作爲活動之間的意圖轉移。 - SharedPreferences(。編輯)到站務應用程序重新啓動:我發現沒有辦法加載/保存Parcable因此我不得不寫額外的代碼爲它
- Fourtunately包可以加載/保存
Parcelable
鍋爐-code看起來像這樣
public class MyAppData implements Parcelable {
/****** here is the data that i want to use ******************/
private String path = null;
// ... 20 more attibutes
public String getPath() {return path;}
public void setPath(String path) {this.path = path;}
// ... 20 more attibutes
/****** here start a lot of boiler-code necessary to handle the data ******************/
/********** code needed to implement interface Parcelable *************/
public static final Parcelable.Creator<MyAppData> CREATOR
= new Parcelable.Creator<MyAppData>() {
public MyAppData createFromParcel(Parcel in) {
return new MyAppData(in);
}
public MyAppData[] newArray(int size) {
return new MyAppData[size];
}
};
public MyAppData() {};
private MyAppData(Parcel in) {
setPath(in.readString());
// ... 20 more attibutes
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(getPath());
// ... 20 more attibutes
}
@Override
public int describeContents() {return 0;}
/************ code neccessary to handle SharedPreferences(.Editor) because SharedPreferences cannot handle Parcable ********/
private static final String SHARED_KEY_Path = "filter_Path";
// ... 20 more attibutes
public void saveSettings(SharedPreferences.Editor edit) {
if (edit != null) {
edit.putString(SHARED_KEY_Path, this.getPath());
// ... 20 more attibutes
}
}
public void loadSettings(SharedPreferences sharedPref) {
if (sharedPref != null) {
this.setPath(sharedPref.getString(SHARED_KEY_Path, this.getPath()));
// ... 20 more attibutes
}
}
}
這是一個使用MyAppData和鍋爐碼碼
MyAppData mMyData;
// to survive recreate on rotation
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
this.mMyData.saveInstanceState(this, savedInstanceState);
super.onSaveInstanceState(savedInstanceState);
}
// to survive recreate on rotation or remember settings on last app start
@Override
protected void onCreate(Bundle savedInstanceState) {
...
this.mMyData.loadSettingsAndInstanceState(this, savedInstanceState);
}
@Override
protected void onPause() {
...
this.mMyData.saveSettings(this);
}
// to pass to some other activity
private void openSomeActivity() {
final Intent intent = new Intent().setClass(context,
SomeActivity.class);
intent.putExtra(EXTRA_FILTER, filter);
context.startActivityForResult(intent, 0815);
}
// to receive from some other activity
@Override
protected void onActivityResult(final int requestCode,
final int resultCode, final Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
switch (requestCode) {
case 0815 :
myData = intent.getParcelableExtra(EXTRA_FILTER);
break;
}
}