简体   繁体   English

Android中的Json离线缓存

[英]Json Offline Caching in Android

I have my website with articles and I already have my Json. 我的网站上有文章,我已经有Json。

So then, I would like to parse my articles in my android app. 因此,我想在我的android应用中解析我的文章。 My code is from: http://www.androidhive.info/2014/07/android-custom-listview-with-image-and-text-using-volley/ 我的代码来自: http : //www.androidhive.info/2014/07/android-custom-listview-with-image-and-text-using-volley/

It works 100% but what I want is to use it even if there is no internet connection or in offline. 它可以100%工作,但是即使没有Internet连接或处于脱机状态,我也想使用它。

I found this link: How can implement offline caching of json in Android? 我找到了此链接: 如何在Android中实现json的离线缓存? but I don't know how can I implement it. 但我不知道该如何实施。

I already tried to add this code inside the try catch: 我已经尝试在try catch中添加以下代码:

cacheThis.writeObject(MainActivity.this, filename, movieList); cacheThis.writeObject(MainActivity.this,文件名,movieList); movieList.addAll((List) cacheThis.readObject(MainActivity.this, filename)); movieList.addAll((List)cacheThis.readObject(MainActivity.this,filename));

and removed the movieList.add(movie); 并删除了movieList.add(movie); but the output is blank. 但输出为空白。

So here's my code: 所以这是我的代码:

public class MainActivity extends Activity implements Serializable {
    // Log tag
    private static final String TAG = MainActivity.class.getSimpleName();

    // Movies json url
    String filename = "time.json";
    private static final String url = "http://api.androidhive.info/json/movies.json";
    private ProgressDialog pDialog;
    private List<Movie> movieList = new ArrayList<Movie>();
    private ListView listView;
    private CustomListAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView = (ListView) findViewById(R.id.list);
        adapter = new CustomListAdapter(this, movieList);
        listView.setAdapter(adapter);

        pDialog = new ProgressDialog(this);
        // Showing progress dialog before making http request
        pDialog.setMessage("Loading...");
        pDialog.show();

        // changing action bar color
        getActionBar().setBackgroundDrawable(
                new ColorDrawable(Color.parseColor("#1b1b1b")));

        // Creating volley request obj
        JsonArrayRequest movieReq = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());
                        hidePDialog();

                        // Parsing json
                        for (int i = 0; i < response.length(); i++) {
                            try {

                                JSONObject obj = response.getJSONObject(i);
                                Movie movie = new Movie();
                                movie.setTitle(obj.getString("title"));
                                movie.setThumbnailUrl(obj.getString("image"));
                                movie.setRating(((Number) obj.get("rating"))
                                        .doubleValue());
                                movie.setYear(obj.getInt("releaseYear"));

                                // Genre is json array
                                JSONArray genreArry = obj.getJSONArray("genre");
                                ArrayList<String> genre = new ArrayList<String>();
                                for (int j = 0; j < genreArry.length(); j++) {
                                    genre.add((String) genreArry.get(j));
                                }
                                movie.setGenre(genre);


                                //cacheThis.writeObject(MainActivity.this, filename, movieList);
                                //movieList.addAll((List<Movie>) cacheThis.readObject(MainActivity.this, filename));
                                // adding movie to movies array
                                movieList.add(movie);

                            } catch (JSONException e) {
                                e.printStackTrace();
                            } catch (ClassNotFoundException e) {
                                e.printStackTrace();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }

                        }

                        // notifying list adapter about data changes
                        // so that it renders the list view with updated data
                        adapter.notifyDataSetChanged();
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d(TAG, "Error: " + error.getMessage());
                        hidePDialog();

                    }
                });

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(movieReq);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        hidePDialog();
    }

    private void hidePDialog() {
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}
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;
    }
}

Here is the general pattern you have to follow: 这是您必须遵循的一般模式:

First of all try to load the item from cache. 首先,尝试从缓存加载项目。 If item exist and did not expire than use it, otherwise make an internet request to fetch the item from web and store the result. 如果项目存在并且没有过期,请使用它,否则请提出一个Internet请求以从Web上获取该项目并存储结果。

As for your code: 至于你的代码:

movieList.addAll((List<Movie>) cacheThis.readObject(MainActivity.this, filename));
if (!movieList.isEmpty) {
    JsonArrayRequest movieReq = new JsonArrayRequest(....
    .....
    AppController.getInstance().addToRequestQueue(movieReq);
} else {
    hidePDialog();
}

Also at the end of your JsonArrayRequest you should just call 同样在JsonArrayRequest的结尾,您应该只调用

cacheThis.writeObject(MainActivity.this, filename, movieList);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM