Algodrill
Algodrill

Reputation: 126

Saving JSON to system cache

In my application I get a json a url that contains information. I would like to save this json in the phone and then used the json whether the phone is identical to that of the url. If the json to change, then you should download again the json.

I get my json recovered and read my object but I'd keep the json in the phone memory and use the json to avoid downloading it again to save the data

Can you help me please?

One example:

public void affichage_phenomene(final String id_phenomene)
{
    if(id_phenomene.length()==0)
        return;

    mProgressDialog = ProgressDialog.show(this, "Patientez","Chargement...", true);

    new Thread((new Runnable()
    {
        public void run()
        {
            try
            {
                JSONArray jsonArray = Json.getJsonByUrl(page_Json); // On récupère un tableau contenant les éléments json           
                JSONObject jsonObject = jsonArray.getJSONObject(0);
                listItem2 = new ArrayList<HashMap<String, String>>();

                map.put("titre", jsonObject.getString("nom"));
                map.put("description", jsonObject.getString("description"));
                map.put("liens", jsonObject.getString("liens"));
                map.put("note_moyenne", jsonObject.getString("note_moyenne"));
                map.put("img",LoadPicture.loadImageFromWebOperations(getString(R.string.URL_Images)+jsonObject.getString("image"),"/sdcard/MysticWay/phenomene_"+idphenomene+".jpg"));
                JSONArray liste_lieux = jsonObject.getJSONArray("lieux");
                nombre_de_lieux = liste_lieux.length();
                if(nombre_de_lieux>0)
                {

                    for(int i = 0;i<nombre_de_lieux;i++)
                    {
                        map3 = new HashMap<String, String>();
                        JSONObject lieucible = liste_lieux.getJSONObject(i);
                        map3.put("idlieu", lieucible.getString("idlieuxspirituels"));
                        map3.put("nomlieu", lieucible.getString("nom_lieux"));
                        map3.put("adresse", lieucible.getString("adresse_lieux"));
                        map3.put("img", LoadPicture.loadImageFromWebOperations(getString(R.string.URL_Images)+lieucible.getString("image"),"/sdcard/MysticWay/icon_lieu_"+lieucible.getString("idlieuxspirituels")+".jpg"));
                        listItem2.add(map3);
                    }
                }
                handler.sendEmptyMessage(0);
                return;
            }
            catch (Exception e)
            {
                e.printStackTrace();
                handler.sendEmptyMessage(1);
                return;
            }
        }
    })).start();
}

private Handler handler = new Handler() {
    public void handleMessage(android.os.Message msg) {
        if(msg.what == 0)
        {
            // Si le transfert c'est bien exécuté
            mProgressDialog.dismiss();
            Titre.setText(map.get("titre"));
            Description.setText(Html.fromHtml(map.get("description")));
            Lien.setText(map.get("liens"));
            note.setText(map.get("note_moyenne"));
            if(nombre_de_lieux==1)
            {
                View_Fiche_Phenomene.this.liste_lieux.setText(nombre_de_lieux+" lieu est associé à ce phénomène.");
                liste_lieux.setEnabled(true);
            }
            else if (nombre_de_lieux>1)
            {
                View_Fiche_Phenomene.this.liste_lieux.setText(nombre_de_lieux+" lieux sont associés à ce phénomène.");
                liste_lieux.setEnabled(true);
            }

            Intent checkIntent = new Intent();
            checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
            startActivityForResult(checkIntent, 0);
            if (map.get("img") == null)
                Image.setImageResource(R.drawable.noimage);
            else
                Image.setImageDrawable(Drawable.createFromPath(map.get("img")));

            if(Float.parseFloat(map.get("note_moyenne"))== 5)//img 5
                notemoyenne.setImageResource(R.drawable.etoile_5);
            else if (Float.parseFloat(map.get("note_moyenne"))<5 && Float.parseFloat(map.get("note_moyenne")) > 4)//img 4.5
                notemoyenne.setImageResource(R.drawable.etoile_4_5);
            else if (Float.parseFloat(map.get("note_moyenne")) == 4)//img 4
                notemoyenne.setImageResource(R.drawable.etoile_4);
            else if (Float.parseFloat(map.get("note_moyenne"))<4 && Float.parseFloat(map.get("note_moyenne")) > 3)//img 3.5
                notemoyenne.setImageResource(R.drawable.etoile_3_5);
            else if (Float.parseFloat(map.get("note_moyenne")) == 3)//img 3
                notemoyenne.setImageResource(R.drawable.etoile_3);
            else if (Float.parseFloat(map.get("note_moyenne"))<3 && Float.parseFloat(map.get("note_moyenne")) > 2)//img 2.5
                notemoyenne.setImageResource(R.drawable.etoile_2_5);
            else if (Float.parseFloat(map.get("note_moyenne")) == 2)//img 2
                notemoyenne.setImageResource(R.drawable.etoile_2);
            else if (Float.parseFloat(map.get("note_moyenne"))<2 && Float.parseFloat(map.get("note_moyenne")) > 1)//img 1.5
                notemoyenne.setImageResource(R.drawable.etoile_1_5);
            else if (Float.parseFloat(map.get("note_moyenne")) == 1)//img 1
                notemoyenne.setImageResource(R.drawable.etoile_1);
            else if (Float.parseFloat(map.get("note_moyenne"))<1 && Float.parseFloat(map.get("note_moyenne")) > 0)//img 0.5
                notemoyenne.setImageResource(R.drawable.etoile_0_5);
            //sinon img 0
        }
        if(msg.what == 1)
        {
            // Erreur : réseau ou autre
            mProgressDialog.dismiss();
            AlertDialog.Builder adb=new AlertDialog.Builder(mContext);
            adb.setTitle("Erreur");
            adb.setMessage("Impossible de comuniquer avec le serveur!");
            adb.setPositiveButton("Ok", null);
            adb.show();
        }
    };
};

Upvotes: 1

Views: 802

Answers (2)

ajacian81
ajacian81

Reputation: 7589

Storing the result using a Sqlite db is a great idea. As for checking whether or not the data has changed, there's a few ways you can do it - you can add on the server side a Last-Modified header that can include the time the results last changed. If the Last-Modified time is the same as when you last got the JSON request (which you can check in your Sqlite DB), then no need to download the body of the request.

Another way you can do it, if you don't want to keep track of timestamps (although that is the best method), is to keep track of MD5 hashes, or SHA1, or whatever is least resource heavy. Then you can put the hash in an HTTP header, and if the hash matches with what you stored in the Sqlite db, then no need to download the content. This would only be useful with a larger amount of JSON data that will be going across the network, since there is a cost to doing encryption on the server side (both in terms of time and resources).

Upvotes: 1

David Scott
David Scott

Reputation: 1666

I would save the data in an Sqlite db when you download it. Then you can manipulate it how you like, update certain rows etc.

Upvotes: 1

Related Questions