空指针AsyncTask的回报 [英] Nullpointer asynctask return

查看:284
本文介绍了空指针AsyncTask的回报的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图访​​问使用的AsyncTask A服务器上的文件,这是我的code:

 新PostTask()执行(http://antoniofalcone.it/fantavoti/gazz.csv);
@覆盖
保护字符串doInBackground(字符串... PARAMS){
   字符串URL =参数[0];    HTTPGET HTTPGET =新HTTPGET(URL);
    HTT presponse响应= NULL;
    尝试{
        响应= httpClient.execute(HTTPGET,localContext);
    }赶上(ClientProtocolException E){
        Log.d(clientprotocol,LOG2);
        e.printStackTrace();
    }赶上(IOException异常五){
        Log.d(IOException异常:,LOG2);
        e.printStackTrace();
    }    尝试{
        读者=新的BufferedReader(
                新的InputStreamReader(
                        response.getEntity()的getContent()
                        )
                );
    }赶上(IllegalStateException异常五){
        Log.d(非法状态:,LOG2);
        e.printStackTrace();
    }赶上(IOException异常五){
        Log.d(IOException2,LOG2);
        e.printStackTrace();
    }
   返回全部完成!
}@覆盖
保护无效onProgressUpdate(整数...值){
   super.onProgressUpdate(值);
}@覆盖
保护无效onPostExecute(字符串结果){
   super.onPostExecute(结果);
}
}

我要读的csv文件,但我得到一个 NullPointerException异常的BufferedReader(读者) 。在资产目录中的本地文件的工作它的罚款。
谁能帮我?

下面是完整的logcat:

  08-31 18:16:54.930:W / dalvikvm(2218):主题ID = 1:螺纹未捕获的异常退出(组= 0xa4ceeb20)
08-31 18:16:54.930:E / AndroidRuntime(2218):致命异常:主要
08-31 18:16:54.930:E / AndroidRuntime(2218):工艺:com.falc1.fantacalcio2,PID:2218
08-31 18:16:54.930:E / AndroidRuntime(2218):了java.lang.RuntimeException:无法启动活动ComponentInfo {com.falc1.fantacalcio2 / com.falc1.fantacalcio2.MainActivity}:显示java.lang.NullPointerException
08-31 18:16:54.930:E / AndroidRuntime(2218):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
08-31 18:16:54.930:E / AndroidRuntime(2218):在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
08-31 18:16:54.930:E / AndroidRuntime(2218):在android.app.ActivityThread.access $ 800(ActivityThread.java:135)
08-31 18:16:54.930:E / AndroidRuntime(2218):在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1196)
08-31 18:16:54.930:E / AndroidRuntime(2218):在android.os.Handler.dispatchMessage(Handler.java:102)
08-31 18:16:54.930:E / AndroidRuntime(2218):在android.os.Looper.loop(Looper.java:136)
08-31 18:16:54.930:E / AndroidRuntime(2218):在android.app.ActivityThread.main(ActivityThread.java:5017)
08-31 18:16:54.930:E / AndroidRuntime(2218):在java.lang.reflect.Method.invokeNative(本机方法)
08-31 18:16:54.930:E / AndroidRuntime(2218):在java.lang.reflect.Method.invoke(Method.java:515)
08-31 18:16:54.930:E / AndroidRuntime(2218):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:779)
08-31 18:16:54.930:E / AndroidRuntime(2218):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
08-31 18:16:54.930:E / AndroidRuntime(2218):在dalvik.system.NativeStart.main(本机方法)
08-31 18:16:54.930:E / AndroidRuntime(2218):因:显示java.lang.NullPointerException
08-31 18:16:54.930:E / AndroidRuntime(2218):在fragments.VotiFragment.readCsv(VotiFragment.java:178)
08-31 18:16:54.930:E / AndroidRuntime(2218):在fragments.VotiFragment.onCreateView(VotiFragment.java:75)
08-31 18:16:54.930:E / AndroidRuntime(2218):在android.app.Fragment.performCreateView(Fragment.java:1700)
08-31 18:16:54.930:E / AndroidRuntime(2218):在android.app.FragmentManagerImpl.moveToState(FragmentManager.java:890)
08-31 18:16:54.930:E / AndroidRuntime(2218):在android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
08-31 18:16:54.930:E / AndroidRuntime(2218):在android.app.BackStackRecord.run(BackStackRecord.java:684)
08-31 18:16:54.930:E / AndroidRuntime(2218):在android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1447)
08-31 18:16:54.930:E / AndroidRuntime(2218):在android.app.Activity.performStart(Activity.java:5240)
08-31 18:16:54.930:E / AndroidRuntime(2218):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2168)
08-31 18:16:54.930:E / AndroidRuntime(2218):11 ...更多


