【问题标题】:Android Context used in classes other than ActivityActivity 以外的类中使用的 Android Context
【发布时间】:2016-07-30 03:52:37
【问题描述】:

在我的主要活动中:

 LoginUser.loginUser(username.getText().toString(),password.getText().toString(), getApplication());

所以在我的 LoginUser 类中, 我想启动一个这样的对话框:

new AlertDialog.Builder(context).set.....

但失败了, 得到这样的故障信息:

android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

我也想用like

Intent intent = new Intent(context, ABC.class)
context.startActivity(intent);

也失败了。并得到这样的故障信息:

android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?

我对所有这些都很困惑,有人可以帮助我吗?非常感谢!

【问题讨论】:

  • 请添加完整代码您将如何显示 dailog 表示活动或服务或片段中的位置?

标签: android android-intent android-activity android-alertdialog android-context


【解决方案1】:

我不完全确定您在做什么,但对于第一个问题,您似乎正在尝试使用非活动上下文来显示对话框。

TL;DR,您不能使用带有应用程序上下文的 AlertDialog,它需要一个 Activity。 考虑类似的事情:

new AlertDialog.Builder(<activity>)

第二个问题也类似,你可以用一个应用上下文来启动一个activity,但是你需要将它作为一个新任务来启动。为此,您需要添加一个标志。 (虽然,这不被认为是好的做法)

Intent intent = new Intent(context, MyActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);

查看here,详细了解您可以在 Android 中使用各种类型的上下文,不能做什么。

【讨论】:

    【解决方案2】:

    试试这个。

    LoginUser.loginUser(username.getText().toString(),password.getText().toString(),  Mainactivity.this);
    

    将 getApllicationcontext() 替换为您的 Activity。

    new AlertDialog.Builder(<activity>)
    

    【讨论】:

      【解决方案3】:

      你也可以用这个

      LoginUser.loginUser(username.getText().toString(),password.getText().toString(), this);
      

      LoginUser.java

      public void loginUser(Context context){
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-14
        • 2014-03-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多