Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ANDROID: How to save JSON data in a file and retrieve it?

Tags:

json

file

android

I'm new to android so please help me out. I am trying to save my ToDoList in a file so that the next time I open it, all the items are reloaded

This is the code I have so far,

MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
gson = new Gson();
    try {
        BufferedReader br = new BufferedReader(new FileReader("storage.json"));
        Entry e = gson.fromJson(br, Entry.class);
        Log.d("reading", e.toString());
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }}

@Override
protected void onStop() {
    super.onStop();
    json = gson.toJson(mEntries);
    Log.d("jsondata", json);
    try {
        file1 = new FileWriter("storage.json");
        file1.write(json);
        file1.flush();
        file1.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

Entry.java

public class Entry {
String S;
boolean b;

public Entry(String S, boolean b) {
    this.S = S;
    this.b = b;
}

public String getS() {
    return S;
}

public void setS(String S) {
    this.S = S;
}

public void setB(boolean b) {
    this.b = b;
}

public boolean isB() {
    return b;
}

}

How do I proceed from here? In onCreate() I would like to check if the file exists and if yes, import data from file and display on screen.

like image 220
android101 Avatar asked Oct 21 '16 04:10

android101


People also ask

How do I save JSON data to a file?

Another way of writing JSON to a file is by using json.dump() method The JSON package has the “dump” function which directly writes the dictionary to a file in the form of JSON, without needing to convert it into an actual JSON object.

How do I save JSON to local text file?

To save JSON to local text file with JavaScript. we can create a blob from the text. const a = document. createElement("a"); const file = new Blob([content], { type: "text/plain" }); a.


1 Answers

Every android app has its own internal storage only that app can access, you can read from there or write to it.

In you case, you first want to check if you such file exist before creating one.

  private String read(Context context, String fileName) {
    try {
        FileInputStream fis = context.openFileInput(fileName);
        InputStreamReader isr = new InputStreamReader(fis);
        BufferedReader bufferedReader = new BufferedReader(isr);
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            sb.append(line);
        }
        return sb.toString();
    } catch (FileNotFoundException fileNotFound) {
        return null;
    } catch (IOException ioException) {
        return null;
    }
}

private boolean create(Context context, String fileName, String jsonString){
    String FILENAME = "storage.json";
    try {
        FileOutputStream fos = context.openFileOutput(fileName,Context.MODE_PRIVATE);
        if (jsonString != null) {
            fos.write(jsonString.getBytes());
        }
        fos.close();
        return true;
    } catch (FileNotFoundException fileNotFound) {
        return false;
    } catch (IOException ioException) {
        return false;
    }

}

public boolean isFilePresent(Context context, String fileName) {
    String path = context.getFilesDir().getAbsolutePath() + "/" + fileName;
    File file = new File(path);
    return file.exists();
}

onCreate of the Activity, you can use do the following

boolean isFilePresent = isFilePresent(getActivity(), "storage.json");
if(isFilePresent) {
   String jsonString = read(getActivity(), "storage.json");
   //do the json parsing here and do the rest of functionality of app
} else {
   boolean isFileCreated = create(getActivity, "storage.json", "{}");
   if(isFileCreated) {
     //proceed with storing the first todo  or show ui
   } else {
     //show error or try again.
   }
}

reference https://developer.android.com/guide/topics/data/data-storage.html#filesInternal

like image 103
SanthoshN Avatar answered Sep 17 '22 20:09

SanthoshN