Android从另一个活动打开AlertDialog

时间:2012-08-05 12:08:42

标签: android android-activity alertdialog

我在这里和其他网站上阅读了相互矛盾的报道,说明它/不可能显示来自其他活动的警报对话框。我正在努力做到这一点:

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();

    }

}

Catch android.view.WindowManager $ BadTokenException:无法添加窗口 - 令牌null不适用于应用程序。

非常感谢你的帮助: - )

1 个答案:

答案 0 :(得分:0)

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

此外,这行代码是什么?

private static final String Context = null;