如何删除 FATAL EXCEPTION: AsyncTask in android

how to remove FATAL EXCEPTION: AsyncTask in android(如何删除 FATAL EXCEPTION: AsyncTask in android)

本文介绍了如何删除 FATAL EXCEPTION: AsyncTask in android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

10-23 00:41:00.705: E/AndroidRuntime(3622): FATAL EXCEPTION: AsyncTask #1
10-23 00:41:00.705: E/AndroidRuntime(3622): java.lang.RuntimeException: An error occured while executing doInBackground()
10-23 00:41:00.705: E/AndroidRuntime(3622):     at android.os.AsyncTask$3.done(AsyncTask.java:299)
10-23 00:41:00.705: E/AndroidRuntime(3622):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
10-23 00:41:00.705: E/AndroidRuntime(3622):     at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
10-23 00:41:00.705: E/AndroidRuntime(3622):     at java.util.concurrent.FutureTask.run(FutureTask.java:239)
10-23 00:41:00.705: E/AndroidRuntime(3622):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
10-23 00:41:00.705: E/AndroidRuntime(3622):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
10-23 00:41:00.705: E/AndroidRuntime(3622):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
10-23 00:41:00.705: E/AndroidRuntime(3622):     at java.lang.Thread.run(Thread.java:856)
10-23 00:41:00.705: E/AndroidRuntime(3622): Caused by: java.lang.IllegalStateException: Content has been consumed
10-23 00:41:00.705: E/AndroidRuntime(3622):     at org.apache.http.entity.BasicHttpEntity.getContent(BasicHttpEntity.java:84)
10-23 00:41:00.705: E/AndroidRuntime(3622):     at org.apache.http.entity.BasicHttpEntity.writeTo(BasicHttpEntity.java:126)
10-23 00:41:00.705: E/AndroidRuntime(3622):     at org.apache.http.entity.HttpEntityWrapper.writeTo(HttpEntityWrapper.java:101)
10-23 00:41:00.705: E/AndroidRuntime(3622):     at org.apache.http.conn.BasicManagedEntity.writeTo(BasicManagedEntity.java:126)
10-23 00:41:00.705: E/AndroidRuntime(3622):     at com.firstgroup.webservice.RequestTask.doInBackground(RequestTask.java:51)
10-23 00:41:00.705: E/AndroidRuntime(3622):     at com.firstgroup.webservice.RequestTask.doInBackground(RequestTask.java:1)
10-23 00:41:00.705: E/AndroidRuntime(3622):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
10-23 00:41:00.705: E/AndroidRuntime(3622):     at java.util.concurrent.FutureTask.run(FutureTask.java:234)
10-23 00:41:00.705: E/AndroidRuntime(3622):     ... 4 more

我正在使用 gson 库调用我的 Web 服务,但出现异常.我不知道为什么会发生这种情况.您能告诉我删除此错误吗?我会给你我所做的步骤..1 )主要活动

I am calling my web service using gson library I am getting exception.I don't know why it is occur .could you please tell me removing this error I will give you steps what I did .. 1 )Main activity

public class Appliacationload extends Activity implements WebserviceCallBack{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.appliacationload);

        /*WebserviceMethod callDepartudeDashboard=new WebserviceMethod();
        callDepartudeDashboard.setObserver(this);
        callDepartudeDashboard.getwebService(ConstantVariable.dashboardWebServiceURL+"a/"+"arrival"+"?crsCode=hnh");*/
        RequestTask callWebService=new RequestTask();
        callWebService.setObserver(this);
         callWebService.execute(ConstantVariable.dashboardWebServiceURL+"a/"+"arrival"+"?crsCode=vic");



    }

    @Override
    public void getWebserviceResponse(String response) {
        // TODO Auto-generated method stub
        Log.d("response", response);



    }

}

我有一个持有者和 RequestTask 类来调用 web 服务并返回回调.

and I have one holder and RequestTask class to call webservice and return call back .

public class RequestTask extends AsyncTask<String, String, String>{
    private  WebserviceCallBack callBack;
    private ProgressDialog progressDialog;
    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        progressDialog= new ProgressDialog((Context) callBack);
        super.onPreExecute();
        progressDialog.setTitle("Please Wait...");
        progressDialog.setMessage("Webservice Call...");
        progressDialog.setCancelable(true);
        progressDialog.show();
    }

    @Override
    protected String doInBackground(String... uri) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response;
        String responseString = null;
        try {
            response = httpclient.execute(new HttpGet(uri[0]));
            StatusLine statusLine = response.getStatusLine();
            if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                Reader reader = new InputStreamReader(response.getEntity().getContent());
                Gson gson = new Gson();
                Holder response1 = gson.fromJson(reader, Holder.class);
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                response.getEntity().writeTo(out);
                out.close();
                responseString = out.toString();
            } else{
                //Closes the connection.
                response.getEntity().getContent().close();
                throw new IOException(statusLine.getReasonPhrase());
            }
        } catch (ClientProtocolException e) {
            //TODO Handle problems..
            progressDialog.hide();
        } catch (IOException e) {
            //TODO Handle problems..
            progressDialog.hide();
        }
        return responseString;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        //Do anything with response..
        if(callBack!=null){
            callBack.getWebserviceResponse(result);
        }
        progressDialog.hide();
    }
    public void setObserver(WebserviceCallBack callback){
        callBack=callback;
    }


}

持有人类;

public class Holder {
    List<deparaturedaseboarddto> data;
}

新更新当我像这样更改我的请求任务时..

New Update when I change my request task like that ..

public class RequestTask extends AsyncTask<String, String, InputStream>{
    private  WebserviceCallBack callBack;
    private ProgressDialog progressDialog;
    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        progressDialog= new ProgressDialog((Context) callBack);
        super.onPreExecute();
        progressDialog.setTitle("Please Wait...");
        progressDialog.setMessage("Webservice Call...");
        progressDialog.setCancelable(true);
        progressDialog.show();
    }

    @Override
    protected InputStream doInBackground(String... uri) {
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response;
        String responseString = null;
        try {
            response = httpclient.execute(new HttpGet(uri[0]));
            StatusLine statusLine = response.getStatusLine();
            if(statusLine.getStatusCode() == HttpStatus.SC_OK){
                /*Reader reader = new InputStreamReader(response.getEntity().getContent());
                Gson gson = new Gson();
                Holder response1 = gson.fromJson(reader, Holder.class);
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                response.getEntity().writeTo(out);
                out.close();
                responseString = out.toString();*/
                return response.getEntity().getContent();
            } else{
                //Closes the connection.
                response.getEntity().getContent().close();
                throw new IOException(statusLine.getReasonPhrase());
            }
        } catch (ClientProtocolException e) {
            //TODO Handle problems..
            progressDialog.hide();
        } catch (IOException e) {
            //TODO Handle problems..
            progressDialog.hide();
        }
        return null;
    }

    @Override
    protected void onPostExecute(InputStream result) {
        super.onPostExecute(result);
        //Do anything with response..

        if(callBack!=null){
            callBack.getWebserviceResponse(result);
        }
        progressDialog.dismiss();
        progressDialog=null;

    }
    public void setObserver(WebserviceCallBack callback){
        callBack=callback;
    }


}

然后回电就这样

public interface WebserviceCallBack {
    public void getWebserviceResponse(InputStream result);

}

主要活动像那样

public class Appliacationload extends Activity implements WebserviceCallBack{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.appliacationload);

        /*WebserviceMethod callDepartudeDashboard=new WebserviceMethod();
        callDepartudeDashboard.setObserver(this);
        callDepartudeDashboard.getwebService(ConstantVariable.dashboardWebServiceURL+"a/"+"arrival"+"?crsCode=hnh");*/
        RequestTask callWebService=new RequestTask();
          callWebService.setObserver(this);
         callWebService.execute(ConstantVariable.dashboardWebServiceURL+"a/"+"arrival"+"?crsCode=vic");



    }

    @Override
    public void getWebserviceResponse(InputStream result) {
        // TODO Auto-generated method stub
        Reader reader = new InputStreamReader(result);
      Gson gson = new Gson();
    Holder response1 = gson.fromJson(reader, Holder.class);
    Log.d("-----", "naveen");
    }

我得到这个异常为什么..?我在回调时发送输入流并在主要活动中制作这里..

I got this exception why ..?I am sending the input stream on call back and make here in main activity ..

例外:

10-23 03:07:33.956: E/AndroidRuntime(22412): FATAL EXCEPTION: main
10-23 03:07:33.956: E/AndroidRuntime(22412): android.os.NetworkOnMainThreadException
10-23 03:07:33.956: E/AndroidRuntime(22412):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
10-23 03:07:33.956: E/AndroidRuntime(22412):    at libcore.io.BlockGuardOs.recvfrom(BlockGuardOs.java:163)
10-23 03:07:33.956: E/AndroidRuntime(22412):    at libcore.io.IoBridge.recvfrom(IoBridge.java:513)
10-23 03:07:33.956: E/AndroidRuntime(22412):    at java.net.PlainSocketImpl.read(PlainSocketImpl.java:488)
10-23 03:07:33.956: E/AndroidRuntime(22412):    at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:46)
10-23 03:07:33.956: E/AndroidRuntime(22412):    at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:240)
10-23 03:07:33.956: E/AndroidRuntime(22412):    at org.apache.http.impl.io.AbstractSessionInputBuffer.fillBuffer(AbstractSessionInputBuffer.java:103)
10-23 03:07:33.956: E/AndroidRuntime(22412):    at org.apache.http.impl.io.AbstractSessionInputBuffer.read(AbstractSessionInputBuffer.java:134)
10-23 03:07:33.956: E/AndroidRuntime(22412):    at org.apache.http.impl.io.ChunkedInputStream.read(ChunkedInputStream.java:161)
10-23 03:07:33.956: E/AndroidRuntime(22412):    at org.apache.http.conn.EofSensorInputStream.read(EofSensorInputStream.java:159)
10-23 03:07:33.956: E/AndroidRuntime(22412):    at java.io.InputStreamReader.read(InputStreamReader.java:244)
10-23 03:07:33.956: E/AndroidRuntime(22412):    at com.google.gson.stream.JsonReader.fillBuffer(JsonReader.java:1298)
10-23 03:07:33.956: E/AndroidRuntime(22412):    at com.google.gson.stream.JsonReader.nextQuotedValue(JsonReader.java:1028)
10-23 03:07:33.956: E/AndroidRuntime(22412):    at com.google.gson.stream.JsonReader.nextName(JsonReader.java:796)
10-23 03:07:33.956: E/AndroidRuntime(22412):    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:178)
10-23 03:07:33.956: E/AndroidRuntime(22412):    at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:40)
10-23 03:07:33.956: E/AndroidRuntime(22412):    at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:81)
10-23 03:07:33.956: E/AndroidRuntime(22412):    at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:60)
10-23 03:07:33.956: E/AndroidRuntime(22412):    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:95)
10-23 03:07:33.956: E/AndroidRuntime(22412):    at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:183)
10-23 03:07:33.956: E/AndroidRuntime(22412):    at com.google.gson.Gson.fromJson(Gson.java:805)
10-23 03:07:33.956: E/AndroidRuntime(22412):    at com.google.gson.Gson.fromJson(Gson.java:743)
10-23 03:07:33.956: E/AndroidRuntime(22412):    at com.firstgroup.applicationload.Appliacationload.getWebserviceResponse(Appliacationload.java:48)
10-23 03:07:33.956: E/AndroidRuntime(22412):    at com.firstgroup.webservice.RequestTask.onPostExecute(RequestTask.java:77)
10-23 03:07:33.956: E/AndroidRuntime(22412):    at com.firstgroup.webservice.RequestTask.onPostExecute(RequestTask.java:1)
10-23 03:07:33.956: E/AndroidRuntime(22412):    at android.os.AsyncTask.finish(AsyncTask.java:631)
10-23 03:07:33.956: E/AndroidRuntime(22412):    at android.os.AsyncTask.access$600(AsyncTask.java:177)
10-23 03:07:33.956: E/AndroidRuntime(22412):    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
10-23 03:07:33.956: E/AndroidRuntime(22412):    at android.os.Handler.dispatchMessage(Handler.java:99)
10-23 03:07:33.956: E/AndroidRuntime(22412):    at android.os.Looper.loop(Looper.java:137)
10-23 03:07:33.956: E/AndroidRuntime(22412):    at android.app.ActivityThread.main(ActivityThread.java:5041)
10-23 03:07:33.956: E/AndroidRuntime(22412):    at java.lang.reflect.Method.invokeNative(Native Method)
10-23 03:07:33.956: E/AndroidRuntime(22412):    at java.lang.reflect.Method.invoke(Method.java:511)
10-23 03:07:33.956: E/AndroidRuntime(22412):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
10-23 03:07:33.956: E/AndroidRuntime(22412):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
10-23 03:07:33.956: E/AndroidRuntime(22412):    at dalvik.system.NativeStart.main(Native Method)

推荐答案

原因是你只能从 Entity 中消费 Content 一次.

The reason is you can only consume Content from Entity once.

你在这里做了两次(也许你不知道)

You did it twice (maybe without you knowing it) in here

Reader reader = new InputStreamReader(response.getEntity().getContent());

这里

response.getEntity().writeTo(out);

我知道这听起来有点奇怪,但实际上 writeTo() 函数将从实体中获取内容以写入 OutputStream.您可以在文档 here 中看到它

I know this is sounds a little weird but actually the writeTo() function will get content from the entity to write to the OutputStream. You can see it in the documentation here

您可以使用的另一种解决方法是将其转换为字符串并让 GSON 处理它

Another workaround you can use is turning it to string and let GSON handle it

@Override
protected String doInBackground(String... uri) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response;
    String responseString = null;
    try {
        response = httpclient.execute(new HttpGet(uri[0]));
        StatusLine statusLine = response.getStatusLine();
        if(statusLine.getStatusCode() == HttpStatus.SC_OK){
            responseString = EntityUtils.toString(response.getEntity()); // content will be consume only once
            Gson gson = new Gson();
            Holder response1 = gson.fromJson(responseString, Holder.class);
        } else{
            //Closes the connection.
            response.getEntity().getContent().close();
            throw new IOException(statusLine.getReasonPhrase());
        }
    } catch (ClientProtocolException e) {
        //TODO Handle problems..
        progressDialog.hide();
    } catch (IOException e) {
        //TODO Handle problems..
        progressDialog.hide();
    }
    return responseString;
}

希望我的回答能帮到你!

I hope my answer can help you!

这篇关于如何删除 FATAL EXCEPTION: AsyncTask in android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何删除 FATAL EXCEPTION: AsyncTask in android

基础教程推荐