【问题标题】:AsyncTask doInBackground returning a nullpointerexception when internet connection is failed互联网连接失败时,AsyncTask doInBackground 返回空指针异常
【发布时间】:2014-01-06 18:00:43
【问题描述】:

DomenK 进行连接检查后,我遇到了下一个错误,我的 try catch 块如下所示:

try
            {
               if (isNetworkAvailable(getApplicationContext()))
                  updateJSONdata();
            }
            catch (Exception ex)
            {
               Toast.makeText(getApplicationContext(), "shit happens", Toast.LENGTH_SHORT).show();
               finish();
            }

01-06 19:24:41.221: E/AndroidRuntime(2174): FATAL EXCEPTION: main
01-06 19:24:41.221: E/AndroidRuntime(2174): java.lang.NullPointerException
01-06 19:24:41.221: E/AndroidRuntime(2174):     at com.flex.sklepik.ReadComments.updateList(ReadComments.java:253)
01-06 19:24:41.221: E/AndroidRuntime(2174):     at com.flex.sklepik.ReadComments$LoadComments.onPostExecute(ReadComments.java:317)
01-06 19:24:41.221: E/AndroidRuntime(2174):     at com.flex.sklepik.ReadComments$LoadComments.onPostExecute(ReadComments.java:1)
01-06 19:24:41.221: E/AndroidRuntime(2174):     at android.os.AsyncTask.finish(AsyncTask.java:417)
01-06 19:24:41.221: E/AndroidRuntime(2174):     at android.os.AsyncTask.access$300(AsyncTask.java:127)
01-06 19:24:41.221: E/AndroidRuntime(2174):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
01-06 19:24:41.221: E/AndroidRuntime(2174):     at android.os.Handler.dispatchMessage(Handler.java:99)
01-06 19:24:41.221: E/AndroidRuntime(2174):     at android.os.Looper.loop(Looper.java:130)
01-06 19:24:41.221: E/AndroidRuntime(2174):     at android.app.ActivityThread.main(ActivityThread.java:3701)
01-06 19:24:41.221: E/AndroidRuntime(2174):     at java.lang.reflect.Method.invokeNative(Native Method)
01-06 19:24:41.221: E/AndroidRuntime(2174):     at java.lang.reflect.Method.invoke(Method.java:507)
01-06 19:24:41.221: E/AndroidRuntime(2174):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
01-06 19:24:41.221: E/AndroidRuntime(2174):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:624)
01-06 19:24:41.221: E/AndroidRuntime(2174):     at dalvik.system.NativeStart.main(Native Method)

我的应用运行良好,但是当异步运行时互联网连接中断时,我的应用会死机。下面是我的 logcat 和异步代码块。也许有人可以帮助我如何制作 try catch 块或检测互联网连接问题、取消下一项工作、自动返回到第一个活动并吐司有关互联网连接问题的简单信息。

异步任务

public class LoadComments extends AsyncTask<Void, Void, Boolean> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(ReadComments.this);
            pDialog.setMessage("ŁADUJĘ LISTĘ SKLEPÓW");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
            wczytajMape();
            idzDoPolozenia(52.249665, 21.012511, 10);
        }

        @Override
        protected Boolean doInBackground(Void... arg0) {
            // we will develop this method in version 2

                updateJSONdata();


            return null;

        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            pDialog.dismiss();
            // we will develop this method in version 2
            updateList();
            ustawMape();
            mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        }

    }

堆栈跟踪:

01-06 18:52:14.583: E/AndroidRuntime(32139): FATAL EXCEPTION: AsyncTask #1
01-06 18:52:14.583: E/AndroidRuntime(32139): java.lang.RuntimeException: An error occured while executing doInBackground()
01-06 18:52:14.583: E/AndroidRuntime(32139):    at android.os.AsyncTask$3.done(AsyncTask.java:200)
01-06 18:52:14.583: E/AndroidRuntime(32139):    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
01-06 18:52:14.583: E/AndroidRuntime(32139):    at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
01-06 18:52:14.583: E/AndroidRuntime(32139):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
01-06 18:52:14.583: E/AndroidRuntime(32139):    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
01-06 18:52:14.583: E/AndroidRuntime(32139):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
01-06 18:52:14.583: E/AndroidRuntime(32139):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
01-06 18:52:14.583: E/AndroidRuntime(32139):    at java.lang.Thread.run(Thread.java:1019)
01-06 18:52:14.583: E/AndroidRuntime(32139): Caused by: java.lang.NullPointerException
01-06 18:52:14.583: E/AndroidRuntime(32139):    at com.flex.sklepik.ReadComments.updateJSONdata(ReadComments.java:195)
01-06 18:52:14.583: E/AndroidRuntime(32139):    at com.flex.sklepik.ReadComments$LoadComments.doInBackground(ReadComments.java:294)
01-06 18:52:14.583: E/AndroidRuntime(32139):    at com.flex.sklepik.ReadComments$LoadComments.doInBackground(ReadComments.java:1)
01-06 18:52:14.583: E/AndroidRuntime(32139):    at android.os.AsyncTask$2.call(AsyncTask.java:185)
01-06 18:52:14.583: E/AndroidRuntime(32139):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
01-06 18:52:14.583: E/AndroidRuntime(32139):    ... 4 more
01-06 18:52:14.793: W/ResourceType(32139): getEntry failing because entryIndex 13 is beyond type entryCount 2
01-06 18:52:14.793: W/ResourceType(32139): Failure getting entry for 0x7f0b000d (t=10 e=13) in package 0 (error -2147483647)
01-06 18:52:14.793: E/GooglePlayServicesUtil(32139): The Google Play services resources were not found. Check your project configuration to ensure that the resources are included.
01-06 18:52:14.813: W/ResourceType(32139): getEntry failing because entryIndex 13 is beyond type entryCount 2
01-06 18:52:14.823: W/ResourceType(32139): Failure getting entry for 0x7f0b000d (t=10 e=13) in package 0 (error -2147483647)
01-06 18:52:14.823: E/GooglePlayServicesUtil(32139): The Google Play services resources were not found. Check your project configuration to ensure that the resources are included.
01-06 18:52:15.173: W/Ads(32139): There was a problem getting an ad response. ErrorCode: 2
01-06 18:52:15.193: E/WindowManager(32139): Activity com.flex.sklepik.ReadComments has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@2afc3688 that was originally added here
01-06 18:52:15.193: E/WindowManager(32139): android.view.WindowLeaked: Activity com.flex.sklepik.ReadComments has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@2afc3688 that was originally added here
01-06 18:52:15.193: E/WindowManager(32139):     at android.view.ViewRoot.<init>(ViewRoot.java:267)
01-06 18:52:15.193: E/WindowManager(32139):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
01-06 18:52:15.193: E/WindowManager(32139):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
01-06 18:52:15.193: E/WindowManager(32139):     at android.view.Window$LocalWindowManager.addView(Window.java:424)
01-06 18:52:15.193: E/WindowManager(32139):     at android.app.Dialog.show(Dialog.java:241)
01-06 18:52:15.193: E/WindowManager(32139):     at com.flex.sklepik.ReadComments$LoadComments.onPreExecute(ReadComments.java:285)
01-06 18:52:15.193: E/WindowManager(32139):     at android.os.AsyncTask.execute(AsyncTask.java:391)
01-06 18:52:15.193: E/WindowManager(32139):     at com.flex.sklepik.ReadComments.onResume(ReadComments.java:147)
01-06 18:52:15.193: E/WindowManager(32139):     at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1150)
01-06 18:52:15.193: E/WindowManager(32139):     at android.app.Activity.performResume(Activity.java:3832)
01-06 18:52:15.193: E/WindowManager(32139):     at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2131)
01-06 18:52:15.193: E/WindowManager(32139):     at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2156)
01-06 18:52:15.193: E/WindowManager(32139):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1680)
01-06 18:52:15.193: E/WindowManager(32139):     at android.app.ActivityThread.access$1500(ActivityThread.java:121)
01-06 18:52:15.193: E/WindowManager(32139):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:943)
01-06 18:52:15.193: E/WindowManager(32139):     at android.os.Handler.dispatchMessage(Handler.java:99)
01-06 18:52:15.193: E/WindowManager(32139):     at android.os.Looper.loop(Looper.java:130)
01-06 18:52:15.193: E/WindowManager(32139):     at android.app.ActivityThread.main(ActivityThread.java:3701)
01-06 18:52:15.193: E/WindowManager(32139):     at java.lang.reflect.Method.invokeNative(Native Method)
01-06 18:52:15.193: E/WindowManager(32139):     at java.lang.reflect.Method.invoke(Method.java:507)
01-06 18:52:15.193: E/WindowManager(32139):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
01-06 18:52:15.193: E/WindowManager(32139):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:624)
01-06 18:52:15.193: E/WindowManager(32139):     at dalvik.system.NativeStart.main(Native Method)

