ListFragment中的AsyncTask在获取响应时停止

时间:2014-05-31 21:41:10

标签: java android json android-fragments android-asynctask

我一直在测试一个服务,该服务返回一个JSON来加载Android上的列表。这一切都与ListActivity完美配合。

现在我正试图在ListFragment上实施同样的事情。我首先使用硬编码数据测试了它,如tutorial所示,它完全没有问题。当我添加AsyncTask以获取JSON数据以填充列表时,它在执行请求时一直崩溃。

这是AsyncTask代码:

public class CallService extends AsyncTask<Void, Void, String> {

    Response response;
    String result = "";
    ArrayList<Article> responseData = new ArrayList<Article>();

    @Override
    protected String doInBackground(Void... params) {
        String url = "[url]";

        HttpGet getRequest = new HttpGet(url);

        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            // crashes here
            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);
        } catch(IOException e) {
            getRequest.abort();
            Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
        }

        responseData = this.response.data;
        return result;
    }

    @Override
    protected void onPostExecute(String outputResult) {
        for(Article a : responseData) {
            articleList.add(a);
        }
        adapter.notifyDataSetChanged();
    }
}
}

我尝试了这个解决方案http://www.michenux.net/android-asynctask-in-fragment-best-pratices-725.html,建议:

  

asyncTask被声明为片段的成员。弱者   使用引用使得片段和异步任务松散   再加。如果您不使用弱引用,则不会执行异步任务   收集垃圾,因为片段保留了对它的引用。

但这并没有改变任何事情。

LogCat的错误:

05-31 18:22:32.280: D/dalvikvm(805): Not late-enabling CheckJNI (already on)
05-31 18:22:35.510: D/dalvikvm(805): GC_FOR_ALLOC freed 79K, 5% free 3146K/3296K, paused 108ms, total 109ms
05-31 18:22:35.520: I/dalvikvm-heap(805): Grow heap (frag case) to 4.211MB for 1127536-byte allocation
05-31 18:22:35.570: D/dalvikvm(805): GC_FOR_ALLOC freed 2K, 4% free 4244K/4400K, paused 42ms, total 42ms
05-31 18:22:36.150: D/gralloc_goldfish(805): Emulator without GPU emulation detected.
05-31 18:22:45.402: D/dalvikvm(805): GC_FOR_ALLOC freed 78K, 4% free 4598K/4744K, paused 36ms, total 38ms
05-31 18:22:45.512: D/dalvikvm(805): GC_FOR_ALLOC freed 12K, 3% free 4786K/4928K, paused 31ms, total 34ms
05-31 18:22:45.532: I/dalvikvm-heap(805): Grow heap (frag case) to 7.778MB for 3188752-byte allocation
05-31 18:22:45.562: D/dalvikvm(805): GC_FOR_ALLOC freed 1K, 2% free 7898K/8044K, paused 29ms, total 30ms
05-31 18:22:47.142: W/dalvikvm(805): threadid=12: thread exiting with uncaught exception (group=0xb1a96ba8)
05-31 18:22:47.172: E/AndroidRuntime(805): FATAL EXCEPTION: AsyncTask #1
05-31 18:22:47.172: E/AndroidRuntime(805): Process: info.androidhive.slidingmenu, PID: 805
05-31 18:22:47.172: E/AndroidRuntime(805): java.lang.RuntimeException: An error occured while executing doInBackground()
05-31 18:22:47.172: E/AndroidRuntime(805):  at android.os.AsyncTask$3.done(AsyncTask.java:300)
05-31 18:22:47.172: E/AndroidRuntime(805):  at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
05-31 18:22:47.172: E/AndroidRuntime(805):  at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
05-31 18:22:47.172: E/AndroidRuntime(805):  at java.util.concurrent.FutureTask.run(FutureTask.java:242)
05-31 18:22:47.172: E/AndroidRuntime(805):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
05-31 18:22:47.172: E/AndroidRuntime(805):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
05-31 18:22:47.172: E/AndroidRuntime(805):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
05-31 18:22:47.172: E/AndroidRuntime(805):  at java.lang.Thread.run(Thread.java:841)
05-31 18:22:47.172: E/AndroidRuntime(805): Caused by: java.lang.SecurityException: Permission denied (missing INTERNET permission?)
05-31 18:22:47.172: E/AndroidRuntime(805):  at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
05-31 18:22:47.172: E/AndroidRuntime(805):  at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
05-31 18:22:47.172: E/AndroidRuntime(805):  at java.net.InetAddress.getAllByName(InetAddress.java:214)
05-31 18:22:47.172: E/AndroidRuntime(805):  at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
05-31 18:22:47.172: E/AndroidRuntime(805):  at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
05-31 18:22:47.172: E/AndroidRuntime(805):  at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
05-31 18:22:47.172: E/AndroidRuntime(805):  at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
05-31 18:22:47.172: E/AndroidRuntime(805):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
05-31 18:22:47.172: E/AndroidRuntime(805):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
05-31 18:22:47.172: E/AndroidRuntime(805):  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
05-31 18:22:47.172: E/AndroidRuntime(805):  at info.androidhive.slidingmenu.FindPeopleFragment$CallService.doInBackground(FindPeopleFragment.java:96)
05-31 18:22:47.172: E/AndroidRuntime(805):  at info.androidhive.slidingmenu.FindPeopleFragment$CallService.doInBackground(FindPeopleFragment.java:1)
05-31 18:22:47.172: E/AndroidRuntime(805):  at android.os.AsyncTask$2.call(AsyncTask.java:288)
05-31 18:22:47.172: E/AndroidRuntime(805):  at java.util.concurrent.FutureTask.run(FutureTask.java:237)
05-31 18:22:47.172: E/AndroidRuntime(805):  ... 4 more
05-31 18:22:47.172: E/AndroidRuntime(805): Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)
05-31 18:22:47.172: E/AndroidRuntime(805):  at libcore.io.Posix.getaddrinfo(Native Method)
05-31 18:22:47.172: E/AndroidRuntime(805):  at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:61)
05-31 18:22:47.172: E/AndroidRuntime(805):  at java.net.InetAddress.lookupHostByName(InetAddress.java:405)
05-31 18:22:47.172: E/AndroidRuntime(805):  ... 17 more
05-31 18:22:47.172: E/AndroidRuntime(805): Caused by: libcore.io.ErrnoException: getaddrinfo failed: EACCES (Permission denied)
05-31 18:22:47.172: E/AndroidRuntime(805):  ... 20 more

1 个答案:

答案 0 :(得分:1)

您错过了清单文件中的互联网权限。只需添加

<uses-permission android:name="android.permission.INTERNET" />