Advertisement
FaizanAhmed123

Untitled

Mar 6th, 2019
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.52 KB | None | 0 0
  1. package com.faizanexample.deventerclass.JSONReadingWriting;
  2.  
  3. import android.content.Context;
  4. import android.util.Log;
  5. import android.widget.Toast;
  6.  
  7. import com.faizanexample.deventerclass.Model.Animal;
  8. import com.google.gson.Gson;
  9.  
  10. import java.io.File;
  11. import java.io.FileOutputStream;
  12. import java.io.FileReader;
  13. import java.io.IOException;
  14. import java.util.List;
  15.  
  16.  
  17.  
  18. public class JSONHelper {
  19. private static final String FILE_NAME="Animal_Dat.json";
  20. private static final String TAG="JSONHelper";
  21. public static boolean exportToJSON(Context context, List<Animal> animalList){
  22. AnimalItem animalItem=new AnimalItem();
  23. animalItem.setAnimals(animalList);
  24. Gson gson=new Gson();
  25. String jsonString =gson.toJson(animalItem);
  26. //Log.i(TAG,jsonString);
  27. FileOutputStream outputStream=null;
  28. File file=new File(context.getFilesDir()+"/"+FILE_NAME);
  29. try {
  30. outputStream=new FileOutputStream(file);
  31.  
  32. if(outputStream==null){Log.i(TAG,"Null");}
  33. outputStream.write(jsonString.getBytes());
  34. return true;
  35.  
  36. } catch (IOException e) {
  37. Toast.makeText(context,"File Exception: "+e.getMessage(),Toast.LENGTH_SHORT);
  38. } finally {
  39. try {
  40. outputStream.close();
  41. } catch (IOException e) {
  42. Toast.makeText(context,"File Exception: "+e.getMessage(),Toast.LENGTH_SHORT);
  43. }
  44. }
  45.  
  46.  
  47. return false;
  48. }
  49. public static List<Animal> importFromJSON(Context context){
  50. FileReader reader=null;
  51. File file=new File(context.getFilesDir()+"/"+FILE_NAME);
  52. try {
  53. reader=new FileReader(file);
  54. Gson gson=new Gson();
  55. AnimalItem animalItem=gson.fromJson(reader,AnimalItem.class);
  56.  
  57.  
  58. return animalItem.getAnimals();
  59.  
  60. } catch (IOException e) {
  61. Toast.makeText(context,"File Exception: "+e.getMessage(),Toast.LENGTH_SHORT);
  62. } finally {
  63. try {
  64. reader.close();
  65. } catch (IOException e) {
  66. Toast.makeText(context,"File Exception: "+e.getMessage(),Toast.LENGTH_SHORT);
  67. }
  68. }
  69. return null;
  70. }
  71. public static class AnimalItem{
  72. List<Animal> animals;
  73.  
  74. public List<Animal> getAnimals() {
  75. return animals;
  76. }
  77.  
  78. public void setAnimals(List<Animal> animals) {
  79. this.animals = animals;
  80. }
  81. }
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement