Cavad
Cavad

Reputation: 75

How can I retrieve Logged user data to nav header as Username in Android studio project with Firebase

I'm new for Android Project. I create project with Firebase. In this project I want to add Logged User name's to textview in nav header. I use for login or registration Model options. But I can't. Does anyone have any experience with this? My firebase database datas shown like this. enter image description here

I want make like this enter image description here

My Home Activity is this

package com.cavad.firebaseproject;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;


public class Home extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, 
 R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) 
 findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    Fragment category = new CategoryFragment();
    this.setDefaultFragment(category);
 }

 private void setDefaultFragment(Fragment defaultFragment)
 {
    this.replaceFragment(defaultFragment);
 }

 public void replaceFragment(Fragment destFragment)
 {
    FragmentManager fragmentManager = this.getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = 
 fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.category, destFragment);
    fragmentTransaction.commit();
 }

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@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 onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_camera) {
        // Handle the camera action
    } else if (id == R.id.nav_gallery) {

    } else if (id == R.id.nav_slideshow) {

    } else if (id == R.id.nav_manage) {

    } else if (id == R.id.nav_share) {

    } else if (id == R.id.nav_send) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
  }
 }

My nav_header xml file is this nav_header_home.xml //

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimaryDark"
android:gravity="bottom"
android:orientation="vertical"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:theme="@style/ThemeOverlay.AppCompat.Dark">

<TextView
    android:id="@+id/userName"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:gravity="center"
    android:text="userName"
    android:textColor="@color/white"
    android:textSize="20sp"
    android:layout_marginTop="15dp"
    android:layout_marginBottom="10dp"
    android:textStyle="bold"/>

</LinearLayout>   

My Model class is this

 package com.cavad.firebaseproject.Model;

public class User {

private String userName;
private String password;
private String email;

public User(){
}

public User(String userName, String password, String email) {
    this.userName = userName;
    this.password = password;
    this.email = email;
}

public String getUserName() {
    return userName;
}

public void setUserName(String userName) {
    this.userName = userName;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}
}

My Firebase database rules is this

  {
    "rules": {
    ".read": true,
    ".write": true
    }
   }

My Login activity is this

 package com.cavad.firebaseproject;

 import android.content.Intent;
 import android.os.Bundle;
 import android.support.annotation.NonNull;
 import android.support.v4.app.Fragment;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.EditText;
 import android.widget.ImageView;
 import android.widget.Toast;

 import com.cavad.firebaseproject.Model.User;
 import com.google.firebase.database.DataSnapshot;
 import com.google.firebase.database.DatabaseError;
 import com.google.firebase.database.DatabaseReference;
 import com.google.firebase.database.FirebaseDatabase;
 import com.google.firebase.database.ValueEventListener;
public class Login extends Fragment {

EditText user, password;
ImageView signin;

FirebaseDatabase database;
DatabaseReference users;

public Login() {

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_login, container, 
 false);

    database = FirebaseDatabase.getInstance();
    users = database.getReference("Users");

    user = view.findViewById(R.id.name);
    password = view.findViewById(R.id.password);
    signin = view.findViewById(R.id.submit);

