getApplicationContext()错误,对话框

时间:2019-01-27 12:04:12

标签: android

我无法创建Pogress对话框,因为getApplicationContext()返回null

  

创建ProgressDialog的问题

public void Diag(Boolean Show){
    ProgressDialog dialog = new ProgressDialog(getApplicationContext());
    if (Show){
        // (Dialog) Wait time
        dialog.setMessage("Iniciando sesión...");
        dialog.setCancelable(false);
        dialog.show();
    }else{
        dialog.dismiss(); // (Dialog) End Wait
    }
}
  

错误:

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{RubenPX.ROX/RubenPX.ROX.Main}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference

编辑:

  

我尝试了这个,但是没有用

public class Diag extends Application{
    ProgressDialog dialog = new ProgressDialog(getApplicationContext());
    public void Show(){
        // (Dialog) Wait time
        dialog.setMessage("Iniciando sesión...");
        dialog.setCancelable(false);
        dialog.show();
    }

    public void Dimiss(){
        dialog.dismiss(); // (Dialog) End Wait
    }
}

1 个答案:

答案 0 :(得分:1)

您应该将Activity Context与使用应用程序上下文结合使用

赞:

public void Diag(Boolean Show, Context context){
    ProgressDialog dialog = new ProgressDialog(context);
    if (Show){
        // (Dialog) Wait time
        dialog.setMessage("Iniciando sesión...");
        dialog.setCancelable(false);
        dialog.show();
    }else{
        dialog.dismiss(); // (Dialog) End Wait
    }
}

必须阅读this