示例#1
0
  /**
   * loadCache
   *
   * @throws IOException
   */
  @SuppressWarnings("unused")
  private void loadCache() {
    Context pContext = mContext.get();
    if (null == pContext) return;

    // Get content.
    String strContent = null;
    FileInputStream pInputStream = null;
    try {
      pInputStream = pContext.openFileInput(CACHE_FILE);

      byte aBytes[] = new byte[pInputStream.available()];
      pInputStream.read(aBytes);

      strContent = new String(aBytes);

      // Parse the json object.
      JSONObject pRoot = new JSONObject(strContent);
      JSONArray aArray = pRoot.optJSONArray(JSON_TAG);
      final int nLength = (null != aArray ? aArray.length() : 0);
      for (int nIdx = 0; nIdx < nLength; nIdx++) {
        JSONObject pObject = aArray.getJSONObject(nIdx);
        MsgEntity pEntity = new MsgEntity();
        pEntity.parse(pObject);

        // Save to array.
        this.append(pEntity);
      }

    } catch (FileNotFoundException aException) {
      aException.printStackTrace();
      strContent = null;
    } catch (IOException aException) {
      aException.printStackTrace();
      strContent = null;
    } catch (JSONException aException) {
      aException.printStackTrace();
    } finally {
      if (null != pInputStream) {
        try {
          pInputStream.close();
        } catch (IOException aException) {
          aException.printStackTrace();
        }
        pInputStream = null;
      }
    }
  }
示例#2
0
  /** saveCache Save cache to local storage. */
  public void saveCache() {
    if (!mUpdated) {
      // Do nothing when records are not updated.
      return;
    }

    final int nSize = (null != mCache ? mCache.size() : 0);
    if (0 >= nSize) return;

    // Save cache to local storage.
    Context pContext = mContext.get();
    if (null == pContext) return;

    FileOutputStream pOutputStream = null;
    try {
      JSONObject pRoot = new JSONObject();
      JSONArray aArray = new JSONArray();
      pRoot.put(JSON_TAG, aArray);

      // Save the content.
      for (MsgEntity entity : mCache) {
        aArray.put(entity.toJson());
      }

      pOutputStream = pContext.openFileOutput(CACHE_FILE, Context.MODE_PRIVATE);
      pOutputStream.write(pRoot.toString().getBytes());

    } catch (FileNotFoundException aException) {
      aException.printStackTrace();
    } catch (IOException aException) {
      aException.printStackTrace();
    } catch (JSONException aException) {
      aException.printStackTrace();
    } finally {
      if (null != pOutputStream) {
        try {
          pOutputStream.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
        pOutputStream = null;
      }
    }
  }