简体   繁体   中英

how to inflate the navigation drawer with the user data

The below code help me inflate the username on the drawer menu but the App crash when the user logout is the a better way to retrieved the user data from fire store and not get app crash error when the user log out

  private void DatabaseMethod(String userId) {

        final DocumentReference documentReference =  fStore.collection("users").document(userId);

        documentReference.addSnapshotListener(new EventListener<DocumentSnapshot>() {
            @Override
            public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {
                assert documentSnapshot != null;
                if(documentSnapshot.getString("fullName")!=null){
                    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
                    View headerView = navigationView.getHeaderView(0);
                    TextView navUsername = (TextView) headerView.findViewById(R.id.username);
                    navUsername.setText(documentSnapshot.getString("fullName"));


                }else{
                    Toast.makeText(HomeActivity.this, "Error", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

Here is my Total code just in case you will like to view the entire code

 package com.example.entertainmentlab;

import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.style.TextAppearanceSpan;
import android.view.MenuItem;
import android.view.View;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.navigation.NavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import java.util.Objects;

import javax.annotation.Nullable;

public class HomeActivity extends AppCompatActivity {
    //Declaring Variable

    TextView username;
   private FirebaseAuth fAuth;
   private String userId;
    private FirebaseFirestore fStore;
    private AppBarConfiguration mAppBarConfiguration;


    protected ActionBarDrawerToggle drawerToggle;
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        fStore = FirebaseFirestore.getInstance();
        fAuth =FirebaseAuth.getInstance();




        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.

        mAppBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_trending, R.id.nav_audio, R.id.nav_videos,R.id.nav_store,R.id.nav_setting)
                .setDrawerLayout(drawer)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);


        //set the toolbar text to this color
        toolbar.setTitleTextColor(getResources().getColor(R.color.colorelabGold));

      //set the NavigationView text color
      navigationView.setItemTextColor(ColorStateList.valueOf(Color.rgb(218,165,32)));

      navigationView.setItemIconTintList(ColorStateList.valueOf(Color.rgb(218,165,32)));
      navigationView.setBackgroundColor(Color.rgb(34,33,33));
      //set the  Color of the navigationView List Menu
        Menu menu = navigationView.getMenu();

        MenuItem tools= menu.findItem(R.id.more);
        SpannableString s = new SpannableString(tools.getTitle());
        s.setSpan(new TextAppearanceSpan(this, R.style.TextAppearance44), 0, s.length(), 0);
        tools.setTitle(s);


        userId = Objects.requireNonNull(fAuth.getCurrentUser()).getUid();


        
//inflate the drawer 
   DatabaseMethod(userId);
//sign the user out 
        navigationView.getMenu().findItem(R.id.nav_logout).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {

               fAuth.signOut();
               
                Intent intent = new Intent(HomeActivity.this,LoginActivity.class);
                startActivity(intent);


                //clear the onBackPress Data
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
                return true;
            }
        });


 }
//Here is the code I am talking about but the app crash when the user logout
    private void DatabaseMethod(String userId) {

        final DocumentReference documentReference =  fStore.collection("users").document(userId);

        documentReference.addSnapshotListener(new EventListener<DocumentSnapshot>() {
            @Override
            public void onEvent(@Nullable DocumentSnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {
                assert documentSnapshot != null;
                if(documentSnapshot.getString("fullName")!=null){
                    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
                    View headerView = navigationView.getHeaderView(0);
                    TextView navUsername = (TextView) headerView.findViewById(R.id.username);
                    navUsername.setText(documentSnapshot.getString("fullName"));


                }else{
                    Toast.makeText(HomeActivity.this, "Error", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.home, menu);
        return true;
    }



    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        return NavigationUI.navigateUp(navController, mAppBarConfiguration)
                || super.onSupportNavigateUp();
    }
}

Here is the crash log cat

2021-02-13 17:53:27.739 3204-3204/? I/ntertainmentla: Late-enabling -Xcheck:jni
2021-02-13 17:53:27.984 3204-3204/? E/ntertainmentla: Unknown bits set in runtime_flags: 0x8000
2021-02-13 17:53:29.532 3204-3204/ I/MultiDex: VM with version 2.1.0 has multidex support
2021-02-13 17:53:29.532 3204-3204/ I/MultiDex: Installing application
2021-02-13 17:53:29.533 3204-3204/ I/MultiDex: VM has multidex support, MultiDex support library is disabled.
2021-02-13 17:53:29.535 3204-3204/ I/LoadedApk: No resource references to update in package com.transsion.theme.icon
2021-02-13 17:53:29.672 3204-3297/ W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.
2021-02-13 17:53:29.679 3204-3204/ D/FirebaseApp: com.google.firebase.iid.FirebaseInstanceId is not linked. Skipping initialization.
2021-02-13 17:53:29.680 3204-3204/ D/FirebaseApp: com.google.firebase.crash.FirebaseCrash is not linked. Skipping initialization.
2021-02-13 17:53:29.681 3204-3204/ D/FirebaseApp: com.google.android.gms.measurement.AppMeasurement is not linked. Skipping initialization.
2021-02-13 17:53:29.681 3204-3204/ I/FirebaseInitProvider: FirebaseApp initialization successful
2021-02-13 17:53:29.769 3204-3303/ W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.
2021-02-13 17:53:29.796 3204-3303/ I/FirebaseAuth: [FirebaseAuth:] Loading module via FirebaseOptions.
2021-02-13 17:53:29.797 3204-3303/ I/FirebaseAuth: [FirebaseAuth:] Preparing to create service connection to gms implementation
2021-02-13 17:53:30.046 3204-3204/ W/ntertainmentla: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
2021-02-13 17:53:30.049 3204-3204/ W/ntertainmentla: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
2021-02-13 17:53:30.233 3204-3204/ D/skia: SkJpegCodec::onGetPixels +
2021-02-13 17:53:30.256 3204-3204/ D/skia: SkJpegCodec::onGetPixels -
2021-02-13 17:53:30.301 3204-3204/ I/SurfaceFactory: [static] sSurfaceFactory = com.mediatek.view.impl.SurfaceFactoryImpl@c8661e1
2021-02-13 17:53:30.310 3204-3204/ D/TouchScreenHelper: --getInstance()
2021-02-13 17:53:30.310 3204-3204/ D/TouchScreenHelper: --getInstance()  com.transsion.view.TouchScreenHelperImpl
2021-02-13 17:53:30.311 3204-3204/ I/TouchScreenHelperImpl: constructed in 
2021-02-13 17:53:30.363 3204-3204/ D/ViewRootImpl[MainActivity]: hardware acceleration = true , fakeHwAccelerated = false, sRendererDisabled = false, forceHwAccelerated = false, sSystemRendererDisabled = false
2021-02-13 17:53:30.381 3204-3204/ V/PhoneWindow: DecorView setVisiblity: visibility = 0, Parent = android.view.ViewRootImpl@f263b1d, this = DecorView@eb83192[MainActivity]
2021-02-13 17:53:30.461 3204-3306/ I/GPUD: @gpudInitialize: successfully initialized with GL, dbg=0 mmdump_dbg=0 mmpath_dbg=0
2021-02-13 17:53:30.478 3204-3306/ E/GED: Failed to get GED Log Buf, err(0)
2021-02-13 17:53:30.514 3204-3306/ D/Surface: Surface::connect(this=0x9cd83800,api=1)
2021-02-13 17:53:30.520 3204-3306/ D/Surface: Surface::setBufferCount(this=0x9cd83800,bufferCount=3)
2021-02-13 17:53:30.521 3204-3306/ D/Surface: Surface::allocateBuffers(this=0x9cd83800)
2021-02-13 17:53:30.566 3204-3306/ W/Gralloc3: mapper 3.x is not supported
2021-02-13 17:53:30.577 3204-3306/ E/ion: ioctl c0044901 failed with code -1: Invalid argument
2021-02-13 17:53:35.418 3204-3204/ W/ActivityThread: handleWindowVisibility: no activity for token android.os.BinderProxy@3f1258d
2021-02-13 17:53:36.241 3204-3204/ V/PhoneWindow: DecorView setVisiblity: visibility = 4, Parent = null, this = DecorView@89356e4[]
2021-02-13 17:53:36.253 3204-3204/ D/ViewRootImpl[WelcomeActivity]: hardware acceleration = true , fakeHwAccelerated = false, sRendererDisabled = false, forceHwAccelerated = false, sSystemRendererDisabled = false
2021-02-13 17:53:36.263 3204-3204/ V/PhoneWindow: DecorView setVisiblity: visibility = 0, Parent = android.view.ViewRootImpl@8540713, this = DecorView@89356e4[WelcomeActivity]
2021-02-13 17:53:36.288 3204-3204/ V/PhoneWindow: DecorView setVisiblity: visibility = 4, Parent = android.view.ViewRootImpl@f263b1d, this = DecorView@eb83192[MainActivity]
2021-02-13 17:53:36.308 3204-3306/ D/Surface: Surface::disconnect(this=0x9cd83800,api=1)
2021-02-13 17:53:36.311 3204-3204/ D/View: [Warning] assignParent to null: this = DecorView@eb83192[MainActivity]
2021-02-13 17:53:36.418 3204-3306/ D/Surface: Surface::connect(this=0x9cd83800,api=1)
2021-02-13 17:53:36.432 3204-3306/ D/Surface: Surface::setBufferCount(this=0x9cd83800,bufferCount=3)
2021-02-13 17:53:36.435 3204-3306/ D/Surface: Surface::allocateBuffers(this=0x9cd83800)
2021-02-13 17:53:36.467 3204-3306/ I/GED: ged_boost_gpu_freq, level 100, eOrigin 2, final_idx 2, oppidx_max 2, oppidx_min 0
2021-02-13 17:53:36.467 3204-3306/ I/chatty: uid=10206() RenderThread identical 1 line
2021-02-13 17:53:36.467 3204-3306/ I/GED: ged_boost_gpu_freq, level 100, eOrigin 2, final_idx 2, oppidx_max 2, oppidx_min 0
2021-02-13 17:53:40.475 3204-3306/ D/Surface: Surface::disconnect(this=0x9cd83800,api=1)
2021-02-13 17:53:40.498 3204-3204/ V/PhoneWindow: DecorView setVisiblity: visibility = 4, Parent = android.view.ViewRootImpl@8540713, this = DecorView@89356e4[WelcomeActivity]

You called startActivity(intent); twice when you the user signs out.. You need to remove the first one.

//sign the user out 
    navigationView.getMenu().findItem(R.id.nav_logout).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {

           fAuth.signOut();
           
            Intent intent = new Intent(HomeActivity.this,LoginActivity.class);

            //clear the onBackPress Data
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
            return true;
        }
    });

the problem was when the user signout firebase set the document snapshot to null to solve it I just catch that error however this might not be a proper solution but it work for now

try {
                        String name = documentSnapshot.getString("fullName");
                        navUsername.setText(name);
                    }catch (Exception a){
                   // throw error and continue
                    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM