android - 获取 "FATAL EXCEPTION : AsyncTask #2"。我不知道是什么原因造成的

标签 android exception android-asynctask

在尝试调用 Web 服务并获取相应的 json 对象时,出现致命异常。我完全不知道去哪里查看以及要更正哪些错误。

[Screendump of the exception in question](http://i.imgur.com/EZcbW.png)

编辑:

    private class CallServiceTask extends AsyncTask<Object, Void, JSONObject>
{

    protected JSONObject doInBackground(Object... params) 
    {
        HttpGet req = (HttpGet) params[0];
        String url = (String) params[1];

        return executeRequest(req, url);
    }
}

这是在 doInBackground 中调用的 executeRequest 方法:

    private JSONObject executeRequest(HttpGet request, String url)
{
    HttpClient client = new DefaultHttpClient();
    JSONObject jsonObj = null;
    client = getNewHttpClient();

    HttpResponse httpResponse;

    try {
        httpResponse = client.execute(request);

        HttpEntity entity = httpResponse.getEntity();

        if (entity != null) {

            InputStream instream = entity.getContent();
            String response = convertStreamToString(instream);
            try {
                jsonObj = new JSONObject(response);
            } catch (JSONException e1) {
                e1.printStackTrace();
            }

            // Closing the input stream will trigger connection release
            instream.close();
        }

    } catch (ClientProtocolException e)  {
        client.getConnectionManager().shutdown();
        e.printStackTrace();
    } catch (IOException e) {
        client.getConnectionManager().shutdown();
        e.printStackTrace();
    }
    return jsonObj;
}

最佳答案

只需查看您的 LogCat 堆栈跟踪(在本例中),它就会告诉您所有您需要知道的有关此异常是什么以及导致它的原因:

thread exiting with uncaught exception

告诉您抛出了您的代码无法处理的异常

An error occurred while executing doInBackground()

这告诉您异步任务中的 doInBackground() 函数抛出了这个未处理的异常

Caused by: java.lang.ClassCastException ...HttpPost... (RestClient.java:275)

这告诉您遇到了 ClassCastException,这是源文件中第 275 行的 HttpPost 调用导致的。

编辑:

应该更仔细地阅读该堆栈跟踪...正如 HandlerExploit 发布的那样 抛出该错误的是 HttpPost,您期待的是 HttpGet...但以下调试方法仍然有效:

如果您使用 e.getMessage() 添加额外的捕获 (ClassCastException e),您很可能会看到一条有用的错误消息,其中更详细地描述了问题。

在这种情况下,当我发现像这样抛出意外异常时,我倾向于添加一个临时的“catch all”(catch (Exception e) { e.printStackTrace() } )并在 e 上设置一个断点。 printStackTrace() 这样我就可以看到有关异常的所有详细信息...可能不是最有效的方法,但它是您在黑暗中的一个开始!

关于android - 获取 "FATAL EXCEPTION : AsyncTask #2"。我不知道是什么原因造成的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9228501/

相关文章:

android - 如何在操作栏下方显示对话框?

android - 如何在单击按钮时滑动标签

web-services - 从 POST Web 服务报告错误

c# - 如何从父函数中捕获子过程异常?

带有包含 Button onClickListener 的 ListView 的 Android AsyncTask

android - 在android中触摸事件后启动字幕

Javascript:如何默认记录异常并继续执行?

android - 如何从获取 NPE 的 Android Activity 调用另一个 Activity AsyncTask 类

java - 声明中的Android AsyncTask错误

android - GeoLocation API 在移动设备上的安全性如何?