Guest User

Untitled

a guest
Jun 20th, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.55 KB | None | 0 0
  1. public class CategoriaPersist {
  2.  
  3. private static CategoriaPersist catpersist = null;
  4. private ArrayList <Categoria> arrayCategorias;
  5. private Context contexto;
  6. private static final String file_name = "categorias";
  7.  
  8. private Gson gson;
  9.  
  10. public CategoriaPersist(Context contexto) {
  11.  
  12. gson = new GsonBuilder().create();
  13. arrayCategorias = new ArrayList<>();
  14. loadCategory(contexto);
  15. this.contexto = contexto;
  16. }
  17.  
  18. //Singleton - para que se pueda instanciar solo una vez
  19. public static CategoriaPersist instanceOf(Context contexto){
  20.  
  21. if(catpersist == null){
  22.  
  23. catpersist = new CategoriaPersist(contexto);
  24. }
  25. return catpersist;
  26. }
  27.  
  28. public void setContext(Context contexto){
  29.  
  30. this.contexto = contexto;
  31. }
  32.  
  33. public void addCategory(Categoria cat, Context contexto){
  34.  
  35. arrayCategorias.add(cat);
  36. persist(contexto);
  37. }
  38.  
  39. public void delCategory(Categoria cat){
  40.  
  41. arrayCategorias.remove(cat);
  42. persist(contexto);
  43. }
  44.  
  45. public void persist(Context contexto){
  46.  
  47. String categories = gson.toJson(arrayCategorias);
  48. File file = new File(contexto.getFilesDir(), file_name);
  49. FileOutputStream outputStream;
  50. try {
  51. outputStream = new FileOutputStream(file);
  52. outputStream.write(categories.getBytes());
  53. outputStream.close();
  54. } catch (Exception e) {
  55. e.printStackTrace();
  56. }
  57. }
  58.  
  59. public void loadCategory(Context contexto){
  60.  
  61. File f = new File(contexto.getFilesDir(), file_name);
  62.  
  63. if(!f.exists()){
  64. try{
  65. f.createNewFile();
  66. } catch (IOException ioe){
  67.  
  68. }
  69. }
  70. try{
  71. FileInputStream fis = contexto.openFileInput(file_name);
  72. InputStreamReader isr = new InputStreamReader(fis);
  73. BufferedReader bufferedReader = new BufferedReader(isr);
  74. StringBuilder sb = new StringBuilder();
  75. String line;
  76. while ((line = bufferedReader.readLine()) != null) {
  77. sb.append(line);
  78. }
  79.  
  80. if(sb.toString().equals("")){
  81. return;
  82. }
  83.  
  84. arrayCategorias = gson.fromJson(sb.toString(),
  85. new TypeToken<ArrayList<Categoria>>(){}.getType());
  86.  
  87. }catch(FileNotFoundException e){
  88. e.printStackTrace();
  89. }catch(IOException e){
  90. e.printStackTrace();
  91. }
  92. }
  93.  
  94. public ArrayList <Categoria> getCategorias(){
  95.  
  96. return arrayCategorias;
  97. }
  98. }
Add Comment
Please, Sign In to add comment