0

我的用户报告说,当他们使用 WiFi 下载 JSON 文件时,该应用程序就像魅力一样工作,但是当他们尝试使用他们的数据连接下载相同的文件时:GPRS、3G、3.5G 等......应用程序强制关闭。并非所有类型的智能手机都会发生这种情况,例如,我的 LG Optimus Black 不会发生这种情况。

为了检索这个文件,我使用了 AsyncTask。

private class GetData extends AsyncTask<Void, Void, Void> {
        protected Void doInBackground(Void... args) {

            DefaultHttpClient httpclient = new DefaultHttpClient();
            try {

                HttpGet httpget = new HttpGet("http://url.com);
                HttpResponse response = httpclient.execute(httpget);
                strPlayers = inputStreamToString(response.getEntity().getContent()).toString();
            }
            catch (IOException e) { e.printStackTrace(); } 
            finally { httpclient.getConnectionManager().shutdown(); }

           return null;
        }

        protected void onPostExecute(Void result) {

            Players players = new Gson().fromJson(strPlayers, Players.class);

            quantity_darkmatter.setText(String.valueOf(players.userName));

        }
    }

这是 StackTrace()

java.lang.RuntimeException: Unable to start activity ComponentInfo{carl.fri.fer.omegan/carl.fri.fer.omegan.Research}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1659)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1675)
at android.app.ActivityThread.access$1500(ActivityThread.java:121)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:943)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3701)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:624)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at carl.fri.fer.omegan.Research.onStart(Research.java:613)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1129)
at android.app.Activity.performStart(Activity.java:3791)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1632)
... 11 more

可能是什么问题?

4

1 回答 1

0

对于非WIFI,连接可能需要更多时间,因此可能是连接超时问题,发生这种情况时 strPlayers 将为空白,并且由于 onPostExecute 中没有错误处理,这可能会给 Gson.fromJson 打嗝并使其抛出异常...在尝试解析它或将其放入 try-catch 块之前尝试测试 strPlayers!=null 以查看它是否引发某种异常。

doInBackground 函数中是否有 e.printStackTrace() 的输出?

于 2012-04-23T10:51:41.197 回答