Ejemplo n.º 1
0
  public void makeJSON() {
    DatabaseHelper dbHelper = new DatabaseHelper(a.getApplicationContext());
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    MedalsDao medalsDao = new MedalsDao(db);

    List<Medal> medals = medalsDao.findAll();

    JSONArray array = new JSONArray();
    JSONObject json;

    for (Medal medal : medals) {
      try {
        json = new JSONObject();
        json.put(Constants.KEY_NAME, medal.getDescription());
        json.put(Constants.KEY_CHECKED, medal.isChecked());

        array.put(json);
      } catch (JSONException e) {
        break;
      }
    }

    String filePath =
        Environment.getExternalStorageDirectory()
            + File.separator
            + Constants.DIR_NAME
            + File.separator
            + Constants.FILE_NAME;
    db.close();

    File jsonFile = new File(filePath);
    try {
      PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(jsonFile)));
      pw.print(array.toString());
      pw.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Ejemplo n.º 2
0
  public void restore() {

    DatabaseHelper dbHelper = new DatabaseHelper(a.getApplicationContext());
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    MedalsDao medalsDao = new MedalsDao(db);
    String filePath =
        Environment.getExternalStorageDirectory()
            + File.separator
            + Constants.DIR_NAME
            + File.separator
            + Constants.FILE_NAME;

    try {
      File file = new File(filePath);
      byte[] fileByte = new byte[(int) file.length()];
      FileInputStream fi = new FileInputStream(file);

      String backupData;
      fi.read(fileByte);
      backupData = new String(fileByte);

      fi.close();

      JSONArray array = new JSONArray(backupData);
      JSONObject json;
      for (int i = 0; i < array.length(); i++) {
        json = array.getJSONObject(i);
        medalsDao.updateFromDesc(
            json.getString(Constants.KEY_NAME), json.getInt(Constants.KEY_CHECKED));
      }
    } catch (Exception e) {

    } finally {
      db.close();
    }
  }