将JSON数据存储在Android中的移动缓存内存中

时间:2015-07-27 07:25:40

标签: android json

我打开此页面并与服务器同步,并显示我从服务器返回的记录和数据。我想提高我的应用程序的性能。我是新手来缓存内存所以请帮助我或者给我一些其他的想法让我的应用更快。

class CreateNewProduct extends AsyncTask<String, String, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(Categry.this);
        pDialog.setMessage("Loading...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }
    protected String doInBackground(String... args) {

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        JSONObject json = jParser.makeHttpRequest(url_search, "GET", params);
        Log.d("Search idioms: ", json.toString());
        try {
// Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

             if (success == 1) {
// products found
// Getting Array of Products
            idioms = json.getJSONArray(TAG_IDIOMS);

// looping through All Products
            for (int i = 0; i < idioms.length(); i++) {
                JSONObject c = idioms.getJSONObject(i);

// Storing each json item in variable
                String id = c.getString(TAG_ID);
                String entry = c.getString(TAG_ENTRY);
                String meaning = c.getString(TAG_MEANING);

// creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
                map.put(TAG_ID, id);
                map.put(TAG_ENTRY, entry);
                map.put(TAG_MEANING, meaning);
// adding HashList to ArrayList
                idiomsList.add(map);
               }
            } else {
// no idioms found
//do something
                //tv1.setVisibility(View.VISIBLE);
                //Toast.makeText(getBaseContext(), "NO data found", Toast.LENGTH_LONG).show();
            }
        }
        /*catch(Exception e){
            Log.e("log_tag", "Error in http connection"+e.toString());
            Toast.makeText(getBaseContext(), "NO data found", Toast.LENGTH_LONG).show();
        }*/
        catch (JSONException e) {
            Log.e("log_tag", "Error in http connection" + e.toString());
            Toast.makeText(getBaseContext(), "NO data found", Toast.LENGTH_LONG).show();
        }
        return null;
    }

    protected void onPostExecute(String file_url) {


            pDialog.dismiss();
            runOnUiThread(new Runnable() {
                public void run() {
/**
 * Updating parsed JSON data into ListView
 * */
                    ListAdapter adapter = new SimpleAdapter(
                            Categry.this, idiomsList,
                            R.layout.activity_list_child, new String[]{TAG_ID, TAG_ENTRY, TAG_MEANING},
                            new int[]{R.id.id, R.id.entry, R.id.meaning});

                    lv.setAdapter(adapter);
                }
            });

        }

    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent(getBaseContext(), homescreen.class);

        startActivity(intent);
        finish();
        //   overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_categry, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
            case R.id.action_settings:
                Intent i = new Intent(getBaseContext(), qrcode.class);
                startActivity(i);
                return true;
            case android.R.id.home:
                Intent intent = new Intent(getBaseContext(), homescreen.class);
                startActivity(intent);
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

2 个答案:

答案 0 :(得分:0)

如果你已完整并完全处理json并使应用程序更流畅意味着使用名为Retrofit的库,它非常简单并且可以轻松地与您的json集成,那么您可以将其存储为json文件以供离线访问< / p>

答案 1 :(得分:0)

您可以使用以下代码将Json对象保存到缓存中...

          try {
                ObjectOutput out = new ObjectOutputStream(new FileOutputStream
                            (new File(getActivity().getCacheDir(), "") + File.separator + "cacheFile.srl"));
                    out.writeObject(jsonObj.toString());
                    out.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

如果你想从缓存中读取json对象,你可以使用下面的代码..

        try {
                ObjectInputStream in = new ObjectInputStream(new FileInputStream
                        (new File(getActivity().getCacheDir() + File.separator + "cacheFile.srl")));
                jsonObj = new JSONObject((String) in.readObject());
                in.close();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (OptionalDataException e) {
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (StreamCorruptedException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }