Skip to content

Instantly share code, notes, and snippets.

@teocci
Last active February 15, 2022 08:54
Show Gist options
  • Save teocci/80bf687b3f26de4f6b812bdcbf62f6a6 to your computer and use it in GitHub Desktop.
Save teocci/80bf687b3f26de4f6b812bdcbf62f6a6 to your computer and use it in GitHub Desktop.
save JSON data in a file and retrieve it
Gson gson = new Gson();
Type collectionType = new TypeToken<ArrayList<PersonContainer>>() {}.getType();
ArrayList<PersonContainer> Persons = gson.fromJson(new FileReader("input.json"), collectionType);
System.out.println(gson.toJson(persons));
class PersonContainer
{
Person person;
}
class Person
{
public int id;
public String name;
}
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.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment