Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write and Read a json data to internal storage android

I have a json array received from php

[  
   {  
      "name":"Daniel Bryan",
      "img":"pictures\/smallest\/dierdrepic.jpg",
      "username":"@dbryan",
      "user_id":"4"
   },
   {  
      "name":"Devil Hacker",
      "img":"pictures\/smallest\/belitapic.jpg",
      "username":"@dvHack",
      "user_id":"1"
   }
]
  • What i want is to write this data in a file_name.anyextension in my apps data folder or anywhere safe.
  • Also read this data from file_name.anyextension and convert it to a valid json array that can be further edited.

Can anyone show me a way how can i possibly to this thing ?

like image 783
Slim Shady Avatar asked Feb 21 '15 14:02

Slim Shady


People also ask

Where does android store JSON files?

You need to store you json file in assets folder.

How do I access internal storage on android?

You can also access free internal storage from your Android phone through Settings > System > Storage > Device storage. Here you can preview what data are using your internal storage and how much free storage you can use furtherly.


1 Answers

private void writeToFile(String data) {
    try {
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("config.txt", Context.MODE_PRIVATE));
        outputStreamWriter.write(data);
        outputStreamWriter.close();
    }
    catch (IOException e) {
        Log.e("Exception", "File write failed: " + e.toString());
    } 
}


private String readFromFile() {

    String ret = "";

    try {
        InputStream inputStream = context.openFileInput("config.txt");

        if ( inputStream != null ) {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String receiveString = "";
            StringBuilder stringBuilder = new StringBuilder();

            while ( (receiveString = bufferedReader.readLine()) != null ) {
                stringBuilder.append(receiveString);
            }

            inputStream.close();
            ret = stringBuilder.toString();
        }
    }
    catch (FileNotFoundException e) {
        Log.e("login activity", "File not found: " + e.toString());
    } catch (IOException e) {
        Log.e("login activity", "Can not read file: " + e.toString());
    }

    return ret;
}

When read string from file convert it to JsonObject or JsonArray

JSONArray jarray = new JSONArray(str);
like image 77
Morteza Soleimani Avatar answered Sep 22 '22 12:09

Morteza Soleimani