如何缓存JSON数据可脱机使用?缓存、数据、JSON

2023-09-04 23:48:07 作者:红尘烟雨碎相思

我已经在列表视图解析JSON数据,现在我想让它可脱机使用。 有没有一种方法来保存JSON数据的手机,让您可以看到的数据,如果你的手机是离线?

请问有人知道的例子吗?

编辑现在的工作:

 公共类MainActivity扩展ListActivity {


    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        新TheTask()执行()。
    }

    类TheTask扩展的AsyncTask<虚空,虚空,JSONArray> {
        InputStream的是= NULL;
        字符串结果=;
        JSONArray jArray = NULL;

        ProgressDialog PD;

        @覆盖
        保护无效onPostExecute(JSONArray结果){
            super.onPostExecute(结果);
            pd.dismiss();
            ArrayList的<字符串>名单=新的ArrayList<字符串>();
            尝试 {
                的for(int i = 0; I< result.length();我++){

                    JSONObject的JB = result.getJSONObject(我);
                    字符串名称= jb.getString(姓名)++ jb.getString(艺术);
                    list.add(名称);
                }
            }赶上(例外五){
                e.printStackTrace();
            }
            setListAdapter(新ArrayAdapter<字符串>(MainActivity.this,android.R.layout.simple_list_item_1,列表));
        }

        @覆盖
        在preExecute保护无效(){
            super.on preExecute();
            PD = ProgressDialog.show(MainActivity.this,国家,
                    载入中...,真正的);
        }

        @覆盖
        保护JSONArray doInBackground(虚空......为arg0){
            ConnectivityManager厘米=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

                尝试 {
                    HttpClient的HttpClient的=新DefaultHttpClient();
                    HttpPost httppost =新HttpPost(***);
                    HTT presponse响应= httpclient.execute(httppost);
                    HttpEntity实体= response.getEntity();
                    是= entity.getContent();
                }赶上(例外五){
                    Log.e(log_tag,错误的HTTP连接+ e.toString());
                }

                //转换响应串
                尝试 {
                    的BufferedReader读卡器=新的BufferedReader(新的InputStreamReader(
                            是,ISO-8859-1),8);
                    StringBuilder的SB =新的StringBuilder();
                    串线= NULL;
                    而((行= reader.readLine())!= NULL){
                        sb.append(行+\ N);
                    }
                    is.close();
                    结果= sb.toString();
                    将writeToFile(结果);
                }赶上(例外五){
                    Log.e(log_tag,错误转换结果+ e.toString());
                }

                尝试 {
                    jArray =新JSONArray(结果);
                }赶上(JSONException E){
                    Log.e(log_tag,错误分析数据+ e.toString());
                }

                尝试 {
                    jArray =新JSONArray(readFromFile());
                }赶上(JSONException E){
                    Log.e(log_tag,错误分析数据+ e.toString());
                }

            返回jArray;
        }
    }

    私人无效将writeToFile(字符串数据){
        尝试 {
            OutputStreamWriter outputStreamWriter =新OutputStreamWriter(openFileOutput(config.txt的,Context.MODE_PRIVATE));
            outputStreamWriter.write(数据);
            outputStreamWriter.close();
        }
        赶上(IOException异常E){
            Log.e(异常,文件写入失败:+ e.toString());
        }
    }

    私人字符串readFromFile(){

        字符串RET =;

        尝试 {
            InputStream中的InputStream = openFileInput(config.txt的);

            如果(的InputStream!= NULL){
                InputStreamReader的InputStreamReader的=新的InputStreamReader(InputStream的);
                BufferedReader中的BufferedReader =新的BufferedReader(InputStreamReader的);
                字符串receiveString =;
                StringBuilder的StringBuilder的=新的StringBuilder();

                而((receiveString = bufferedReader.readLine())!= NULL){
                    stringBuilder.append(receiveString);
                }

                inputStream.close();
                RET = stringBuilder.toString();
            }
        }赶上(FileNotFoundException异常E){
            Log.e(登录活动,找不到文件:+ e.toString());
        }赶上(IOException异常E){
            Log.e(登录活动,无法读取文件:+ e.toString());
        }

        返回RET;
    }
}
 

解决方案

您有两种方式。要么你创建一个数据库,并保存所有的数据也并检索它回来时,你想。或者,如果你拥有的数据并不多,你不希望处理的数据库,那么你写的JSON字符串到一个文本文件中的存储卡阅读后,当您处于脱机状态。

而对于第二种情况,你每次上网的时间,你可以从你的Web服务检索相同的JSON和超过写入到旧的。通过这种方式,你可以肯定的是,你必须保存到设备的最新JSON。

QQ音乐离线 缓存问题

I have parsed the JSON Data in a listview and now I want to make it available offline. Is there a way to save the JSON data at the phone so that you can see the data if your phone is offline?

Does someone knows an example?

EDIT works now:

 public class MainActivity extends ListActivity {


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new TheTask().execute();
    }

    class TheTask extends AsyncTask<Void, Void, JSONArray> {
        InputStream is = null;
        String result = "";
        JSONArray jArray = null;

        ProgressDialog pd;

        @Override
        protected void onPostExecute(JSONArray result) {
            super.onPostExecute(result);
            pd.dismiss();
            ArrayList<String> list= new ArrayList<String>();
            try {
                for(int i=0;i<result.length();i++) {

                    JSONObject jb = result.getJSONObject(i) ;
                    String name = jb.getString("name")+" "+jb.getString("Art");
                    list.add(name);
                }
            } catch(Exception e) {
                e.printStackTrace();
            }
            setListAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, list));
        }

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

        @Override
        protected JSONArray doInBackground(Void... arg0) {
            ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

                try {
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpPost httppost = new HttpPost("***");
                    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, "iso-8859-1"), 8);
                    StringBuilder sb = new StringBuilder();
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                    is.close();
                    result = sb.toString();
                    writeToFile(result);
                } catch (Exception e) {
                    Log.e("log_tag", "Error converting result " + e.toString());
                }

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

                try {
                    jArray = new JSONArray(readFromFile());
                } 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;
    }
}

解决方案

You have two ways. Either you create a database and save all of the data there and retrieve it back when you want to. Or if the data you have is not that much and you don't want to deal with databases, then you write the json string to a text file in the memory card and read it later when you are offline.

And for the second case, every time you go online, you can retrieve the same json from your web service and over write it to the old one. This way you can be sure that you have the latest json saved to the device.