Deekor Deekor - 6 months ago 25
Android Question

read and write data with GSON

I am struggling to find a good example on how to read and write data in my android app using GSON. Could someone please show me or point me to a good example? I am using this for data persistence between activities.

My professor gave this example to for writing:

Vector v = new Vector(10.0f, 20.0f);
Gson gson = new Gson();
String s = gson.toJson(v);


How would I go about saving that to a file?

Answer

How to save your JSON into a file on internal storage:

String filename = "myfile.txt";

Vector v = new Vector(10.0f, 20.0f);
Gson gson = new Gson();
String s = gson.toJson(v);

FileOutputStream outputStream;

try {
  outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
  outputStream.write(s.getBytes());
  outputStream.close();
} catch (Exception e) {
  e.printStackTrace();
}

How to read it back:

 FileInputStream fis = context.openFileInput("myfile.txt", Context.MODE_PRIVATE);
 InputStreamReader isr = new InputStreamReader(fis);
 BufferedReader bufferedReader = new BufferedReader(isr);
 StringBuilder sb = new StringBuilder();
 String line;
 while ((line = bufferedReader.readLine()) != null) {
     sb.append(line);
 }

 String json = sb.toString();
 Gson gson = new Gson();
 Vector v = gson.fromJson(json, Vector.class);