【问题讨论】:

    标签: java android android-intent android-asynctask


    【解决方案1】:

    你必须在这里修复你的错误:

    01-06 18:52:14.583: E/AndroidRuntime(32139): Caused by: java.lang.NullPointerException
    01-06 18:52:14.583: E/AndroidRuntime(32139):    at com.flex.sklepik.ReadComments.updateJSONdata(ReadComments.java:195)
    

    检查您在行中引用的内容:ReadComments.java:195,并确保检查它是否为空指针。

    我假设您从服务器获取空字符串,记住检查连接状态是不够的,可能还有其他故障可能导致数据错误或为空。服务器可能已关闭、无法访问,或者 dns 可能已关闭,或者服务器可能返回 HTTP 错误,...。您必须处理所有这些情况。

    【讨论】:

      【解决方案2】:

      您可以使用以下功能检查互联网连接 -

      if(isInternetConnection(YourActivity.this){
           //do Internet Stuff
      }
      else{
           //No Network
      }
      
      
      public static boolean isInternetConnection(Context mContext) {
          final ConnectivityManager connMgr = (ConnectivityManager) mContext
                  .getSystemService(Context.CONNECTIVITY_SERVICE);
      
          final android.net.NetworkInfo wifi = connMgr
                  .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
      
          final android.net.NetworkInfo mobile = connMgr
                  .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
      
          if (wifi.isAvailable()
                  && wifi.getState() == NetworkInfo.State.CONNECTED) {
              return true;
          } else if (null!=mobile && mobile.isAvailable()
                  && mobile.getState() == NetworkInfo.State.CONNECTED) {
              return true;
          } else {
              return false;
          }
      }
      

      【讨论】:

      • 是的,我在第一个活动中得到了这个方法,它在启动应用程序之前检查连接,但是当用户打开第二个活动时,启动 AsyncTask 然后连接丢失我的应用程序失败。我不知道 AsyncTask 中的连接检测到底放在哪里。
      • 你需要包围 updateJSONdata();带有 try/catch 子句的函数,一旦收到 Null 指针异常,您需要取消 AsyncTask。
      • finish() 方法不应该取消 AsynsTask?
      • finish() 使您的 Activity 自行完成,取消 AsyncTask developer.android.com/reference/android/os/… 类似调用 - asynctaskInstance.cancel(true);此外,请注意@marcin_j 评论,他指出了真正的错误。你必须处理它。
      【解决方案3】:

      尝试捕获 updateJSONdata(); 在运行 AsyncTask 之前,请确保 Internet 工作正常。

      try{
                      updateJSONdata();
      
      } catch(Exception e){
      
      }
      

      【讨论】:

        【解决方案4】:

        不要忘记在 AndroidManifest.xml 上声明

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

        干杯!

        【讨论】:

          【解决方案5】:

          这个功能甚至比 Kanaks 更简单(用于检查 wifi/3g 状态)。

          public static boolean isNetworkAvailable(Context context)
          {
              ConnectivityManager connectivityManager = 
                  (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
              NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
          
              return activeNetworkInfo != null && activeNetworkInfo.isConnected();
          }
          

          但我们还没有在这里完成,因为我们可以获得 wifi/3g 信号但没有收到数据包。您需要使用 try/catch 语句与我提供的函数协作来捕获该异常。

          try
          {
             if (isNetworkAvailable(context)
                updateJSONData();
          }
          catch (Exception ex)
          {
             // Connection time out
          }
          

          【讨论】:

            猜你喜欢
            • 2012-02-18
            • 1970-01-01
            • 1970-01-01
            • 2014-05-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多