Android.view.WindowManager $ BadTokenException: Failed to add window - null token is invalid

I get this error whenever I try to run a window class. I use a separate class, not just a method inside my game class, so I need to disable the back button in this popup. I call this class with a button. This code works great if I use it in my game class, but not in a 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() { } } 
+6
source share
1 answer

You do not call setContentView(R.layout.myLayout) in your onCreate(Bundle) method. Name it right after super.onCreate(savedInstanceState); .

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

There are two methods: almost all subclasses of Activity implementation:

onCreate (Bundle) is where you initialize your activity. Most importantly, here you usually call setContentView (int) using a layout resource that defines your user interface, and using findViewById (int) to get widgets in that user interface that you need to interact with programmatically.

onPause () is where you deal with a user leaving your activity. Most importantly, any changes made by the user should be at this stage (usually for a ContentProvider containing data).

Change 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); 
+13
source

Source: https://habr.com/ru/post/949981/


All Articles