java - Firebase 无法显示实时数据库中的名称

标签 java android firebase firebase-realtime-database

在我的 Firebase 数据库中,我创建了一个新用户,并为该用户分配了一些值。

See attached image

但是,我无法获取名称并显示在抽屉导航的标题中。为了清楚起见,我发布了完整的 MainActivity.class

请帮我解决这个问题,告诉我我做错了什么,我一整天都在做这个

package com.company.walt.activities;

public class MainActivity extends AppCompatActivity implements IProgressDisplay, ISoftKeyboard, IFirebaseAuth {

    // STATIC
    private static final String TAG = "MainActivity";
    private static final int USER_DASHBOARD = 1;
    private static final int PROFILE_MANAGE = 2;
    private static final int PROFILE_SETTING = 3;

    // FIREBASE
    private FirebaseAuth.AuthStateListener mAuthListener;
    /*
    private FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
    private DatabaseReference databaseReference = firebaseDatabase.getReference();
    private DatabaseReference reference = databaseReference.child(getString(R.string.dbnode_users));
    */


    DatabaseReference mRootRef = FirebaseDatabase.getInstance().getReference();
    DatabaseReference mConditionRef = mRootRef.child("users");


    // VARIABLES
    private ToggleButton mToogleButton;
    private Toolbar mToolbar;
    private AccountHeader mHeaderResult = null;
    private Drawer mResult = null;
    private ProgressBar mProgressBar;

