[英]No errors but alert dialog not displaying
我有非活動類MenuHandler
來處理與菜單相關的事件,我試圖在alert對話框中顯示開發人員消息,此消息從firebase
實時數據庫中獲取。
一切都很好,但警報對話框沒有顯示,我嘗試調試器檢查數據庫中是否有任何錯誤,但我從數據庫正確得到了價值。 從數據庫獲取值沒有錯誤。
當我從MainActivity
選擇菜單時, developerMessage
toast顯示沒有任何反應。
我正確地將context
傳遞給MenuHandler
類。 我可以在使用上下文中顯示Alerdialog
嗎? 或者我只需要在MainActivity
編寫代碼(即只有活動類)。
碼:
public void developersMessage()
{
if (isInternetOn()) {
Toast.makeText(mContext,"Loading message please wait",Toast.LENGTH_SHORT).show();
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.child("version_1_0").child("dev").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
try {
final AlertDialog.Builder builder = new AlertDialog.Builder(mContext, R.style.AppCompatAlertDialogStyle);
builder.setTitle(mContext.getString(R.string.welcome_msg));
builder.setMessage(dataSnapshot.child("dev_msg").getValue(String.class));
builder.setPositiveButton("ok",null);
builder.create().show();
}
catch (Exception e)
{
e.printStackTrace();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
else
{
Toast.makeText(mContext,"please turn on internet ",Toast.LENGTH_SHORT).show();
}
}
構建您的AlertDialog
mDatabase.child("version_1_0").child("dev").addListenerForSingleValueEvent(...);
addListenerForSingleValueEvent(...)
方法在不同的后台線程上運行,因此無法在UI線程內部更新UI。 因此,使用addListenerForSingleValueEvent(...)
方法構建AlertDailog可以解決您的問題。
您應該使用活動上下文來創建AlertDialog。
並請調試以確保onDataChange()
也可以嘗試使用runOnUiThread: https : //developer.android.com/reference/android/app/Activity.html#runOnUiThread (java.lang.Runnable )
yourActivity.runOnUiThread(new Runnable() { public void run() {... code to create & show dialog ...} })
我得到了答案,代碼沒有錯,但錯誤在於我如何從mainactivity發送上下文
在這里我錯誤地初始化了Menuhandler類
public boolean onOptionsItemSelected(MenuItem item) {
final MenuHandler mMenuHandler = new MenuHandler(this.getApplicationContext());//bug lies here
如果我們顯示alertdialog然后我們需要這種方式來傳遞上下文,以便我們的alertdialog正確顯示
public boolean onOptionsItemSelected(MenuItem item) {
final MenuHandler mMenuHandler = new MenuHandler(MainActivity.this);//this is right way to pass context
希望這對將來有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.