Skip to content Skip to sidebar Skip to footer

Write To JSONObject To JSONfile

I have an app that has to take a string, encode it into JSONObject format and write it into a JSON file in the SD. It all seems to be working fine apart from writing part. I have &

Solution 1:

Tested, Hi replace few lines and this will fix your issue.

  JSONObject jsonObject = makeJsonObject();
    try{
        Writer output = null;
        File file = new File(Environment.getExternalStorageDirectory(), "importantemail.json");
        if(file.isDirectory()){
            file.delete();
        }
        if(!file.exists()){
            file.createNewFile();
        }
        output = new BufferedWriter(new FileWriter(file));
        output.write(jsonObject.toString());
        output.close();
        Toast.makeText(getApplicationContext(), "Composition saved", Toast.LENGTH_LONG).show();

    } catch (Exception e) {
        Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
    }
    finish();


}
public JSONObject makeJsonObject()
{
    JSONObject object = new JSONObject();
    try {
        object.put("Message ID", 5);
        object.put("Sender","test");
        object.put("Subject","test");
        object.put("E-mail:","test");
    }catch (JSONException e)
    {
        e.printStackTrace();
    }
    return object;
}

Solution 2:

in 6.0 or later versions of android, you must give runtime permission. check this.


Post a Comment for "Write To JSONObject To JSONfile"