Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.faizanexample.deventerclass.JSONReadingWriting;
- import android.content.Context;
- import android.util.Log;
- import android.widget.Toast;
- import com.faizanexample.deventerclass.Model.Animal;
- import com.google.gson.Gson;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.FileReader;
- import java.io.IOException;
- import java.util.List;
- public class JSONHelper {
- private static final String FILE_NAME="Animal_Dat.json";
- private static final String TAG="JSONHelper";
- public static boolean exportToJSON(Context context, List<Animal> animalList){
- AnimalItem animalItem=new AnimalItem();
- animalItem.setAnimals(animalList);
- Gson gson=new Gson();
- String jsonString =gson.toJson(animalItem);
- //Log.i(TAG,jsonString);
- FileOutputStream outputStream=null;
- File file=new File(context.getFilesDir()+"/"+FILE_NAME);
- try {
- outputStream=new FileOutputStream(file);
- if(outputStream==null){Log.i(TAG,"Null");}
- outputStream.write(jsonString.getBytes());
- return true;
- } catch (IOException e) {
- Toast.makeText(context,"File Exception: "+e.getMessage(),Toast.LENGTH_SHORT);
- } finally {
- try {
- outputStream.close();
- } catch (IOException e) {
- Toast.makeText(context,"File Exception: "+e.getMessage(),Toast.LENGTH_SHORT);
- }
- }
- return false;
- }
- public static List<Animal> importFromJSON(Context context){
- FileReader reader=null;
- File file=new File(context.getFilesDir()+"/"+FILE_NAME);
- try {
- reader=new FileReader(file);
- Gson gson=new Gson();
- AnimalItem animalItem=gson.fromJson(reader,AnimalItem.class);
- return animalItem.getAnimals();
- } catch (IOException e) {
- Toast.makeText(context,"File Exception: "+e.getMessage(),Toast.LENGTH_SHORT);
- } finally {
- try {
- reader.close();
- } catch (IOException e) {
- Toast.makeText(context,"File Exception: "+e.getMessage(),Toast.LENGTH_SHORT);
- }
- }
- return null;
- }
- public static class AnimalItem{
- List<Animal> animals;
- public List<Animal> getAnimals() {
- return animals;
- }
- public void setAnimals(List<Animal> animals) {
- this.animals = animals;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement