【问题标题】:StartActivity not working when Toast called before it当 Toast 在它之前调用时,StartActivity 不起作用
【发布时间】:2016-03-28 18:19:55
【问题描述】:

当我在开始另一个活动之前不调用 Toast 时,事情会按预期工作。但是,如果我在 startActivity 之前调用 Toast,则活动将不会开始。请检查此代码以了解我的问题:

class LoginTask extends HttpAsyncTask {
    @Override
    protected void onPostExecute(String result) {
        if (result != null) {
            LoginResponse loginResponse = (LoginResponse) getMappedModel(result, LoginResponse.class);
            if(loginResponse.getResult().equals("success")) {
                /*startActivity works only if I comment this line*/ Toast.makeText(getBaseContext(), "Logged in Successfully!", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(intent);
            } else {
                Toast.makeText(getBaseContext(), "Wrong username or password!", Toast.LENGTH_LONG).show();
            }
        }
    }
}

【问题讨论】:

  • getBaseContext() 替换为LoginActivity.this 并重试。
  • 做到了。这没有帮助!
  • 收到任何错误日志吗?
  • 尝试:“This”或“ActivityName.this”。如果是 "Activity" , "getActivity()"

标签: android android-intent android-toast


【解决方案1】:

如果没有看到你所有的代码,我会建议使用 getApplicationContext,这将返回应用程序的上下文。

Toast.makeText(getApplicationContext (), "Logged in Successfully!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext (), MainActivity.class);

【讨论】:

    【解决方案2】:

    我不确定为什么您的 Toast 会阻止 MainActivity 启动,但您应该能够通过将显示代码的 toast 移动到 MainActivityOnCreate 方法中来修复它。您还可以添加额外的特殊意图布尔值showsuccesstoast,这将在 MainActivity.onCreate 中指示应该显示 toast。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-04
      相关资源
      最近更新 更多