Android AsyncTask give BadTokenException in Acti

2019-04-13 04:34发布

问题:

I want to download table's data in backgroud so i did using AsyncTask.The preoblem is When the button click it should start download.

I think there are some issues in button click function, because of I called another activity inise the onNextAction() & other Activity's onCreate() called AsyncTask, that time also I got same error. Its say LocalActivityManager didn't start

OR may be issue in : Its running inside the ActivityGroup...

Inside the ActivityGroup how to call AsyncTask?

Error place is

    @Override
    protected void onPreExecute() {
        this.dialog.setMessage("Downloading Table Data.......");
        this.dialog.show();
        myProgress = 0;
    }

Error is :

    08-22 10:22:18.935: ERROR/AndroidRuntime(448): FATAL EXCEPTION: main
08-22 10:22:18.935: ERROR/AndroidRuntime(448): java.lang.IllegalStateException: Could not execute method of the activity
08-22 10:22:18.935: ERROR/AndroidRuntime(448):     at android.view.View$1.onClick(View.java:2144)
08-22 10:22:18.935: ERROR/AndroidRuntime(448):     at android.view.View.performClick(View.java:2485)
08-22 10:22:18.935: ERROR/AndroidRuntime(448):     at android.view.View$PerformClick.run(View.java:9080)
08-22 10:22:18.935: ERROR/AndroidRuntime(448):     at android.os.Handler.handleCallback(Handler.java:587)
08-22 10:22:18.935: ERROR/AndroidRuntime(448):     at android.os.Handler.dispatchMessage(Handler.java:92)
08-22 10:22:18.935: ERROR/AndroidRuntime(448):     at android.os.Looper.loop(Looper.java:123)
08-22 10:22:18.935: ERROR/AndroidRuntime(448):     at android.app.ActivityThread.main(ActivityThread.java:3683)
08-22 10:22:18.935: ERROR/AndroidRuntime(448):     at java.lang.reflect.Method.invokeNative(Native Method)
08-22 10:22:18.935: ERROR/AndroidRuntime(448):     at java.lang.reflect.Method.invoke(Method.java:507)
08-22 10:22:18.935: ERROR/AndroidRuntime(448):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
08-22 10:22:18.935: ERROR/AndroidRuntime(448):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
08-22 10:22:18.935: ERROR/AndroidRuntime(448):     at dalvik.system.NativeStart.main(Native Method)
08-22 10:22:18.935: ERROR/AndroidRuntime(448): Caused by: java.lang.reflect.InvocationTargetException
08-22 10:22:18.935: ERROR/AndroidRuntime(448):     at java.lang.reflect.Method.invokeNative(Native Method)
08-22 10:22:18.935: ERROR/AndroidRuntime(448):     at java.lang.reflect.Method.invoke(Method.java:507)
08-22 10:22:18.935: ERROR/AndroidRuntime(448):     at android.view.View$1.onClick(View.java:2139)
08-22 10:22:18.935: ERROR/AndroidRuntime(448):     ... 11 more
08-22 10:22:18.935: ERROR/AndroidRuntime(448): Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token android.app.LocalActivityManager$LocalActivityRecord@4052e998 is not valid; is your activity running?
08-22 10:22:18.935: ERROR/AndroidRuntime(448):     at android.view.ViewRoot.setView(ViewRoot.java:527)
08-22 10:22:18.935: ERROR/AndroidRuntime(448):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
08-22 10:22:18.935: ERROR/AndroidRuntime(448):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
08-22 10:22:18.935: ERROR/AndroidRuntime(448):     at android.view.Window$LocalWindowManager.addView(Window.java:424)
08-22 10:22:18.935: ERROR/AndroidRuntime(448):     at android.app.Dialog.show(Dialog.java:241)
08-22 10:22:18.935: ERROR/AndroidRuntime(448):     at com.xont.controller.admin.ListRoutesActivity$DailyDownldAsyncTask.onPreExecute(ListRoutesActivity.java:515)
08-22 10:22:18.935: ERROR/AndroidRuntime(448):     at android.os.AsyncTask.execute(AsyncTask.java:391)
08-22 10:22:18.935: ERROR/AndroidRuntime(448):     at com.xont.controller.admin.ListRoutesActivity.onNextAction(ListRoutesActivity.java:139)

