0

我在此处和其他网站上阅读了相互冲突的报告,这些报告说它是/不可能显示来自另一个活动的警报对话框。我正在尝试这样做:

public class Options extends Activity {

    /** Include classes */
    SharedPreferences sharedPrefs;
    Preferences prefs;
    Location loc;
    LocationSQL locSQL;
    NetworkConnection netConnect;

    /** Declare buttons */
    Button bLocation;
    Button bRefresh;

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

        sharedPrefs = PreferenceManager.getDefaultSharedPreferences(Options.this);

        /** Set the location for the user */
        setLocationPref();

        /** Refresh selection */
        bRefresh = (Button) findViewById(R.id.bRefresh);
        bRefresh.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
        loc = new Location(getApplicationContext());
            try{

                loc.locationSelection();
            }catch (Exception e){
                Log.d("ERROR", "Catch " + e);
            }
            }
        });

        /** Location selection */
        bLocation = (Button) findViewById(R.id.bLocation);
        bLocation.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

            }
        });
    }
}

然后我想做一些处理,如果需要调用一个 AlertDialog 框。但我得到下面的错误。我知道如果我是正确的,我正在使用已被破坏的上下文?但我想不出如何解决这个问题?

public class Location {

    private static final String Context = null;
    NetworkConnection nc;
    SharedPreferences getSharedPrefs;
    SharedPreferences putSharedPrefs;
    NetworkConnection netConnect;
    Options opts;
    Context context;

    public Location (Context arg)
    {
        context = arg;
    }

    public void locationSelection(){

        message();

    }

    public void message(){

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
        alertDialogBuilder.setTitle("Your Title");
        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();

    }

}

捕获 android.view.WindowManager$BadTokenException: Unable to add window -- token null 不适用于应用程序。

非常感谢您的帮助 :-)

4

1 回答 1

0

不要将 getApplicationContext() 传递给您的 Location 构造函数,而是尝试传递 YourClass.this(这里是 Options.this)。

另外,这行代码是什么?

private static final String Context = null;
于 2012-08-05T12:32:04.547 回答