解决方案

语句, =响应httpClient.execute(HTTPGET,localContext); 正确被try包裹/ catch块,但如果抛出一个异常(如情况下,当服务器无法访问,不正确的URL,或者网络出现故障),那么catch块只打印例外和继续在。这意味着随后的语句:

读者=新的BufferedReader(
                新的InputStreamReader(
                        response.getEntity()的getContent()
                        )

将创下一个空指针异常,因为响应为空。对于httpClient.execute声明你的catch块应该只是收益打印出错误异常后。更好的办法是将刚一组尝试catch块为请求和响应解析两者。类似如下:

 的Htt presponse响应= NULL;
尝试{
    HTTPGET HTTPGET =新HTTPGET(URL);
    响应= httpClient.execute(HTTPGET,localContext);
    读者=新的BufferedReader(新的InputStreamReader(response.getEntity()的getContent()));
}赶上(IOException异常ioex){
    Log.d(TAG,IOException异常,ioex);
}赶上(ISE IllegalStateException异常){
    Log.d(TAGIllegalStateException异常,ISE);
}

由于日志语句可以与消息打印一个例外,我刚刚合并了你。你并不需要reduntant printStateTrace语句。由于ClientProtocolException从IOException异常继承,你只需要捕捉的基类。

和奖金,可以按如下方式让你的日志报表更加过滤通过在你的类声明TAG变量:

 公共静态最后弦乐TAG = VotiFragment.class.getSimpleName();

而现在,我完成了清理你的code,我才意识到你有另外一个问题。您的AsyncTask的整点是为了避免在主线程上做网络I / O。但所有的AsyncTask确实是开始HTTP请求,但不实际解析响应。它只是创建了读者对象,我presume你实际上从你的UI线程流。这意味着主线程上剩余的网络I / O,除非反应是完全缓冲。我会建议你做所有的分析在后台任务。

I am trying to access a file on a server using asynctask, this is my code:

new PostTask().execute("http://antoniofalcone.it/fantavoti/gazz.csv");
@Override
protected String doInBackground(String... params) {
   String url=params[0];

    HttpGet httpGet = new HttpGet(url);
    HttpResponse response = null;
    try {
        response = httpClient.execute(httpGet, localContext);
    } catch (ClientProtocolException e) {
        Log.d("clientprotocol", log2);
        e.printStackTrace();
    } catch (IOException e) {
        Log.d("IOexception: ", log2);
        e.printStackTrace();
    }

    try {
        reader = new BufferedReader(
                new InputStreamReader(
                        response.getEntity().getContent()
                        )
                );
    } catch (IllegalStateException e) {
        Log.d("Illegalstate: ", log2);
        e.printStackTrace();
    } catch (IOException e) {
        Log.d("IOException2 ", log2);
        e.printStackTrace();
    }
   return "All Done!";
}

@Override
protected void onProgressUpdate(Integer... values) {
   super.onProgressUpdate(values);
}

@Override
protected void onPostExecute(String result) {
   super.onPostExecute(result);
}
}

I have to read that csv file, but i get a Nullpointerexception on the BufferedReader ("reader"). Working on a local file in assets directory it's fine. Can anyone help me?

Here is the full logcat:

