How to resolve WindowManager$BadTokenException in android
<p>Hi i am developing a TabBar application which consists of four tabs. Whenever the application is opened the first tab gets selected.In the first tab i am loading a <code>WebView</code> which consists of HTML 5 content(some labels and Textboxes). After entering some data in TextBoxes and able to navigate to the another WebView, in this WebView i am having a spinner i.e.,an HTML spinner. But whenever i click on that spinner i am getting the following <code>Exception</code>:</p>

<pre><code>**02-15 15:16:56.081: E/AndroidRuntime(6133): android.view.WindowManager$BadTokenException: Unable to add window -- token android.app.LocalActivityManager$LocalActivityRecord@449e45c8 is not valid; is your activity running?
02-15 15:16:56.081: E/AndroidRuntime(6133):     at android.view.ViewRoot.setView(ViewRoot.java:505)
02-15 15:16:56.081: E/AndroidRuntime(6133):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
02-15 15:16:56.081: E/AndroidRuntime(6133):     at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
02-15 15:16:56.081: E/AndroidRuntime(6133):     at android.view.Window$LocalWindowManager.addView(Window.java:424)
02-15 15:16:56.081: E/AndroidRuntime(6133):     at android.app.Dialog.show(Dialog.java:241)
02-15 15:16:56.081: E/AndroidRuntime(6133):     at android.webkit.WebView$InvokeListBox.run(WebView.java:7095)
02-15 15:16:56.081: E/AndroidRuntime(6133):     at android.os.Handler.handleCallback(Handler.java:587)
02-15 15:16:56.081: E/AndroidRuntime(6133):     at android.os.Handler.dispatchMessage(Handler.java:92)
02-15 15:16:56.081: E/AndroidRuntime(6133):     at android.os.Looper.loop(Looper.java:123)
02-15 15:16:56.081: E/AndroidRuntime(6133):     at android.app.ActivityThread.main(ActivityThread.java:4627)
02-15 15:16:56.081: E/AndroidRuntime(6133):     at java.lang.reflect.Method.invokeNative(Native Method)
02-15 15:16:56.081: E/AndroidRuntime(6133):     at java.lang.reflect.Method.invoke(Method.java:521)
02-15 15:16:56.081: E/AndroidRuntime(6133):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
02-15 15:16:56.081: E/AndroidRuntime(6133):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
02-15 15:16:56.081: E/AndroidRuntime(6133):     at dalvik.system.NativeStart.main(Native Method)**
</code></pre>

<p>My code is as follows:</p>

