How to Cache Parsed JSON for Offline usage

前端 未结 2 1606
走了就别回头了
走了就别回头了 2020-12-30 15:06

I have parsed JSON successfully but now i want to Cache it for offline usage, even internet is not available, and if any new entry comes i want to cache that as well.

<
2条回答
  •  独厮守ぢ
    2020-12-30 16:05

    Why not just save it to cache folder of your app using something like this:

    String path = Environment.getExternalStorageDirectory() + File.separator + "cache" + File.separator;
    File dir = new File(path);
    if (!dir.exists()) {
        dir.mkdirs();
    }
    path += "data";
    File data = new File(path);
    if (!data.createNewFile()) {
        data.delete();
        data.createNewFile();
    }
    ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(data));
    objectOutputStream.writeObject(actorsList);
    objectOutputStream.close();
    

    And after, you can read it in any time using:

    List list = null;
    File data = new File(path);
    try {
        if(data.exists()) {
            ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(data));
            list = (List) objectInputStream.readObject();
            objectInputStream.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    
    
    

    UPDATE: Okay, make class named ObjectToFileUtil, paste this code to created class

    package ;
    
    import android.os.Environment;
    
    import java.io.*;
    
    public class ObjectToFileUtil {
    
        public static String objectToFile(Object object) throws IOException {
            String path = Environment.getExternalStorageDirectory() + File.separator + "cache" + File.separator;
            File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            path += "data";
            File data = new File(path);
            if (!data.createNewFile()) {
                data.delete();
                data.createNewFile();
            }
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(data));
            objectOutputStream.writeObject(object);
            objectOutputStream.close();
            return path;
        }
    
        public static Object objectFromFile(String path) throws IOException, ClassNotFoundException {
            Object object = null;
            File data = new File(path);
            if(data.exists()) {
                ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(data));
                object = objectInputStream.readObject();
                objectInputStream.close();
            }
            return object;
        }
    }
    

    Change < yourpackagehere > to your package name and don't forget to add WRITE_EXTERNAL_STORAGE permission to AndroidManifest.xml. In your MainActivity add field

    private String dataPath;
    

    and replace your onPostExecute method of JSONAsyncTask class to

    protected void onPostExecute(Boolean result) {
        dialog.cancel();
        adapter.notifyDataSetChanged();
        if(result) {
            try {
                dataPath = objectToFile(arrayList);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
        }
    }
    

    Now you can access get actorsList from File anytime when you want, by using

    try {
        actorsList = (ArrayList)objectFromFile(dataPath);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    

    If you want to save path of file after closing application you must save dataPath string (and load on application start), for example, using SharedPreferences.

    提交回复
    热议问题