Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android.view.WindowManager$BadTokenException: Unable to add window — token null is not valid

Tags:

java

android

I get this error whenever I try to start my window class. I am using separate class, and not just a method within my game class, cause I need to disable back button on that popup window. I am calling this class with a button. This code works fine if I use it within my game class, but not in separate class. Here is my code:

public class Popup_pogresno extends Activity implements OnClickListener{

    private PopupWindow pwindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        LayoutInflater layoutInflater 
         = (LayoutInflater)Popup_pogresno.this
          .getSystemService(LAYOUT_INFLATER_SERVICE);  
        View popupView = layoutInflater.inflate(R.layout.popup, null);  
                 pwindow  = new PopupWindow(popupView, 300, 170, true);

                 Button btnDismiss = (Button)popupView.findViewById(R.id.bPopupOK);
                 btnDismiss.setOnClickListener(new Button.OnClickListener(){

         public void onClick(View v) {
          // TODO Auto-generated method stub
             pwindow.dismiss();
         }});

                 pwindow.showAtLocation(popupView, Gravity.CENTER, 0, 0);

       }

    public void onClick(View v) {
        // TODO Auto-generated method stub

    }
    @Override
    public void onBackPressed() {

    }
}
like image 329
marjanbaz Avatar asked Jul 22 '13 11:07

marjanbaz


Video Answer


1 Answers

You are not calling setContentView(R.layout.myLayout) in your onCreate(Bundle) method. Call it right after super.onCreate(savedInstanceState);.

This is from the Activity resource page on Android developers site:

There are two methods almost all subclasses of Activity will implement:

onCreate(Bundle) is where you initialize your activity. Most importantly, here you will usually call setContentView(int) with a layout resource defining your UI, and using findViewById(int) to retrieve the widgets in that UI that you need to interact with programmatically.

onPause() is where you deal with the user leaving your activity. Most importantly, any changes made by the user should at this point be committed (usually to the ContentProvider holding the data).

Edit 1:

Replace:

pwindow.showAtLocation(popupView, Gravity.CENTER, 0, 0);

with:

new Handler().postDelayed(new Runnable(){

    public void run() {
        pwindow.showAtLocation(popupView, Gravity.CENTER, 0, 0);
    }

}, 100L);
like image 170
Vikram Avatar answered Oct 28 '22 01:10

Vikram