<pre><code>public class RDCMobileActivity extends ActivityGroup{

    int tempBackStatus = 1; 
    WebView mWebView;
    TextView mTextView;
    View mapactivityview = null;
    ProgressBar progressBar;
    LocationManager locManager;
    private static boolean linksActivated;
    private static Double latitude,longitude;
    private Stack&lt;String&gt; mIds;
    private LocalActivityManager mActivityManager;
    private int mSerial;
    private String loadURL;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rdcmobile);
        loadURL = this.getIntent().getStringExtra("URL");
        progressBar = (ProgressBar) findViewById(R.id.progress);
        mIds = new Stack&lt;String&gt;();
        mActivityManager = getLocalActivityManager();  
        mWebView = (WebView) findViewById(R.id.webview);
        mWebView.setVerticalScrollBarEnabled(false);
        mWebView.setHorizontalScrollBarEnabled(false);
        //mWebView.requestFocusFromTouch();
        mWebView.setPadding(0, 0, 0, 0);
        mWebView.setInitialScale(1);

        mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        mWebView.setScrollbarFadingEnabled(false);

        WebSettings settings = mWebView.getSettings();
        settings.setLoadWithOverviewMode(true);
        settings.setUseWideViewPort(true);

        //Enable Javascript.
        settings.setJavaScriptEnabled(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setLayoutAlgorithm(LayoutAlgorithm.NORMAL);
        //settings.setDefaultZoom(ZoomDensity.FAR);

        //Enable local database.
        settings.setDatabaseEnabled(true);
        String databasePath = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
        settings.setDatabasePath(databasePath);

        //Enable location cache.
        String geoCachePath = this.getApplicationContext().getDir("geolocation", Context.MODE_PRIVATE).getPath();
        settings.setGeolocationDatabasePath(geoCachePath);
        settings.setGeolocationEnabled(true);

        //Enable manifest cache.
        String cachePath = this.getApplicationContext().getDir("cache", Context.MODE_PRIVATE).getPath();
        settings.setAppCachePath(cachePath);
        settings.setAllowFileAccess(true);
        settings.setAppCacheEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setAppCacheMaxSize(1024 * 1024 * 8);
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);

        locManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
        locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,1000L,500.0f, locationListener);
        Location location = locManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        if(location != null)                                
        {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
            Log.w("Latitude",Double.toString(latitude));
            Log.w("Longitude",Double.toString(longitude));
        }  

        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onExceededDatabaseQuota(String url,String databaseIdentifier, long currentQuota,
                    long estimatedSize, long totalUsedQuota,WebStorage.QuotaUpdater quotaUpdater) {
                quotaUpdater.updateQuota(estimatedSize);
            }

            public void onProgressChanged(WebView view, int progress) {
                if (progress == 100) {
                    progressBar.setVisibility(View.GONE);
                    //linprogress.setVisibility(View.GONE);
                } else {
                    progressBar.setVisibility(View.VISIBLE);
                    //linprogress.setVisibility(View.VISIBLE);
                }
            }

            public void onGeolocationPermissionsShowPrompt(String origin, Callback callback) {
                super.onGeolocationPermissionsShowPrompt(origin, callback);
                callback.invoke(origin, true, false);
            }
        });


        mWebView.setWebViewClient(new WebViewClient() {

            @Override
            public void onReceivedError(WebView view, int errorCode,String description, String failingUrl) {}
            public void onReceivedSslError (WebView view, SslErrorHandler handler, SslError error) {
                 handler.proceed() ;
            }
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.d(" url..", url);
                if (Uri.parse(url).getScheme().equalsIgnoreCase("rdc")) {
                    //rdc://settitle?title=&lt;title&gt; 
                    if (Uri.parse(url).getHost().equalsIgnoreCase("settitle")) {
                        String titleValue = Uri.parse(url).getQueryParameter("title");
                        String title = titleValue.substring(0, titleValue.length());
                        TextView mTextView = (TextView)findViewById(R.id.textview);
                        mTextView.setText(title.toString());
                    } 
                    else if (Uri.parse(url).getHost().equalsIgnoreCase("showmap")){ 
                             addMapView();
                    }else if (Uri.parse(url).getHost().equalsIgnoreCase("hidemap")){
                             removeMapView();
                    }else if ( Uri.parse(url).getHost().equalsIgnoreCase("cart") ||
                             Uri.parse(url).getHost().equalsIgnoreCase("offers") ||
                             Uri.parse(url).getHost().equalsIgnoreCase("certificates") ||
                             Uri.parse(url).getHost().equalsIgnoreCase("account")){
                             int tabIndex=0;
                             if(Uri.parse(url).getHost().equalsIgnoreCase("offers"))
                                  tabIndex=0;
                             if(Uri.parse(url).getHost().equalsIgnoreCase("certificates"))
                                  tabIndex=1;
                             else if(Uri.parse(url).getHost().equalsIgnoreCase("cart"))
                                  tabIndex=2;
                             else if(Uri.parse(url).getHost().equalsIgnoreCase("account"))
                                  tabIndex=3;       
                                  Main.setCurrentTab(tabIndex);
                    }else if (Uri.parse(url).getHost().equalsIgnoreCase("currentlocation")){            
                               //Send the Latitude and Longitude values to the Javascript Function running in the WebView.
                               //Example latlongs:42.3583333,-71.0602778(Boston). 
                               mWebView.loadUrl("javascript:currentLocation(latitude,longitude);");
                    }else if(Uri.parse(url).getHost().equalsIgnoreCase("hidenav")){ 
                                RelativeLayout mRelView = (RelativeLayout)findViewById(R.id.rel2);
                                mRelView.setVisibility(View.GONE);                  
                    }else if(Uri.parse(url).getHost().equalsIgnoreCase("shownav")){ 
                                RelativeLayout mRelView = (RelativeLayout)findViewById(R.id.rel2);
                                mRelView.setVisibility(View.VISIBLE);                   
                    }else if(Uri.parse(url).getHost().equalsIgnoreCase("showactivity")){
                                progressBar.setVisibility(View.VISIBLE);
                    }else if(Uri.parse(url).getHost().equalsIgnoreCase("hideactivity")){
                                progressBar.setVisibility(View.GONE);   
                    }else if(Uri.parse(url).getHost().equalsIgnoreCase("alert")) {
                                Map&lt;String,String&gt; params=getQueryMap(Uri.parse(url).getQuery());
                                dispAlertBox(params.get("title"),params.get("message"),params.get("ok"),params.get("cancel"));              
                    }else if(Uri.parse(url).getHost().equalsIgnoreCase("setbadge")){ 
                                //rdc://setbadge?tab=&lt;number&gt;&amp;value=&lt;number&gt; 
                                //Supports only cart
                                Map&lt;String, String&gt; params = getQueryMap(Uri.parse(url).getQuery());
                                Main.setCartText(""+params.get("value"));
                    }else if(Uri.parse(url).getHost().equalsIgnoreCase("debug")) {
                               //rdc://debug?txt=&lt;debug txt&gt;
                               Map&lt;String, String&gt; params = getQueryMap(Uri.parse(url).getQuery());
                               Log.w("Debug Scheme txt parameter",params.get("txt"));
                    }else if(Uri.parse(url).getHost().equalsIgnoreCase("warn")) {
                               //rdc://warn?txt=&lt;warn txt&gt;
                               Map&lt;String, String&gt; params = getQueryMap(Uri.parse(url).getQuery());
                               Log.w("Warn Scheme txt parameter",params.get("txt"));
                    }else if(Uri.parse(url).getHost().equalsIgnoreCase("error")) {
                               //rdc://error?txt=&lt;error txt&gt;
                               Map&lt;String, String&gt; params = getQueryMap(Uri.parse(url).getQuery());
                               Log.w("Error Scheme txt parameter",params.get("txt"));
                    }else if(Uri.parse(url).getHost().equalsIgnoreCase("appbadge")) {
                               //rdc://appbadge?value=&lt;number&gt; 
                               //Not feasible in Android    
                    }else if(Uri.parse(url).getHost().equalsIgnoreCase("reload")) {
                               //rdc://reload 
                               mWebView.reload();
                    }else if(Uri.parse(url).getHost().equalsIgnoreCase("reloadall")) { 
                               //rdc://reloadAll    
                               if(Main.main.getTabIndexNo()==1){
                                   //Implement the Code.
                               }
                               else if(Main.main.getTabIndexNo()==2){
                                   //Implement the Code.
                               }
                               else if(Main.main.getTabIndexNo()==3){
                                   //Implement the Code.
                               }

                    }else if(Uri.parse(url).getHost().equalsIgnoreCase("version")) {
                               //rdc://version 
                        try{
                            PackageInfo pinfo = getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
                            mWebView.addJavascriptInterface(this,pinfo.versionName);
                        }catch(NameNotFoundException e){    
                         }
                    }else{
                             removeMapView();
                    }
                           return true;
            } else if (Uri.parse(url).getScheme().equalsIgnoreCase("browser")) {
                           String newURL = url.replace("browser", "http");
                           linksActivated=true;
                           Main.main.setTopLayer();
                           Main.main.loadWebView(newURL);
                           return true;
            } else if (Uri.parse(url).getScheme().equalsIgnoreCase("next")) {
                           String newURL = url.replace("next", "https");
                           Intent intent = new Intent(RDCMobileActivity.this,RDCMobileActivity.class);
                           intent.putExtra("URL", newURL);
                           replaceContentView(url,intent);
                           return true;
            } else if (Uri.parse(url).getScheme().equalsIgnoreCase("prev")) {
                           finish();
                           return true;
            }else if (Uri.parse(url).getScheme().equalsIgnoreCase("root")) {                       
                           return true;
            }else if (Uri.parse(url).getScheme().equalsIgnoreCase("safari")) {
                           String newURL = url.replace("safari", "http");
                           Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(newURL));
                           startActivity(intent);
                           return true;
            }                   
                return false;
            }
        });

        this.runOnUiThread(new Runnable() {
            public void run() {
                mWebView.loadUrl(loadURL);
            }
        });
    }

    //Gives the Updated Latitude and Longitude Values.
    private void updateWithNewLocation(Location location) {
        if (location != null) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
            Log.w("Latitude",Double.toString(latitude));
            Log.w("Longitude",Double.toString(longitude));
        } else {
            //Do Nothing.
        }
    }

    private final LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            updateWithNewLocation(location);
        }

        public void onProviderDisabled(String provider) {
            updateWithNewLocation(null);
        } 

        public void onProviderEnabled(String provider) {}

        public void onStatusChanged(String provider, int status, Bundle extras) {}
    };



    protected void onPause(){
        super.onPause();
        //removeMapView();
    }

    //Executes whenever this Activity comes into Focus.
    protected void onResume() {
        super.onResume();
        mWebView.reload();
    }

    public void setVisibleOnBack() {
        mWebView.goBack();
        tempBackStatus++;
    }

    private void addMapView() {
        Intent intent = new Intent(this, RDCMapActivity.class);
        Window window = getLocalActivityManager().startActivity("RDCMapActivity", intent);
        mapactivityview = window.getDecorView();

        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)mWebView.getLayoutParams();
        params.height = mWebView.getHeight()-50;
        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);

        //we need this to adjust the height of the map
        //mWebView.loadUrl("javascript:document.getElementById('topnavbar1').offsetHeight");

        RelativeLayout mRelView = (RelativeLayout) findViewById(R.id.rel3);
        mRelView.addView(mapactivityview, params);
    }

    private void removeMapView() {
        RelativeLayout mRelView = (RelativeLayout) findViewById(R.id.rel3);
        mRelView.removeView(mapactivityview);
        getLocalActivityManager().removeAllActivities();
    }

    public static Map&lt;String, String&gt; getQueryMap(String query)  
    {  
        String[] params = query.split("&amp;");  
        Map&lt;String, String&gt; map = new HashMap&lt;String, String&gt;(); 
        String name="";
        String value="";
        String paramArr[];
        for (String param : params){    
            paramArr=param.split("=");
            if(paramArr.length==2){
                name = paramArr[0];  
                value = paramArr[1];             
            }else{
                name=paramArr[0];
                value="";
            }
            map.put(name, value); 
        }  
        return map;  
    }  

    //Sets Multiple Views For CurrentTab.
    public void replaceContentView(final String url, Intent newIntent) {
        //View view = getLocalActivityManager().startActivity(url,newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)).getDecorView();
        String id = "id" + mSerial++;
        mIds.push(id);
        //View view = mActivityManager.startActivity(id,newIntent).getDecorView();
        View view = getLocalActivityManager().startActivity(id,newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                | Intent.FLAG_ACTIVITY_SINGLE_TOP))
        .getDecorView();
        setContentView(view);
        mWebView.loadUrl(url);
    }   

    //Displays An AlertBox.
    public void dispAlertBox(final String title,final String message,final String ok,final String cancel) {
         Main.dispAlertBox(title,message,ok,cancel);
    }
</code></pre>
