开发者

in saveState what's my context?

开发者 https://www.devze.com 2023-03-31 10:09 出处:网络
I am trying to do some cleanup within a saveState() call.I want to pop-up a dialog if there is an error on exiting the activity, but the activity is already gone by this point.

I am trying to do some cleanup within a saveState() call. I want to pop-up a dialog if there is an error on exiting the activity, but the activity is already gone by this point.

I want to have this happen from an activity called StudentEdit but what should the context be? When I use StudentEdit.this, the dialog pops up and then disappears. getApplicationContext causes a null pointer exception.

private void saveState() {

    // some error checking code
    // if blah blah
    AlertDialog alertDialog = new AlertDialog.Builder(StudentEdit.this).create();

alertDialog.setMessage("error");

alertDialog.setButton(BUTTON_POSITIVE, "Yes", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {

               // do something for yes

              } });
alertDialog.setButton(BUTTON_NEGATIVE, "No", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int id) {
             dialog.cancel();            // kill dialog
             StudentEdit.this.finish();  // kill the activity
    }
});
alertDialog.show()开发者_如何学JAVA;

} 


this should work for you.

@Override
protected void onPause() {
    saveState(this)
}

change your saveState to.

private saveState(Context context) {
    //AlertDialog alertDialog = new AlertDialog.Builder(context).create();
    Toast.maketext(context, "Boom..." Toast.LENGTH_SHORT).show();
}

this should be enough, the call from onSaveInstanceState may not be needed.

UPDATE

i would still suggest considering your design, if you really need to show something at this point. may be a Toast would do, blocking the UI with the alert at this point is not recommended.


I don't think you can show UI there by design. If you have an error, you should persist that data as well and show it to the user on the next launch.

You can't use the ApplicationContext, in general, for UI-related stuff.

0

精彩评论

暂无评论...
验证码 换一张
取 消