1

我正在开发一个 android 应用程序,首先我将请求发送到 Web 服务并以 0 或 1 格式获取响应状态,如果我得到响应为 1 然后加载完整的 JSON 文件。我的问题是我想制作一个离线应用程序,我想从一个活动中下载 JSON 数据并在不同的活动中读取该数据,列表视图显示每个下载的 JSON 文件的标题。单击 listview 项后,将显示 JSON 数据。并且一些 JSON 数据项包含图像的 URL,我还想下载它们并在另一个活动中显示它们。我还想加密下载的 JSON 数据。请帮我。

作为参考,我附上了 JSON 文件格式。

imgWidth":""}}},{"OptionId":"246410","OptionDesc":{"1":{"text":"ETPM","image":"","imgHeight":"", "imgWidth":""}}}]},{"question_id":"61563","question":{"1":{"text":"以下五个中的四个在某些方面是相似的,因此形成一组。哪个不属于该组?","image":"","imgHeight":"","imgWidth":""}},"correct_ans":{"1":{"text" :"27","image":"","imgHeight":"","imgWidth":""}},"rightOption":[],"rightOptionID":"246414","rightOptionNo"

4

3 回答 3

2

你需要做这样的事情:

   private class PrepareMapTask extends AsyncTask<String, Integer, Boolean>
    {
        // Initialize with invalid value
        private int mPrepareResult = -1;
        private String mJsonString = null;

        protected Boolean doInBackground(String... urls)
        {
            mJsonString = downloadFileFromInternet(urls[0]);
            if(mJsonString == null /*|| mJsonString.isEmpty()*/)
                return false;

            JSONObject jObject = null;
            try {
                jObject = new JSONObject(mJsonString);
                JSONArray jsonImageArray = jObject.getJSONArray("imageTarget");
                JSONArray jsonUrlArray = jObject.getJSONArray("videoUrls");
                JSONArray jsonVideoOrUrlArray = jObject.getJSONArray("videoOrUrl");
                if (jsonImageArray == null || jsonUrlArray == null)
                    return false;
                for (int i = 0; i<jsonImageArray.length(); i++){ 
                    mapTargetUrl.put(jsonImageArray.get(i).toString(), jsonUrlArray.get(i).toString());
                    mVideoOrUrl.add(jsonVideoOrUrlArray.get(i).toString());
                }
            } catch (JSONException e) {
                e.printStackTrace();
                return false;
            }

            return true;
        }

        protected void onPostExecute(Boolean result)
        {
        }

        private String downloadFileFromInternet(String url)
        {
            if(url == null /*|| url.isEmpty() == true*/)
                new IllegalArgumentException("url is empty/null");
            StringBuilder sb = new StringBuilder();
            InputStream inStream = null;
            try
            {
                url = urlEncode(url);
                URL link = new URL(url);
                inStream = link.openStream();
                int i;
                int total = 0;
                byte[] buffer = new byte[8 * 1024];
                while((i=inStream.read(buffer)) != -1)
                {
                    if(total >= (1024 * 1024))
                    {
                        return "";
                    }
                    total += i;
                    sb.append(new String(buffer,0,i));
                }
            }catch(Exception e )
            {
                e.printStackTrace();
                return null;
            }catch(OutOfMemoryError e)
            {
                e.printStackTrace();
                return null;
            }
            return sb.toString();
        }

        private String urlEncode(String url)
        {
            if(url == null /*|| url.isEmpty() == true*/)
                return null;
            url = url.replace("[","");
            url = url.replace("]","");
            url = url.replaceAll(" ","%20");
            return url;
        }

    }

根据您的 json 获取数据结构并修改代码。

于 2013-08-19T09:28:49.310 回答
2

使用该链接中详述的解析器解析所有数据

http://www.androidhive.info/2012/01/android-json-parsing-tutorial/ 然后使用下面的方法将所有数据写入文件,这样你的数据就会被下载并保存为文件

public void appendData(String text)
{       
    File myFile = new File("sdcard/myfile.file");
    if (!myFile.exists())
    {
      try
      {
          myFile.createNewFile();
      } 
      catch (IOException e)
      {
          // TODO Auto-generated catch block
          e.printStackTrace();
      }
  }
  try
  {
      //BufferedWriter for performance, true to set append to file flag
      BufferedWriter buf = new BufferedWriter(new FileWriter(myFile, true)); 
      buf.append(text);
      buf.newLine();
      buf.close();
  }
  catch (IOException e)
  {
      // TODO Auto-generated catch block
      e.printStackTrace();
  }
}
于 2013-08-19T09:30:47.163 回答
0
try {

                  DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPostRequest = new HttpPost(URL);


        // Set HTTP parameters
        /*StringEntity se;
        se = new StringEntity(jsonObjSend.toString());*/
        jsonObjSend.length();

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(jsonObjSend.length());
        nameValuePairs.add(new BasicNameValuePair("data", jsonObjSend.toString()));
       // Log.i("jsonObjSend.toString()","jsonObjSend.toString()"+jsonObjSend.toString());

        Log.i("HTTPPOST","URL: "+URL);
        Log.i("HTTPPOST","Request: "+jsonObjSend.toString());
        UrlEncodedFormEntity en=new UrlEncodedFormEntity(nameValuePairs);
        en.getContent();
        httpPostRequest.getParams().setParameter("http.socket.timeout", new Integer(600000));
        httpPostRequest.setEntity(en);
        long t = System.currentTimeMillis();
        HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
        Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis()-t) + "ms]");
        Log.i(TAG, httpPostRequest.getRequestLine().getProtocolVersion().toString());
        responses = convertEntityToString(response.getEntity(), "UTF-8");
        Log.i("HTTPPOST","Responce: "+responses);
        Log.i("HTTPPOST","******************");
        //Log.i("Encoding",response.getEntity().getContentEncoding().getName());



                if (response.equalsIgnoreCase("")) {
                    webresponse = 1;
                } else {
                    webresponse = 0;
                }
            } catch (IOException e) {
                h.post(new Runnable() {

                    @Override
                    public void run() {
                        pd.dismiss();
                        AlertNullWebserviceResponce();

                    }
                });

                e.printStackTrace();
            }
于 2013-08-19T09:34:32.167 回答