Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class CategoriaPersist {
- private static CategoriaPersist catpersist = null;
- private ArrayList <Categoria> arrayCategorias;
- private Context contexto;
- private static final String file_name = "categorias";
- private Gson gson;
- public CategoriaPersist(Context contexto) {
- gson = new GsonBuilder().create();
- arrayCategorias = new ArrayList<>();
- loadCategory(contexto);
- this.contexto = contexto;
- }
- //Singleton - para que se pueda instanciar solo una vez
- public static CategoriaPersist instanceOf(Context contexto){
- if(catpersist == null){
- catpersist = new CategoriaPersist(contexto);
- }
- return catpersist;
- }
- public void setContext(Context contexto){
- this.contexto = contexto;
- }
- public void addCategory(Categoria cat, Context contexto){
- arrayCategorias.add(cat);
- persist(contexto);
- }
- public void delCategory(Categoria cat){
- arrayCategorias.remove(cat);
- persist(contexto);
- }
- public void persist(Context contexto){
- String categories = gson.toJson(arrayCategorias);
- File file = new File(contexto.getFilesDir(), file_name);
- FileOutputStream outputStream;
- try {
- outputStream = new FileOutputStream(file);
- outputStream.write(categories.getBytes());
- outputStream.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- public void loadCategory(Context contexto){
- File f = new File(contexto.getFilesDir(), file_name);
- if(!f.exists()){
- try{
- f.createNewFile();
- } catch (IOException ioe){
- }
- }
- try{
- FileInputStream fis = contexto.openFileInput(file_name);
- InputStreamReader isr = new InputStreamReader(fis);
- BufferedReader bufferedReader = new BufferedReader(isr);
- StringBuilder sb = new StringBuilder();
- String line;
- while ((line = bufferedReader.readLine()) != null) {
- sb.append(line);
- }
- if(sb.toString().equals("")){
- return;
- }
- arrayCategorias = gson.fromJson(sb.toString(),
- new TypeToken<ArrayList<Categoria>>(){}.getType());
- }catch(FileNotFoundException e){
- e.printStackTrace();
- }catch(IOException e){
- e.printStackTrace();
- }
- }
- public ArrayList <Categoria> getCategorias(){
- return arrayCategorias;
- }
- }
Add Comment
Please, Sign In to add comment