    private String currentName = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES) {
            setTheme(R.style.NightTheme);
        } else {
            setTheme(R.style.LightTheme);
        }

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        switchAppTheme();

        createToolbar();

        buildHeader(false, savedInstanceState);

        createDrawerBuilder();

        mProgressBar = (ProgressBar) findViewById(R.id.progressBar);

    }

    @Override
    protected void onResume() {
        super.onResume();
        checkAuthenticationState();
    }

    /**
     * Used to check if user is authenticated or not
     */
    private void checkAuthenticationState() {
        Log.d(TAG, "checkAuthenticationState: checking authentication state.");
        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        if (user == null) {
            Log.d(TAG, "checkAuthenticationState: user is null, navigating back to login screen.");
            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
            startActivity(intent);
            finish();
        } else {
            Log.d(TAG, "checkAuthenticationState: user is authenticated.");
        }
    }

    /**
     * Used to switch between light and dark mode
     */
    public void switchAppTheme() {

        mToogleButton = (ToggleButton) findViewById(R.id.switcher);

        if (AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES) {
            mToogleButton.setChecked(true);
        }

        mToogleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
                    restartApp();
                } else {
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
                    restartApp();
                }
            }
        });
    }

    /**
     * Used to create the toolbar on top
     */
    private void createToolbar() {
        mToolbar = (Toolbar) findViewById(R.id.main_toolbar);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setTitle(R.string.app_name);
    }

    /**
     * small helper method to reuse the logic to build the AccountHeader
     * this will be used to replace the header of the drawer with a compact/normal header
     *
     * @param compact
     * @param savedInstanceState
     */
    private void buildHeader(boolean compact, Bundle savedInstanceState) {

        IProfile profile;

        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

        if (user != null) {

            String email = user.getEmail();

            profile = new ProfileDrawerItem()
                    .withIdentifier(USER_DASHBOARD)
                    .withName(getCurrentName())
                    .withEmail(email)
                    .withIcon(getResources().getDrawable(R.drawable.ic_user_img));

            mHeaderResult = new AccountHeaderBuilder()

                    .withActivity(this)
                    .withHeaderBackground(R.drawable.ip_menu_header_bg)
                    .withCompactStyle(compact)
                    .addProfiles(
                            profile,

                            new ProfileSettingDrawerItem()
                                    .withIdentifier(PROFILE_MANAGE)
                                    .withName("Manage Account")
                                    .withDescription("Manage your details")
                                    .withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_settings)
                                            .actionBar().colorRes(R.color.material_drawer_dark_primary_text)),

                            new ProfileSettingDrawerItem()
                                    .withIdentifier(PROFILE_SETTING)
                                    .withName("Add Account")
                                    .withDescription("Register new account")
                                    .withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_person_add)
                                            .actionBar().colorRes(R.color.material_drawer_dark_primary_text))

                    )
                    .withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() {

                        @Override
                        public boolean onProfileChanged(View view, IProfile profile, boolean current) {

                            //sample usage of the onProfileChanged listener
                            //if the clicked item has the identifier 1 add a new profile ;)

                            if (profile instanceof IDrawerItem && ((IDrawerItem) profile).getIdentifier() == USER_DASHBOARD) {
                                // Navigate to home fragment
                                FragmentManager manager = getSupportFragmentManager();
                                FragmentTransaction transaction = manager.beginTransaction();
                                Fragment fragment = new Fragment();

                                fragment = new HomeFragment();
                                transaction.replace(R.id.flContent, fragment);
                                transaction.commit();

                            }

                            if (profile instanceof IDrawerItem && ((IDrawerItem) profile).getIdentifier() == PROFILE_MANAGE) {
                                // Navigate to home fragment
                                FragmentManager manager = getSupportFragmentManager();
                                FragmentTransaction transaction = manager.beginTransaction();
                                Fragment fragment = new Fragment();

                                fragment = new AccountFragment();
                                transaction.replace(R.id.flContent, fragment);
                                transaction.commit();

                            } else if (profile instanceof IDrawerItem && ((IDrawerItem) profile).getIdentifier() == PROFILE_SETTING) {
                                Toast.makeText(MainActivity.this, "ACCOUNT", Toast.LENGTH_SHORT).show();

                            }

                            return false;
                        }
                    })
                    .build();

        }

    }


    /**
     * Used to create the drawer with all the icons and items
     */
    private void createDrawerBuilder() {
        //create the drawer and remember the `Drawer` mResult object
        mResult = new DrawerBuilder()
                .withActivity(this)
                .withAccountHeader(mHeaderResult)
                .withToolbar(mToolbar)
                .addDrawerItems(
                        new SecondaryDrawerItem().withName("1st")
                                .withIdentifier(1)
                                .withIconTintingEnabled(true)
                                .withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_device_hub))
                                .withTag("Bullhorn"),

                        new SecondaryDrawerItem().withName("2nd")
                                .withIdentifier(2)
                                .withIconTintingEnabled(true)
                                .withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_shopping_cart))
                                .withTag("Bullhorn"),

                        new SecondaryDrawerItem().withName("3rd")
                                .withIdentifier(3)
                                .withIconTintingEnabled(true)
                                .withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_camera_roll))
                                .withTag("Bullhorn"),

                        new SecondaryDrawerItem().withName("4th")
                                .withIdentifier(4)
                                .withIconTintingEnabled(true)
                                .withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_content_copy))
                                .withTag("Bullhorn"),

                        new SecondaryDrawerItem().withName("5th")
                                .withIdentifier(5)
                                .withIconTintingEnabled(true)
                                .withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_folder_open))
                                .withTag("Bullhorn"),

                        new SectionDrawerItem().withName(R.string.drawer_section_header).withEnabled(false),

                        new SecondaryDrawerItem().withName("6th")
                                .withIdentifier(6)
                                .withIconTintingEnabled(true)
                                .withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_settings))
                                .withTag("Bullhorn"),

                        new SecondaryDrawerItem().withName("7th")
                                .withIdentifier(7)
                                .withIconTintingEnabled(true)
                                .withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_headset_mic))
                                .withTag("Bullhorn"),

                        new SecondaryDrawerItem().withName("8th")
                                .withIdentifier(8)
                                .withIconTintingEnabled(true)
                                .withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_security))
                                .withTag("Bullhorn"),

                        new SecondaryDrawerItem().withName("9th")
                                .withIdentifier(9)
                                .withIconTintingEnabled(true)
                                .withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_power_settings_new))
                                .withTag("Bullhorn")

                )
                .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
                    @Override
                    public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {

                        navigateDrawerItem((int) drawerItem.getIdentifier(), drawerItem);
                        return true;
                    }
                })
                .addStickyDrawerItems(
                        new SecondaryDrawerItem().withName(R.string.drawer_all_right_reserved).withIcon(FontAwesome.Icon.faw_copyright).withEnabled(false)
                ).build();

    }

    /**
     * Used to navigate to drawer fragment items
     */
    public void navigateDrawerItem(int pos, IDrawerItem drawerItem) {

        // Create a new fragment and specify the fragment to show based on nav item clicked
        Fragment fragment = null;
        Class fragmentClass;

        switch (pos) {
            case 1:
                fragmentClass = Fragment1.class;
                break;
            case 2:
                fragmentClass = Fragment2.class;
                break;
            case 3:
                fragmentClass = Fragment3.class;
                break;
            case 4:
                fragmentClass = Fragment4.class;
                break;
            case 5:
                fragmentClass = Fragment5.class;
                break;
            case 6:
                fragmentClass = Fragment6.class;
                break;
            case 7:
                fragmentClass = Fragment7.class;
                break;
            case 8:
                fragmentClass = Fragment8.class;
                break;

            case 9:
                fragmentClass = HomeFragment.class;
                signOut();
                restartApp();
                break;

            default:
                fragmentClass = HomeFragment.class;
        }
        try {
            fragment = (Fragment) fragmentClass.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // Insert the fragment by replacing any existing fragment
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
        mResult.closeDrawer();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            default:
                return super.onOptionsItemSelected(item);
        }

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //add the values which need to be saved from the drawer to the bundle
        outState = mResult.saveInstanceState(outState);

        //add the values which need to be saved from the accountHeader to the bundle
        outState = mHeaderResult.saveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onBackPressed() {
        //handle the back press :D close the drawer first and if the drawer is closed close the activity
        if (mResult != null && mResult.isDrawerOpen()) {
            mResult.closeDrawer();
        } else {
            super.onBackPressed();
        }
    }

    /**
     * Sign out from application
     */
    private void signOut() {
        Log.d(TAG, "signOut: signing out");
        FirebaseAuth.getInstance().signOut();
    }

    /**
     * Used to restart the application
     */
    private void restartApp() {
        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    protected void onStart() {
        super.onStart();

        Query query = mConditionRef.orderByKey().equalTo(FirebaseAuth.getInstance().getCurrentUser().getUid());

        query.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                for (DataSnapshot singelSnapshot : dataSnapshot.getChildren())
                {
                    User user = singelSnapshot.getValue(User.class);

                    setCurrentName(user.getName());

                    Log.d(TAG, "onDataChange: found user: " + user.toString());
                }

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });


    }

    @Override
    protected void onStop() {
        super.onStop();

    }

    /*
   * **********************************************************************************************
   * GET & SET
   * */

    public String getCurrentName() {
        return this.currentName;
    }

    //public method to set the age variable
    public void setCurrentName(String name) {
        this.currentName = name;
    }

    /*
    * **********************************************************************************************
    * INTERFACE METHODS
    * */

    /**
     * Display progressbar
     */
    public void showProgress() {
        findViewById(R.id.progressBar).setVisibility(View.VISIBLE);
    }

    /**
     * Hide progressbar
     */
    public void hideProgress() {
        if (mProgressBar.getVisibility() == View.VISIBLE) {
            findViewById(R.id.progressBar).setVisibility(View.INVISIBLE);
        }
    }

    /**
     * Hide softKeyboard
     */
    public void hideSoftKeyboard() {
        this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    }

    /*
    * **********************************************************************************************
    * FIREBASE SETUP
    * */

    /**
     * Firebase Auth
     */
    public void setupFirebaseAuth() {

        mAuthListener = new FirebaseAuth.AuthStateListener() {

            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if (user != null) {
                    // User is signed in
                    Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
                    //toastMessage("Successfully signed in with: " + user.getEmail());


                } else {
                    // User is signed out
                    Log.d(TAG, "onAuthStateChanged:signed_out");

                    Toast.makeText(MainActivity.this, "Signed out", Toast.LENGTH_SHORT).show();

                    Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                    startActivity(intent);
                }
            }

        };

    }

}