This is my full code for that activity;

   public class ListRoutesActivity extends Activity {
//variable declaration ....

// Service URL & methods
public static final String APPURL = "http://192.168.1.213:7986/XontService";
private static final String NAMESPACE = "http://tempuri.org/";
private static final String METHOD_TABLEDATA = "LoadDownLoadTablesDataJson";
private static String SOAP_ACTION1 = "http://tempuri.org/IXontService/LoadDownLoadTablesDataJson";

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.daily_download_route);

    SharedPreferences myPrefs = this.getSharedPreferences("myLogedPrefs",MODE_WORLD_READABLE);
    strBusinessUnit = myPrefs.getString("BusinessUnit", "");
    strExecutive = myPrefs.getString("Executive", "");
    strTerritoryCode = myPrefs.getString("TerritoryCode", "");

    tl = (TableLayout) findViewById(R.id.dailyDRoute);
    routeList = getSalesRoute();
    for (int i = 0; i < routeList.size(); i++) {
        TableRow tr = new TableRow(this);
        CheckBox ch = new CheckBox(this);
        ch.setHeight(1);
        ch.setId(i);
        TextView tv2 = new TextView(this);
        tr.addView(ch);
        tv2.setText(routeList.get(i).getDescription());
        tv2.setTextColor(Color.BLACK);
        ch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
                if(arg0.isChecked()){   
                    selectedRoutes.add(routeList.get(arg0.getId()).getRouteCode());
                }else {
                    selectedRoutes.remove(routeList.get(arg0.getId()));
                }
            }
        });
        tr.addView(tv2); 
        tl.addView(tr);
    }
}

 public void deselectAll(View view){
     for (int i = 0; i < tl.getChildCount(); i++) {
          CheckBox cb = (CheckBox)((TableRow)tl.getChildAt(i)).getChildAt(0);
          cb.setChecked(false);
     }
 }

 public void selectAll(View view){
     for (int i = 0; i < tl.getChildCount(); i++) {
          CheckBox cb = (CheckBox)((TableRow)tl.getChildAt(i)).getChildAt(0);
          cb.setChecked(true);
     }
 }

 public void onCancelAction(View view){
     SettingActivityGroup.group.back();  
     return;
 }

 public void onNextAction(View view){
    if(selectedRoutes.size() > 0){
        StringBuffer routeCode = new StringBuffer();
        for(int i=0; i<selectedRoutes.size();i++){
            routeCode.append("\'" + selectedRoutes.get(i) +"\'" +",");
        }
        routeCode.delete(routeCode.length() - 1,routeCode.length());
        strUField1 = routeCode.toString();
//      new DailyDownldAsyncTask().execute();
      //    String s = new DownlaodTableActivity().loadDailyDownloadData(strBusinessUnit, strExecutive,strTerritoryCode,strUField1);


//  System.out.println(" ---s - " + s);

            new DailyDownldAsyncTask().execute();
//          Intent i = new Intent(getBaseContext(), DownlaodTableActivity.class);
//          Bundle bundle = new Bundle();
//              bundle.putString("strRouteCode", strUField1);
//              bundle.putString("name", "ListRoutesActivity");
//              i.putExtras(bundle);
//          View vi = SettingActivityGroup.group.getLocalActivityManager().startActivity(
//                  "ListRoutesActivity", i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
//                  .getDecorView();
//
//          SettingActivityGroup.group.replaceView(vi);

    }else{
        Toast.makeText(ListRoutesActivity.this,"Please select the Route!",Toast.LENGTH_SHORT).show();
    }
     return;
 }


 public String loadDailyDownloadData(String strBusinessUnit, String strExecutive, String strTerritoryCode,String strUField1){
        SoapPrimitive responsePrimitiveData;
        String downloadResult = "";
        dailyDownTable = "LoadTarget";
        String actualtable = "";
        StringBuffer sucessDownTable = new StringBuffer();
            try {
                responsePrimitiveData = soapPrimitiveData(dailyDownTable,strBusinessUnit, strExecutive, strTerritoryCode,strUField1);
                 if (responsePrimitiveData != null) {
                    try {
                        String result = responsePrimitiveData.toString();
                        if(!result.equals("")){
                            JSONObject jsonobject = new JSONObject(result);
                            for(int x = 0; x < jsonFilter.length; x++){
                                Log.i("loadDailyDownloadData", "-- " + x);
                                JSONArray array = jsonobject.getJSONArray(jsonFilter[x]); // return [name:value]
                                boolean isRecordAvailable  = false;
                                String updateType = getTableUpdateType(dailyDownTable);
                                if(array.length()>0){
                                    // actual table assignment
                                    if(jsonFilter[x].equals("OutStanding1")){
                                         actualtable = "WMOutstandingInvoice";
                                    }else if(jsonFilter[x].equals("PDCheque1")){
                                         actualtable = "WMPDCheque";
                                    }else if(jsonFilter[x].equals("ReturnCheque1")){
                                         actualtable = "WMReturnCheque";
                                    }else if(jsonFilter[x].equals("Target1")){
                                         actualtable = "WMRetailerTarget";
                                    }

                                   if(!updateType.equals("3")){
                                       //check table whether its contain records or not
                                       isRecordAvailable = isTableRecords(dailyDownTable);
                                   }

                                   // delete the retailer who are attached to selected routes
                                   deleteRetailerRecords(actualtable, strUField1);

                                   // check the update type. 1 =Insert , 2= Update , 3=Delete
                                    if (updateType.equals("1")) {
                                        String[] strWhereField = getTablePrimaryKey(dailyDownTable,strBusinessUnit);
                                        saveOrUpdate(actualtable,array,isRecordAvailable,strWhereField);

                                    } else if (updateType.equals("2")) {
                                        String[] strWhereField = getTablePrimaryKey(dailyDownTable,strBusinessUnit);
                                        saveOrUpdate(actualtable,array,isRecordAvailable,strWhereField);

                                    }else if(updateType.equals("3")){
                                        deleteTableAllRecords(actualtable); 
                                        String[] strWhereField = new String[0];
                                        saveOrUpdate(actualtable, array,isRecordAvailable,strWhereField);
                                    }
                                    if(x == 3){
                                        sucessDownTable.append(actualtable);
                                    }else{
                                        sucessDownTable.append(actualtable + ",");
                                    }
                                }
                            }
                        }
                        downloadResult = sucessDownTable.toString();
                    } catch (JSONException e) {
                        Log.i("Error" ,"Error on loadDailyDownloadData()"+ e.getMessage() );
                        e.printStackTrace();
                    }
                }else{
                    downloadResult = "";
                }
            } catch (IOException e) {
                Log.i("Error" ,"Error on loadDailyDownloadData()"+ e.getMessage() );
                e.printStackTrace();
            } catch (XmlPullParserException e) {
                Log.i("Error" ,"Error on loadDailyDownloadData()"+ e.getMessage() );
                e.printStackTrace();
            }
            Log.i("--------"," --- sucessDownTable--" + sucessDownTable);
            Log.i("***" ,dailyDownTable);

            return downloadResult;
    }


  public class DailyDownldAsyncTask extends
        AsyncTask<String, Integer, String> {
    private final ProgressDialog dialog = new ProgressDialog(
            ListRoutesActivity.this);
    int myProgress;

    @Override
    protected void onPostExecute(String result) {
        if (this.dialog.isShowing()) {
            this.dialog.dismiss();
        }
        Toast.makeText(ListRoutesActivity.this,
                "Download  LoadTarget has been successfully",
                Toast.LENGTH_SHORT).show();
        Intent i = new Intent(getBaseContext(),
                DailyDownloadTargetActvity.class);
        View vi = SettingActivityGroup.group
                .getLocalActivityManager()
                .startActivity("DailyDownloadTargetActvity",
                        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
                .getDecorView();
        SettingActivityGroup.group.replaceView(vi);

    }

    @Override
    protected void onPreExecute() {
        this.dialog.setMessage("Downloading Table Data.......");
        this.dialog.show();
        myProgress = 0;
    }

    @Override
    protected String doInBackground(String... params) {
        loadDailyDownloadData(strBusinessUnit, strExecutive,
                strTerritoryCode, strUField1);
        return null;

    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        dialog.setProgress(values[0]);
    }
}

Error place is onNextAction() & onPreExecute()'s this.dialog.show();

My question is

  1. Solution for this...
  2. Can't we call AsyncTask inside the Button click function?

I know the activity is not started.....why that didn't start?I am calling everything in same activity not different activity...

Please help me ...

Thanks in advance....

回答1:

I have done this using this link.... Android: AsyncTask ProgressDialog will not open in ActivityGroup

Create a helper method for this purpose in the activity class:

private Context getDialogContext() {
    Context context;
    if (getParent() != null) context = getParent();
    else context = this;
    return context;
}

Then change the line

private final ProgressDialog dialog = new ProgressDialog(CheckInActivity.this);

to

private final ProgressDialog dialog = new ProgressDialog(getDialogContext());