首先我们盘点一下参与者
Crime 罪犯类,
CrimeLab 罪犯列表类
CriminalIntentJSONSerializer 罪犯json化 并且保存
没有视图也没有控制的事 三个模型类玩游戏
保存和加载自然归CriminalIntentJSONSerializer管理
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public class CriminalIntentJSONSerializer { private Context context; private String Filename; public CriminalIntentJSONSerializer(Context c, String f) { context = c; Filename = f; } public void saveCrimes(ArrayList<Crime> crimes) throws JSONException,IOException {....} public ArrayList<Crime> loadCrimes() throws IOException,JSONException {....}
|
将crime自己变成JSON 和将JSON 变成crime自然是Crime自己的事情喽
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| public class Crime extends android.text.format.DateFormat{ public JSONObject toJSON()throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put(JSON_ID,mId.toString()); jsonObject.put(JSON_TITLE,mTitle); jsonObject.put(JSON_SOLVED,mSolved); jsonObject.put(JSON_DATE,mDate.getTime()); if(photo!=null) jsonObject.put(JSON_PHOTO,photo.toJSON()); return jsonObject; } public Crime(JSONObject jsonObject) throws JSONException { mId = UUID.fromString(jsonObject.getString(JSON_ID)); if(jsonObject.has(JSON_TITLE)) { mTitle=jsonObject.getString(JSON_TITLE); } mSolved=jsonObject.getBoolean(JSON_SOLVED); mDate = new Date(jsonObject.getLong(JSON_DATE)); if(jsonObject.has(JSON_PHOTO)) photo = new Photo(jsonObject.getJSONObject(JSON_PHOTO)); }
|
那剩下那个干嘛呢?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| public class CrimeLab { private CriminalIntentJSONSerializer criminalIntentJSONSerializer; public boolean saveCrimes() { try { criminalIntentJSONSerializer.saveCrimes(crimes); Log.d(TAG,"crimes saved to file"); return true; } catch (Exception e) { Log.e(TAG,"Error saving criems;",e); return false; } } }
|
CrimeLab 负责将crime批量传输到CriminalIntentJSONSerializer,然后每一个crime调用自己的toJSON方法,最后保存起来;
加载的时候,每一个crime都直接调用自己的初始化方法。从JSON拿到数据;
是不是很清楚的;