Last active
February 15, 2022 08:54
-
-
Save teocci/80bf687b3f26de4f6b812bdcbf62f6a6 to your computer and use it in GitHub Desktop.
save JSON data in a file and retrieve it
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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