    signin.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v){

  signin(user.getText().toString(),password.getText().toString());
        }
    });

    return view;
   }
  private void signin(final String user, final String pwd){
    users.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            if (dataSnapshot.child(user).exists())
            {
                if (!user.isEmpty())
                {
                    User login = 
  dataSnapshot.child(user).getValue(User.class);
                    if (login.getPassword().equals(pwd))
                    {
                        Toast.makeText(getActivity(), "Uğurla daxil 
 oldunuz", Toast.LENGTH_SHORT).show();
                        startActivity(new 
 Intent(getActivity().getApplication(), Home.class));

                    }
                    else
                        Toast.makeText(getActivity(), "Zəhmət olmasa 
 Şifrəni düzgün daxil edin", Toast.LENGTH_SHORT).show();
                }
                else
                {
                    Toast.makeText(getActivity(), "Zəhmət olmasa 
 İstifadəçi adınızı daxil edin", Toast.LENGTH_SHORT).show();
                }
            }
            else
                Toast.makeText(getActivity(), "Belə bir istifadəçi adı 
   tapılmadı !!!", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
  }
 }

My Login acticity xml is this

 <LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".Login"
android:background="@color/colorPrimaryDark"
android:orientation="vertical">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:weightSum="2"
    android:layout_marginTop="7dp"
    android:layout_marginBottom="7dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="7dp"
            android:layout_marginBottom="7dp"
            app:hintEnabled="false"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp">

            <EditText
                android:id="@+id/name"
                android:layout_width="match_parent"
                android:layout_height="48dp"
                android:hint="@string/name"
                android:inputType="text"
                android:textSize="20sp"
                android:drawableStart="@drawable/ic_user"
                android:drawableLeft="@drawable/ic_user"
                android:drawablePadding="10dp"
                android:background="@drawable/edttext_background"
                android:paddingRight="10dp"
                android:paddingLeft="10dp"/>
        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="7dp"
            android:layout_marginBottom="7dp"
            app:hintEnabled="false"
            app:passwordToggleDrawable="@drawable/visibility"
            app:passwordToggleEnabled="true"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp">

            <EditText
                android:id="@+id/password"
                android:layout_width="match_parent"
                android:layout_height="48dp"
                android:textSize="20sp"
                android:inputType="textPassword"
                android:hint="@string/password"
                android:drawableStart="@drawable/ic_lock"
                android:drawableLeft="@drawable/ic_lock"
                android:background="@drawable/edttext_background"
                android:drawablePadding="10dp"
                android:paddingRight="10dp"
                android:paddingLeft="10dp" />
        </android.support.design.widget.TextInputLayout>

        <ImageView
            android:id="@+id/submit"
            android:layout_width="48dp"
            android:layout_height="48dp"
            android:gravity="center"
            android:layout_gravity="center"
            android:src="@drawable/ic_check"
            android:background="@drawable/check_background"
            android:layout_marginTop="15dp"
            android:layout_marginBottom="15dp"/>

    </LinearLayout>

</LinearLayout>

</LinearLayout>

Upvotes: 2

Views: 3971

Answers (3)

sumanth.js
sumanth.js

Reputation: 424

retrive logged user data from firebase realtime database in navigation header

// xml file

    <TextView
        android:id="@+id/your_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="@font/gotham_bold"
        android:text="User Name"
        android:textColor="@color/brown"
        android:textSize="18sp"
     />

        <TextView
            android:id="@+id/user_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:fontFamily="@font/gotham_book"
            android:text="User Name"
            android:textColor="@color/brown"
           android:textSize="15sp"
            android:layout_gravity="center"
            />

// java code

    firebaseDatabase.getReference().child("Users").child(auth.getUid())
            .addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot snapshot) {
                   
                    User user = snapshot.getValue(User.class);

                    View header = navigationView.getHeaderView(0);

                    name = header.findViewById(R.id.your_name);
                    username = header.findViewById(R.id.user_name);

                    name.setText(user.getName1());
                    username.setText("@" + user.getUsername1());
                }

                @Override
                public void onCancelled(@NonNull DatabaseError error) {

                }
            });

Upvotes: 0

loose .rival
loose .rival

Reputation: 81

If you want to retrieve logged user email, username and pictures stored in the real-time database and show them in the navigation header then you can simply follow this:

    NavigationView navigationView = findViewById(R.id.nav_view);
        database = FirebaseDatabase.getInstance();
        auth = FirebaseAuth.getInstance();

    database.getReference().child("Users").child(auth.getUid())
            .addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot snapshot) {
                //we have Users class which contain user properties and methods.
                    User user = snapshot.getValue(User.class);

                    View header = navigationView.getHeaderView(0);
                    nav_email = header.findViewById(R.id.nav_email);
                    nav_username = header.findViewById(R.id.nav_username);
                    nav_profile = header.findViewById(R.id.nav_profilePic);

            Picasso.get().load(user.getProfilePic()).placeholder(R.drawable.avatar).into(nav_profile);
                    nav_email.setText(user.getMail());
                    nav_username.setText(user.getUserName());
                }

                @Override
                public void onCancelled(@NonNull DatabaseError error) {

                }
            });

If you want to use Picasso to retrieve an image from the real time database and then set it on the nav header imageview then add the following dependency in your bundle Gradle module file :

    implementation 'com.squareup.picasso:picasso:2.71828'

Then you can use Picasso in your project.

Upvotes: 0

Kaveri
Kaveri

Reputation: 1088

Step 1. Get the current signed in user:-

The recommended way to get the current user is by calling the getCurrentUser method. If no user is signed in, getCurrentUser returns null.Example :-

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
// Name, email address, and profile photo Url
String name = user.getDisplayName();
String email = user.getEmail();
Uri photoUrl = user.getPhotoUrl();

// Check if user's email is verified
boolean emailVerified = user.isEmailVerified();

// The user's ID, unique to the Firebase project. Do NOT use this value to
// authenticate with your backend server, if you have one. Use
// FirebaseUser.getIdToken() instead.
String uid = user.getUid();
}

For More check the link

Manage Users in Firebase

Step 2. Set it to the navigation view header:- You can get the textview like:-

NavigationView navigationView = (NavigationView) findViewById(R.id.your_nav_view_id);
View header = navigationView.getHeaderView(0)
TextView text = (TextView) header.findViewById(R.id.textView);

Upvotes: 5

Related Questions