Since the HTTP request is time consuming, the best solution would be to use the async task. Otherwise, the main thread may cause errors. The class shown below can do asynchronous loading
private class jsonLoad extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... urls) { String response = ""; for (String url : urls) { DefaultHttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); try { HttpResponse execute = client.execute(httpGet); InputStream content = execute.getEntity().getContent(); BufferedReader buffer = new BufferedReader(new InputStreamReader(content)); String s = ""; while ((s = buffer.readLine()) != null) { response += s; } } catch (Exception e) { e.printStackTrace(); } } return response; } @Override protected void onPostExecute(String result) {
Unlike the other answer, here the loaded json string itself is saved in a file. So serialization is not needed Now loading json from url can be done by calling
jsonLoad jtask=new jsonLoad (); jtask.doInBackground("http:www.json.com/urJsonFile.json");
this will save the contents in a file. To open a saved json string
File file = new File(getApplicationContext().getFilesDir(),"nowList.cache"); StringBuilder text = new StringBuilder(); try { BufferedReader br = new BufferedReader(new FileReader(file)); String line; while ((line = br.readLine()) != null) { text.append(line); text.append('\n'); } br.close(); } catch (IOException e) { //print log } JSONObject jsonObject = new JSONObject(text);
source share