为什么当AsyncTask执行应用程序总是强制停止?

时间:2016-07-15 08:40:40

标签: android

为什么AsyncTask执行应用程序总是强制停止? 有2个结果,首先是AsyncTask success access将强制停止的网址,如果failed to access网址将显示错误且不强制停止。

这是我的代码:

private void insertToDatabase(final String alamat) {

   class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
     @Override
     protected void onPreExecute() {
       myProgressDialog = new ProgressDialog(MainActivity.this);
       myProgressDialog.setIndeterminate(true);
       myProgressDialog.setMessage("Loading...");
       myProgressDialog.setCancelable(true);
       myProgressDialog.show();
     }

     @Override
     protected String doInBackground(String... params) {
       String text = null;
       String urlATM = alamat;
       try {
         JSONArray data = new JSONArray(getJSONUrl(urlATM));
         if(data.length()!=0){
           HashMap<String, String> map;

           for (int i = 0; i < data.length(); i++) {
             JSONObject c = data.getJSONObject(i);
             map = new HashMap<String, String>();
             map.put("id_atm", c.getString("id_atm"));
             map.put("id_bank", c.getString("id_bank"));
             map.put("nama_bank", c.getString("nama_bank"));
             map.put("latitude", c.getString("latitude"));
             map.put("longitude", c.getString("longitude"));
             map.put("name", c.getString("name"));
             map.put("email", c.getString("email"));
             MyArrListATM.add(map);
             //end add marker

             maps.addMarker(new MarkerOptions()
                    .title("ATM"+MyArrListATM.get(i)
                    .get("nama_bank"))
                    .snippet("24 Jam")
                    .position(new LatLng(
                           Double.parseDouble(MyArrListATM.get(i).get("latitude")),
                           Double.parseDouble(MyArrListATM.get(i).get("longitude")))));
           }
           myProgressDialog.dismiss();
         }
       } catch (JSONException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();

         text = e.getMessage();
       }
       //
       return text;
     }

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

       AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
       alertDialog.setTitle("PERINGATAN");
       alertDialog.setMessage("Error: "+result);
       alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "TUTUP", new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
          }
       });

       alertDialog.show();
     }
   }
   SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
   sendPostReqAsyncTask.execute(alamat);
}

并显示此代码的错误:

sendPostReqAsyncTask.execute(alamat);
我做错了什么?

logcat的:

07-15 15:33:53.196 19175-23224/com.emergency.e_place E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #4
                                                                       Process: com.emergency.e_place, PID: 19175
                                                                       java.lang.RuntimeException: An error occured while executing doInBackground()
                                                                           at android.os.AsyncTask$3.done(AsyncTask.java:300)
                                                                           at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
                                                                           at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
                                                                           at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                                                                           at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
                                                                           at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
                                                                           at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
                                                                           at java.lang.Thread.run(Thread.java:841)
                                                                        Caused by: java.lang.IllegalStateException: Not on the main thread
                                                                           at maps.f.g.b(Unknown Source)
                                                                           at maps.z.F.a(Unknown Source)
                                                                           at maps.af.t.a(Unknown Source)
                                                                           at vl.onTransact(:com.google.android.gms.DynamiteModulesB:167)
                                                                           at android.os.Binder.transact(Binder.java:361)
                                                                           at com.google.android.gms.maps.internal.IGoogleMapDelegate$zza$zza.addMarker(Unknown Source)
                                                                           at com.google.android.gms.maps.GoogleMap.addMarker(Unknown Source)
                                                                           at com.emergency.e_place.MainActivity$1SendPostReqAsyncTask.doInBackground(MainActivity.java:584)
                                                                           at com.emergency.e_place.MainActivity$1SendPostReqAsyncTask.doInBackground(MainActivity.java:552)
                                                                           at android.os.AsyncTask$2.call(AsyncTask.java:288)
                                                                           at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                           at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
                                                                           at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
                                                                           at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
                                                                           at java.lang.Thread.run(Thread.java:841) 
07-15 15:33:54.606 19175-19175/com.emergency.e_place E/WindowManager: android.view.WindowLeaked: Activity com.emergency.e_place.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41a95858 V.E..... R......D 0,0-471,144} that was originally added here
                                                                          at android.view.ViewRootImpl.<init>(ViewRootImpl.java:451)
                                                                          at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:267)
                                                                          at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
                                                                          at android.app.Dialog.show(Dialog.java:289)
                                                                          at com.emergency.e_place.MainActivity$1SendPostReqAsyncTask.onPreExecute(MainActivity.java:559)
                                                                          at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
                                                                          at android.os.AsyncTask.execute(AsyncTask.java:535)
                                                                          at com.emergency.e_place.MainActivity.insertToDatabase(MainActivity.java:629)
                                                                          at com.emergency.e_place.MainActivity.access$1000(MainActivity.java:77)
                                                                          at com.emergency.e_place.MainActivity$17.onNavigationItemSelected(MainActivity.java:961)
                                                                          at android.support.design.widget.NavigationView$1.onMenuItemSelected(NavigationView.java:136)
                                                                          at android.support.v7.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:811)
                                                                          at android.support.v7.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:153)
                                                                          at android.support.v7.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:958)
                                                                          at android.support.design.internal.NavigationMenuPresenter.onItemClick(NavigationMenuPresenter.java:187)
                                                                          at android.widget.AdapterView.performItemClick(AdapterView.java:308)
                                                                          at android.widget.AbsListView.performItemClick(AbsListView.java:1510)
                                                                          at android.widget.AbsListView$PerformClick.run(AbsListView.java:3472)
                                                                          at android.widget.AbsListView$3.run(AbsListView.java:4835)
                                                                          at android.os.Handler.handleCallback(Handler.java:733)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                          at android.os.Looper.loop(Looper.java:146)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:5511)
                                                                          at java.lang.reflect.Method.invokeNative(Native Method)
                                                                          at java.lang.reflect.Method.invoke(Method.java:515)
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
                                                                          at dalvik.system.NativeStart.main(Native Method)

2 个答案:

答案 0 :(得分:3)

在UI线程上

map.addMarkerdismiss dialog或用户界面的任何更改必须

  

doInBackground(Params ...),在后台线程上调用

因此,您应该删除myProgressDialog.dismiss();中的doInBackground 并将maps.addMarker...移至onPostExecute(Result)onProgressUpdate(Progress...)(因为在UI线程上调用了onPostExecuteonProgressUpdate

protected String doInBackground(String... params) {
   ...
   //end add marker
   MarkerOptions markerOptions = new MarkerOptions().title()....;
   onProgressUpdate(markerOptions)
}
protected void onProgressUpdate(MarkerOptions... values) {
   maps.addMarker(values);
}
protected void onPostExecute(String result) {
   // or you can add all markers to maps in here
} 

答案 1 :(得分:0)

您无法在后台线程中访问maps。您可以使用publishProgress并使用onProgressUpdate方法处理它。