How can implement offline caching of json in Android?

后端 未结 3 1478
旧时难觅i
旧时难觅i 2021-02-02 04:42

I am working on a articles application like techcrunch I am parsing data from json. I am parsing title,author and image from json. Articles are displayed in list-view. I want to

3条回答
  •  暖寄归人
    2021-02-02 05:12

    This probably isn't the best way to do it, but it worked for me.

    You might find this helpful: http://www.vogella.com/tutorials/JavaSerialization/article.html

    I had to do the same in some project. This is what I did:

    public final class cacheThis {
    private cacheThis() {}
    
    public static void writeObject(Context context, String fileName, Object object) throws IOException {
          FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
          ObjectOutputStream oos = new ObjectOutputStream(fos);
          oos.writeObject(object);
          oos.flush();
          oos.close();
    
          fos.close();
       }
    
       public static Object readObject(Context context, String fileName) throws IOException,
             ClassNotFoundException {
          FileInputStream fis = context.openFileInput(fileName);
          ObjectInputStream ois = new ObjectInputStream(fis);
          Object object = ois.readObject();
          fis.close();
          return object;
       }
    }
    

    To write to file:

    cacheThis.writeObject(YourActivity.this, fileName, movieList);
    

    To read from file:

    movieList.addAll((List) cacheThis.readObject(
                    VideoActivity.this, fileName));
    

    You have to have your Movie class implements Serializable

提交回复
热议问题