0

I want to set JSon data in cache for be available offline and to reduce load time. So, I've made a AsyncTask with this post: How to Cache Json data to be available offline?

My application has store data in the offline file (I think because I have data in cache), but it don't parse it when I reload the app. So when I reload the application, it reparse data from internet and not from the cache file. So I want that the application parse the old data with the cache and look if we have new data to download from the URL.

This is my code:

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

    /* Navigation Sample */
    toolbar = (Toolbar) findViewById(R.id.tool_bar);
    setSupportActionBar(toolbar);
    mRecyclerView = (RecyclerView) findViewById(R.id.RecyclerView); // Assigning the RecyclerView Object to the xml View
    mRecyclerView.setHasFixedSize(true);                            // Letting the system know that the list objects are of fixed size
    mAdapter = new MyAdapter(TITLES,ICONS,NAME,EMAIL,PROFILE);       // Creating the Adapter of MyAdapter class(which we are going to see in a bit)
    mRecyclerView.setAdapter(mAdapter);                              // Setting the adapter to RecyclerView
    mLayoutManager = new LinearLayoutManager(this);                 // Creating a layout Manager
    mRecyclerView.setLayoutManager(mLayoutManager);                 // Setting the layout Manager
    Drawer = (DrawerLayout) findViewById(R.id.DrawerLayout);        // Drawer object Assigned to the view
    mDrawerToggle = new ActionBarDrawerToggle(this,Drawer,toolbar,R.string.openDrawer,R.string.closeDrawer){

        @Override
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            // code here will execute once the drawer is opened( As I dont want anything happened whe drawer is
            // open I am not going to put anything here)
        }

        @Override
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
            // Code here will execute once drawer is closed
        }
    }; // Drawer Toggle Object Made
    Drawer.setDrawerListener(mDrawerToggle); // Drawer Listener set to the Drawer toggle
    mDrawerToggle.syncState();               // Finally we set the drawer toggle sync State




    // My App

    mListView = (ListView) findViewById(list1);
    imagearticle = (ImageView) findViewById(R.id.imagearticleaccueil);

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    new TheTask().execute();
    }

    class TheTask extends AsyncTask<Void, Void, JSONArray> {
        ProgressDialog pd;

        @Override
        protected void onPostExecute(JSONArray result) {
            super.onPostExecute(result);
            pd.dismiss();

            Log.i("4", "ok");
            try
            {
                Log.i("5", "ok");
                for(int i=0;i<result.length();i++)
                {
                    json_data = result.getJSONObject(i);
                    try {
                        URL imageURL = new URL("http://" + json_data.getString("article_thumbnail"));
                        HttpURLConnection connection = (HttpURLConnection) imageURL.openConnection();
                        InputStream inputStream = connection.getInputStream();
                        bitmap = BitmapFactory.decodeStream(inputStream);

                        Log.i("6", "ok");

                    } catch (MalformedURLException e) {
                        Log.i("chargementimage", "" + e.toString());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    HashMap<String,Object> temp=new HashMap<String, Object>();
                    temp.put("id", json_data.getString("article_id"));
                    temp.put("picture", bitmap);
                    temp.put("nom", json_data.getString("article_title").replaceAll("&#039;", "'"));
                    temp.put("client", json_data.getString("username"));
                    donnees.add(temp);

                    Log.i("7", "ok");

                }

                Log.i("8", "ok");
                adapter = new SimpleAdapter(getBaseContext(),donnees,
                        R.layout.list_article,new String[]{"picture", "nom","client"},new int[] {R.id.imagearticleaccueil, R.id.nom, R.id.client});
                adapter.setViewBinder(new MyViewBinder());

                mListView.setAdapter(adapter);

                Log.i("9", "ok");

            }
            catch(JSONException e){
                Log.i("tagjsonexp", "" + e.toString());
            }
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pd = ProgressDialog.show(MainActivity.this, "State",
                    "Loading...", true);
        }

        @Override
        protected JSONArray doInBackground(Void... arg0) {

            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(strURL);
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
            } catch (Exception e) {
                Log.e("log_tag", "Error in http connection " + e.toString());
            }

            // Convert response to string
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                result = sb.toString();
                writeToFile(result);

                Log.i("1", "ok");
            } catch (Exception e) {
                Log.e("log_tag", "Error converting result " + e.toString());
            }

            try {
                jArray = new JSONArray(result);
                Log.i("2", "ok");
            } catch (JSONException e) {
                Log.e("log_tag", "Error parsing data " + e.toString());
            }

            try {
                jArray = new JSONArray(readFromFile());
                Log.i("3", "ok");
            } catch (JSONException e) {
                Log.e("log_tag", "Error parsing data " + e.toString());
            }
            return jArray;
        }
    }

private void writeToFile(String data) {
    try {
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("config.txt", Context.MODE_PRIVATE));
        outputStreamWriter.write(data);
        outputStreamWriter.close();
    }
    catch (IOException e) {
        Log.e("Exception", "File write failed: " + e.toString());
    }
}

private String readFromFile() {

    String ret = "";

    try {
        InputStream inputStream = openFileInput("config.txt");

        if ( inputStream != null ) {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String receiveString = "";
            StringBuilder stringBuilder = new StringBuilder();

            while ( (receiveString = bufferedReader.readLine()) != null ) {
                stringBuilder.append(receiveString);
            }

            inputStream.close();
            ret = stringBuilder.toString();
        }
    } catch (FileNotFoundException e) {
        Log.e("login activity", "File not found: " + e.toString());
    } catch (IOException e) {
        Log.e("login activity", "Can not read file: " + e.toString());
    }

    return ret;
}

Thanks

Community
  • 1
  • 1
Dave1111
  • 89
  • 7
  • Check your doInBackground(). It has 1."read from web" 2."write to cache" 3."read from cache" .. but no "check the existance of cache and read from it" code before 1. (numbers in this comment are not same in your code) – Toris Jul 19 '15 at 16:49
  • May you help me please to do this ? Thanks – Dave1111 Jul 19 '15 at 18:04

1 Answers1

1

I've not tested but this may work. Sorry for bad indent.


    @Override
    protected JSONArray doInBackground(Void... arg0) {

    // result is used as String but not defined in doInBackground() ...

    // Load from cache
    String result = readFromFile();

   // If cache is empty, load from web 
   if ("".equals(result))
    {
        // COPY from original code BEGIN
        try {
            HttpClient httpclient = new DefaultHttpClient();
        ....
            result = sb.toString();
            writeToFile(result);

            Log.i("1", "ok");
        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
        }
        // COPY from original code END
    } // end of if ("".equals(result))

        try {
            jArray = new JSONArray(result);
            Log.i("2", "ok");
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }

        /*
        // We already got jArray.
        try {
            jArray = new JSONArray(readFromFile());
            Log.i("3", "ok");
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }
        */

        return jArray;
    } // end of doInBackground()
Toris
  • 2,348
  • 13
  • 16
  • Thank you that's work but if I want to update my Json for add an article. I need to compare the json and the `readFromFile()` ? And how to compare only the last article to not refresh all the article (long time to load). Thanks – Dave1111 Jul 19 '15 at 19:20
  • Check timestamp or ETag (or hash). It depends on what headers server will return. – Toris Jul 19 '15 at 19:39
  • This may helps. http://stackoverflow.com/questions/7095897/im-trying-to-use-javas-httpurlconnection-to-do-a-conditional-get-but-i-neve – Toris Jul 19 '15 at 19:51