1

其他類用在我Mainactivity的Android環境:比活動

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 

另外我想使用像

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? 

我對所有這些都很困惑,任何人都可以幫助我嗎?非常感謝你!

+0

請添加完整的代碼,你將如何展現dailog是指凡在活動或服務或片段? –

回答

1

我不完全確定你在做什麼,但對於第一個問題,它看起來像是在嘗試使用非活動上下文來顯示對話框。

TL; DR,您不能使用應用程序上下文的AlertDialog,它需要一個Activity。 考慮是這樣的:

new AlertDialog.Builder(<activity>) 

第二個問題也是類似的,你可以開始使用應用程序上下文的活動,但你需要啓動它作爲一個新的任務。要做到這一點,你需要添加一個標誌。 (雖然,這是不被認爲是很好的做法)

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

檢查here了更多關於您可以和不可以用各類安卓上下文做什麼。

0

試試這個。

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

將getApllicationcontext替換爲您的活動。

new AlertDialog.Builder(<activity>) 
0

您可以使用此以及

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

LoginUser.java

public void loginUser(Context context){ 
}