08-31 18:16:54.930: W/dalvikvm(2218): threadid=1: thread exiting with uncaught exception (group=0xa4ceeb20)
08-31 18:16:54.930: E/AndroidRuntime(2218): FATAL EXCEPTION: main
08-31 18:16:54.930: E/AndroidRuntime(2218): Process: com.falc1.fantacalcio2, PID: 2218
08-31 18:16:54.930: E/AndroidRuntime(2218): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.falc1.fantacalcio2/com.falc1.fantacalcio2.MainActivity}: java.lang.NullPointerException
08-31 18:16:54.930: E/AndroidRuntime(2218):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
08-31 18:16:54.930: E/AndroidRuntime(2218):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
08-31 18:16:54.930: E/AndroidRuntime(2218):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
08-31 18:16:54.930: E/AndroidRuntime(2218):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
08-31 18:16:54.930: E/AndroidRuntime(2218):     at android.os.Handler.dispatchMessage(Handler.java:102)
08-31 18:16:54.930: E/AndroidRuntime(2218):     at android.os.Looper.loop(Looper.java:136)
08-31 18:16:54.930: E/AndroidRuntime(2218):     at android.app.ActivityThread.main(ActivityThread.java:5017)
08-31 18:16:54.930: E/AndroidRuntime(2218):     at java.lang.reflect.Method.invokeNative(Native Method)
08-31 18:16:54.930: E/AndroidRuntime(2218):     at java.lang.reflect.Method.invoke(Method.java:515)
08-31 18:16:54.930: E/AndroidRuntime(2218):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
08-31 18:16:54.930: E/AndroidRuntime(2218):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
08-31 18:16:54.930: E/AndroidRuntime(2218):     at dalvik.system.NativeStart.main(Native Method)
08-31 18:16:54.930: E/AndroidRuntime(2218): Caused by: java.lang.NullPointerException
08-31 18:16:54.930: E/AndroidRuntime(2218):     at fragments.VotiFragment.readCsv(VotiFragment.java:178)
08-31 18:16:54.930: E/AndroidRuntime(2218):     at fragments.VotiFragment.onCreateView(VotiFragment.java:75)
08-31 18:16:54.930: E/AndroidRuntime(2218):     at android.app.Fragment.performCreateView(Fragment.java:1700)
08-31 18:16:54.930: E/AndroidRuntime(2218):     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:890)
08-31 18:16:54.930: E/AndroidRuntime(2218):     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
08-31 18:16:54.930: E/AndroidRuntime(2218):     at android.app.BackStackRecord.run(BackStackRecord.java:684)
08-31 18:16:54.930: E/AndroidRuntime(2218):     at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1447)
08-31 18:16:54.930: E/AndroidRuntime(2218):     at android.app.Activity.performStart(Activity.java:5240)
08-31 18:16:54.930: E/AndroidRuntime(2218):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2168)
08-31 18:16:54.930: E/AndroidRuntime(2218):     ... 11 more

解决方案

The statement, response = httpClient.execute(httpGet, localContext); is properly wrapped by a try/catch block, but if an exception is thrown (such as the case when the server is unreachable, incorrect URL, or the network is down), then the catch blocks just print the exception and continues on. That means the subsequent statement:

reader = new BufferedReader( new InputStreamReader( response.getEntity().getContent() )

Will hit a null pointer exception because response is null. Your catch blocks for the httpClient.execute statement should just return after printing out the error exception. A better approach would be have just one set of try catch blocks for both the request and response parsing. Something like the following:

HttpResponse response = null;
try {
    HttpGet httpGet = new HttpGet(url);
    response = httpClient.execute(httpGet, localContext);
    reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
} catch (IOException ioex) {
    Log.d(TAG, "IOException", ioex);
} catch (IllegalStateException ise) {
    Log.d(TAG, "IllegalStateException", ise);
}

Since the log statements can print an exception with a message, I've just combined that for you. You don't need the reduntant printStateTrace statements. Since ClientProtocolException inherits from IOException, you just need to catch the base class.

And for bonus, you can make your log statements more filterable by declaring a "TAG" variable in your class as follows:

public static final String TAG = VotiFragment.class.getSimpleName();

And now that I'm done cleaning up your code, I just realized another issue you have. The whole point of your asynctask is to avoid doing network I/O on the main thread. But all your asynctask does is starts the HTTP request, but doesn't actually parse the response. It just creates the reader object which I presume you actually stream from on your UI thread. That means the remaining network i/o on the main thread unless the response was fully buffered. I would advise that you do all the parsing in the background task.

这篇关于空指针AsyncTask的回报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