从sdcard解析JSON - GSON

时间:2013-08-25 21:23:35

标签: android json android-layout android-intent gson

您好我基于this tutorial从http服务器创建了解析JSON。但我想从sdcard解析这个JSON文件。我可以使用Environment.getExternalStorageDirectory()。getAbsolutePath()打印json文件位置,但我不知道如何更改AsyncTask读取文件。有人可以帮我做这些东西吗? (我是Android开发的新手) 代码如下所示:

public class ClientActivity extends Activity {

    TextView capitalTextView;
    ProgressDialog progressDialog;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);    
        setContentView(R.layout.main1);
        capitalTextView = (TextView) findViewById(R.id.capital_textview);

        this.retrieveCapitals();
    }

    void retrieveCapitals() {

        progressDialog = ProgressDialog.show(this,
                "Please wait...", "Retrieving data...", true, true);

        CapitalsRetrieverAsyncTask task = new CapitalsRetrieverAsyncTask();
        task.execute();
        progressDialog.setOnCancelListener(new CancelListener(task));       
    }

    private class CapitalsRetrieverAsyncTask extends AsyncTask<Void, Void, Void> {

        Response response;

        @Override
        protected Void doInBackground(Void... params) {
            String url = "http://sample.com/sample_data.json";
            HttpGet getRequest = new HttpGet(url);

            File file = new File( Environment.getExternalStorageDirectory().getAbsolutePath() + "/example.json");
            System.out.println(file);

            try {
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpResponse getResponse = httpClient.execute(getRequest);
                final int statusCode = getResponse.getStatusLine().getStatusCode();

                if (statusCode != HttpStatus.SC_OK) { 
                    Log.w(getClass().getSimpleName(), "Error " + statusCode + " for URL " + url); 
                    return null;
                }

                HttpEntity getResponseEntity = getResponse.getEntity();
                InputStream httpResponseStream = getResponseEntity.getContent();
                Reader inputStreamReader = new InputStreamReader(httpResponseStream);

                Gson gson = new Gson();
                this.response = gson.fromJson(inputStreamReader, Response.class);
                System.out.println(this.response);
            } 
            catch (IOException e) {
                getRequest.abort();
                Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            StringBuilder builder = new StringBuilder();
            for (Shop shop : this.response.shops) {

                builder.append(String.format("<br>ID: <b>%s</b><br>Shop: <b>%s</b><br>Description: <b>%s</b><br><br>", shop.getId(), shop.getName(), shop.getDescription()));

            }

            capitalTextView.setText(Html.fromHtml(builder.toString()));
            progressDialog.cancel();
        }

    }

    private class CancelListener implements OnCancelListener {

        AsyncTask<?, ?, ?> cancellableTask;

        public CancelListener(AsyncTask<?, ?, ?> task) {
            cancellableTask = task;
        }

        @Override
        public void onCancel(DialogInterface dialog) {
            cancellableTask.cancel(true);
        }

    }

}

1 个答案:

答案 0 :(得分:0)

不要保存JSON文件。 JSON用于将值从一个地方传输到另一个地方。

相反,根据数据,您可以使用共享首选项或SQLite数据库来存储它。 看一下这个: http://developer.android.com/guide/topics/data/data-storage.html

然后您可以轻松检索并修改数据。