Android - 如何正确设置AsyncTask以从URL获取JSON数据?

时间:2014-03-06 23:22:13

标签: android android-asynctask

我有一个对象,contact,带有detailsURL String。在该URL处有一些JSON,其中包含有关我需要设置的联系人的更多信息。我试图这样做AsyncTask的方式是这样的:

    class detailDownloader extends AsyncTask<String, Void, Void> {
      String detail;
      private contact c;

      public detailDownloader(String detail, contact c) {
          this.c = c;
          this.detail = detail;
      }

      protected Void doInBackground(String... urls) {
          String url = urls[0];
          Log.d("contact", "1");
          String s;
          try {
            InputStream in = new java.net.URL(url).openStream();
              Log.d("contact", "2");
            BufferedReader br2 = null;
            br2 = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            StringBuilder sb2 = new StringBuilder();
              Log.d("contact", "3");
            while((s = br2.readLine()) != null) {
                sb2.append(s);
            }
            s = sb2.toString();
            JSONArray detail = new JSONArray(s);
            for(int j = 0; j < detail.length(); j++){
                JSONObject obj2 = detail.getJSONObject(j);
                boolean favorite = obj2.getBoolean("favorite");
                String email = obj2.getString("email");
                String largeURL = obj2.getString("largeImageURL");
                JSONObject address = obj2.getJSONObject("address");
                String street = address.getString("street");
                String city = address.getString("city");
                String state = address.getString("state");
                c.setFavorite(favorite);
                c.setLargeURL(largeURL);
                c.setEmail(email);
                c.setStreet(street);
                c.setCityState(city + ", " + state);
            }
            in.close();
          } catch (Exception e) {
              Log.e("Error", e.getMessage());
          }
        return null;
      }
}

detailDownloader由以下人员调用:       new detailDownloader(c.getDetailsURL(), c).execute();

但我在日志中收到回复:"03-06 16:30:24.724: I/Choreographer(29237): Skipped 370 frames! The application may be doing too much work on its main thread."

知道如何解决这个问题吗?

2 个答案:

答案 0 :(得分:0)

乍一看,这段代码对我来说很合适。你确定这个类导致了跳帧吗?你确定你没有在导致这个问题的主线程上做其他事吗?

您的detailsDownloader类是否实现onPreExecute或onPostExecute?如果是这样,您也应该发布这些方法的代码。

答案 1 :(得分:0)

此类错误通常是由于使用过多UI threads造成的,请查看this以获取更多信息。