这是 LogCat 中的输出

01-01 20:30:24.294 4992-4992/com.company.walt D/MainActivity: onDataChange: found user: User{name='Ben Solo', phone='0997755223311', profile_img='', user_id='D1lXejIFjNTcRr87PAI8rdjm7Wt2'}

最佳答案

与其他同步方法调用不同,onDataChange 方法是异步的。

这意味着监听器声明之后的代码很可能会在 onDataChange 获取调用并设置用户名之前运行。这将导致您的名字在显示中为空

将当前用户代码转移到setCurrentName方法

 setCurrentName(String name){

        currentUser = new ProfileDrawerItem()
            .withIdentifier(USER_DASHBOARD)

            // Using name passed by onDataChange
            .withName(name)

            .withEmail(email)
            .withIcon(getResources().getDrawable(R.drawable.ic_user_img));

 }

现在,当 onDataChange 被调用时,您的显示器将获得名称,并且应该根据您的逻辑进行更新

关于java - Firebase 无法显示实时数据库中的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48052852/

相关文章:

java - 通过 CDI 检索单元测试中的替代实体管理器

java - 对称差异 b/w 未排序数组

Android 在拖动时为 Fragment 制作动画并调整其大小

android - 我可以将手机用作带有 Windows 10 登录选项的 webauthn 安全 key 吗

android - Android SDK 路径中的空格是否会导致 Eclipse 出现问题?

java - 使用 Spring 测试列表是否为空

java - 允许用户在Java中搜索和删除ArrayList中的对象

android - 错误:程序类型已存在:com.google.protobuf.DescriptorProtos $ EnumDescriptorProto $ Builder

Firebase 跨服务安全规则在应用程序中不起作用

ios - 当我尝试在 Firebase 数据库中插入日期作为键时崩溃