Android Knowledge

Store & Display Profile Data in Navigation Drawer in Android Studio using Java

Table of Contents

The navigation drawer is a side menu panel that consists of different navigating fragments. The menu is provided at the left of the screen which opens and closes as per your user requirements, There are different fragments present in the menu, so when you click on any one fragment it will lead you to a different screen.

The best example would be Gmail App, when you click on the menu a side panel opens up that consists of All Inboxes, Primary, Promotions, and Socials.

Download the Logo and Background

Logo:

Header Background:

Step-by-Step Implementation

Step 1: Open Android Studio, Create New Project, Choose Empty Activity and Name the Project “Navigation Drawer”.

navigation drawer menu

Step 2: colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="purple_200">#FFBB86FC</color>
    <color name="purple_500">#FF6200EE</color>
    <color name="purple_700">#FF3700B3</color>
    <color name="teal_200">#FF03DAC5</color>
    <color name="teal_700">#FF018786</color>
    <color name="black">#FF000000</color>
    <color name="white">#FFFFFFFF</color>
    <color name="lavender">#8692f7</color>
</resources>

Step 3: strings.xml

<resources>
    <string name="app_name">Navigation Drawer</string>
    <string name="open_nav">Open Navigation Drawer</string>
    <string name="close_nav">Close Navigation Drawer</string>
</resources>

Step 4: themes.xml

<resources xmlns:tools="http://schemas.android.com/tools">
    <!-- Base application theme. -->
    <style name="Theme.NavDrawer" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
        <!-- Primary brand color. -->
        <item name="colorPrimary">@color/lavender</item>
        <item name="colorPrimaryVariant">@color/lavender</item>
        <item name="colorOnPrimary">@color/white</item>
        <!-- Secondary brand color. -->
        <item name="colorSecondary">@color/teal_200</item>
        <item name="colorSecondaryVariant">@color/teal_700</item>
        <item name="colorOnSecondary">@color/black</item>
        <!-- Status bar color. -->
        <item name="android:statusBarColor">?attr/colorPrimaryVariant</item>
        <!-- Customize your theme here. -->
    </style>
    <style name="roundedImageViewRounded">
        <item name="cornerFamily">rounded</item>
        <item name="cornerSize">50%</item>
    </style>

    <style name="Theme.MainActivity" parent="Theme.MaterialComponents.DayNight.NoActionBar">
        <!-- Primary brand color. -->
        <item name="colorPrimary">@color/lavender</item>
        <item name="colorPrimaryVariant">@color/lavender</item>
        <item name="colorOnPrimary">@color/white</item>
        <!-- Secondary brand color. -->
        <item name="colorSecondary">@color/teal_200</item>
        <item name="colorSecondaryVariant">@color/teal_700</item>
        <item name="colorOnSecondary">@color/black</item>
        <!-- Status bar color. -->
        <item name="android:statusBarColor">?attr/colorPrimaryVariant</item>
        <!-- Customize your theme here. -->
    </style>
</resources>

Step 5: AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.NavigationDrawer"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:theme="@style/Theme.MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            <meta-data
                android:name="android.app.lib_name"
                android:value="" />
        </activity>
    </application>

</manifest>

lavender_border.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <stroke
        android:width="2dp"
        android:color="@color/lavender"/>

    <corners
        android:radius="30dp"/>

</shape>

Step 6: Add Images and Vector Asset in Drawables Folder.

I have added two images, the first is the logo image and the second is the header image.

Further, I have added five vector assets. Icon Name – Home, Settings, Info(About), Exit(Logout), Share, Person.

Step 7: Create four blank fragments and name them as follows:

HomeFragment, SettingsFragment, AboutFragment, ShareFragment.

Step 8: nav_menu.xml

Right-click on res -> Android Resource Directory and select the menu then right-click on the menu directory and click on New -> Menu Resource File and name “nav_menu”.

<?xml version="1.0" encoding="utf-8"?>
<menu
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:showIn = "navigation_view">

    <group
        android:checkableBehavior="single">

        <item
            android:id="@+id/nav_home"
            android:icon="@drawable/nav_home"
            android:title="Home"/>

        <item
            android:id="@+id/nav_settings"
            android:icon="@drawable/nav_settings"
            android:title="Settings"/>

        <item
            android:id="@+id/nav_share"
            android:icon="@drawable/nav_share"
            android:title="Share"/>

        <item
            android:id="@+id/nav_about"
            android:icon="@drawable/nav_about"
            android:title="About Us"/>
    </group>
    <item
        android:title="">

        <menu>
            <item
                android:id="@+id/nav_logout"
                android:icon="@drawable/nav_logout"
                android:title="Logout"/>
        </menu>

    </item>

</menu>

Step 9: nav_header.xml

Right-click on layout -> Layout Resource File -> nav_header

<?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="176dp"
    android:background="@drawable/headerbkg"
    android:gravity="bottom"
    android:padding="16dp"
    android:orientation="vertical"
    android:theme="@style/ThemeOverlay.AppCompat.Dark">

    <androidx.cardview.widget.CardView
        android:layout_width="70dp"
        android:layout_height="70dp"
        app:cardCornerRadius="35dp"
        app:cardBackgroundColor="@color/white">

        <com.google.android.material.imageview.ShapeableImageView
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:id="@+id/navImage"
            android:src="@drawable/aklogo"
            android:scaleType="centerCrop"
            app:shapeAppearanceOverlay="@style/roundedImageViewRounded"/>

    </androidx.cardview.widget.CardView>

    <TextView
        android:id="@+id/navName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/white"
        android:text="Name"
        android:textStyle="bold"/>

    <TextView
        android:id="@+id/navEmail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/white"
        android:layout_marginBottom="16dp"
        android:textSize="14sp"
        android:text="email" />

</LinearLayout>

Step 10: activity_main.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="176dp"
    android:background="@drawable/headerbkg"
    android:gravity="bottom"
    android:padding="16dp"
    android:orientation="vertical"
    android:theme="@style/ThemeOverlay.AppCompat.Dark">

    <androidx.cardview.widget.CardView
        android:layout_width="70dp"
        android:layout_height="70dp"
        app:cardCornerRadius="35dp"
        app:cardBackgroundColor="@color/white">

        <com.google.android.material.imageview.ShapeableImageView
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:id="@+id/navImage"
            android:src="@drawable/aklogo"
            android:scaleType="centerCrop"
            app:shapeAppearanceOverlay="@style/roundedImageViewRounded"/>

    </androidx.cardview.widget.CardView>

    <TextView
        android:id="@+id/navName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/white"
        android:text="Name"
        android:textStyle="bold"/>

    <TextView
        android:id="@+id/navEmail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/white"
        android:layout_marginBottom="16dp"
        android:textSize="14sp"
        android:text="email" />

</LinearLayout>

activity_upload.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    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="match_parent"
    android:orientation="vertical"
    tools:context=".UploadActivity">


    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="130dp"
        android:layout_marginEnd="20dp"
        android:layout_marginStart="20dp"
        app:cardCornerRadius="30dp"
        app:cardElevation="20dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:layout_gravity="center_horizontal"
            android:background = "@drawable/lavender_border"
            android:padding="20dp">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Edit Profile"
                android:layout_gravity="center"
                android:textSize="30sp"
                android:textColor="@color/lavender"/>

            <ImageView
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:scaleType="fitXY"
                android:layout_gravity="center"
                android:layout_marginTop="20dp"
                android:id="@+id/uploadImage"
                android:src="@drawable/baseline_person_24" />

            <EditText
                android:layout_width="match_parent"
                android:layout_height="60dp"
                android:id="@+id/uploadName"
                android:background="@drawable/lavender_border"
                android:layout_marginTop="20dp"
                android:padding="16dp"
                android:hint="Enter name"
                android:gravity="start|center_vertical"
                android:textColor="@color/lavender"/>

            <EditText
                android:layout_width="match_parent"
                android:layout_height="60dp"
                android:id="@+id/uploadEmail"
                android:background="@drawable/lavender_border"
                android:layout_marginTop="20dp"
                android:padding="16dp"
                android:hint="Enter email"
                android:gravity="start|center_vertical"
                android:textColor="@color/lavender"/>


            <Button
                android:layout_width="match_parent"
                android:layout_height="60dp"
                android:text="Save"
                android:id="@+id/saveButton"
                android:textSize="18sp"
                android:layout_marginTop="20dp"
                android:backgroundTint="@color/lavender"
                app:cornerRadius = "20dp"/>

        </LinearLayout>

    </androidx.cardview.widget.CardView>

</ScrollView>

Step 11: All fragments.xml

fragment_home.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".HomeFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Home Fragment"
        android:textSize="30sp"
        android:layout_centerInParent="true"
        android:textColor="@color/lavender"/>

</RelativeLayout>

fragment_about.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".AboutFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="About Us Fragment"
        android:textSize="30sp"
        android:layout_centerInParent="true"
        android:textColor="@color/lavender"/>

</RelativeLayout>

fragment_settings.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SettingsFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Settings Fragment"
        android:textSize="30sp"
        android:layout_centerInParent="true"
        android:textColor="@color/lavender"/>

</RelativeLayout>

fragment_share.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ShareFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Share Fragment"
        android:textSize="30sp"
        android:layout_centerInParent="true"
        android:textColor="@color/lavender"/>

</RelativeLayout>

Step 12: Clear unnecessary code in all the Fragments.java

Check our Youtube Video: Navigation Drawer Menu in Android Studio using Java.

Step 13: Java Files

ModelClass.java

package com.example.navdrawer;

import android.graphics.Bitmap;

public class ModelClass {
    private String name, email;
    private Bitmap image;

    public ModelClass(String name, String email, Bitmap image) {
        this.name = name;
        this.email = email;
        this.image = image;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

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

    public Bitmap getImage() {
        return image;
    }

    public void setImage(Bitmap image) {
        this.image = image;
    }
}

DBHelper.java

package com.example.navdrawer;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Bitmap;
import android.widget.Toast;

import java.io.ByteArrayOutputStream;

import androidx.annotation.Nullable;

public class DBHelper extends SQLiteOpenHelper {

    Context context;
    private static String DB_NAME = "user.db";
    private static int DB_VERSION = 1;
    private ByteArrayOutputStream byteArrayOutputStream;
    private byte[] byteImage;

    private static String createTableQuery = "Create table LoginUser(username TEXT " +
            ",email TEXT " +
            ",image BLOB)";

    public DBHelper(@Nullable Context context) {
        super(context, DB_NAME, null, DB_VERSION);
        this.context = context;
    }

    @Override
    public void onCreate(SQLiteDatabase database) {
        database.execSQL(createTableQuery);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

    }
    public void storeData(ModelClass modelClass){
        SQLiteDatabase database = this.getWritableDatabase();
        Bitmap bitmapImage = modelClass.getImage();

        byteArrayOutputStream = new ByteArrayOutputStream();
        bitmapImage.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
        byteImage = byteArrayOutputStream.toByteArray();

        ContentValues contentValues = new ContentValues();
        contentValues.put("username", modelClass.getName());
        contentValues.put("email", modelClass.getEmail());
        contentValues.put("image", byteImage);

        long checkQuery = database.insert("LoginUser", null, contentValues);

        if (checkQuery != -1){
            Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show();
            database.close();
        } else {
            Toast.makeText(context, "Something went wrong", Toast.LENGTH_SHORT).show();
        }
    }
    public Cursor getUser(){
        SQLiteDatabase database = this.getReadableDatabase();
        Cursor cursor = database.rawQuery("Select * from LoginUser", null);
        return cursor;
    }
}

UploadActivity.java

package com.example.navdrawer;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.IOException;

public class UploadActivity extends AppCompatActivity {

    EditText uploadName, uploadEmail;
    ImageView uploadImage;
    Button saveButton;
    private Uri uri;
    private Bitmap bitmapImage;
    DBHelper dbHelper;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload);

        uploadEmail = findViewById(R.id.uploadEmail);
        uploadImage = findViewById(R.id.uploadImage);
        uploadName = findViewById(R.id.uploadName);
        saveButton = findViewById(R.id.saveButton);
        dbHelper = new DBHelper(this);

        ActivityResultLauncher<Intent> activityResultLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        if (result.getResultCode() == Activity.RESULT_OK){
                            Intent data = result.getData();
                            assert data != null;
                            uri = data.getData();
                            try {
                                bitmapImage = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
                            } catch (IOException e) {
                                Toast.makeText(UploadActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                            uploadImage.setImageBitmap(bitmapImage);
                        } else {
                            Toast.makeText(UploadActivity.this, "No Image Selected", Toast.LENGTH_SHORT).show();
                        }
                    }
                }
        );

        uploadImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    Intent intent = new Intent();
                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    activityResultLauncher.launch(intent);
                } catch (Exception e){
                    Toast.makeText(UploadActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });

        saveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                storeImage();
            }
        });
    }

    private void storeImage(){
        if (!uploadName.getText().toString().isEmpty() && !uploadEmail.getText().toString().isEmpty()
        && uploadImage.getDrawable() != null && bitmapImage != null){

            dbHelper.storeData(new ModelClass(uploadName.getText().toString(), uploadEmail.getText().toString(), bitmapImage));
            Intent intent = new Intent(UploadActivity.this, MainActivity.class);
            startActivity(intent);
        } else {
            Toast.makeText(this, "Fields are mandatory", Toast.LENGTH_SHORT).show();
        }
    }
}

MainActivity.java

package com.example.navdrawer;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{

    private DrawerLayout drawerLayout;
    FloatingActionButton fab;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

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

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
                R.string.nav_open, R.string.nav_close);
        drawerLayout.addDrawerListener(toggle);
        toggle.syncState();

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                    new HomeFragment()).commit();
            navigationView.setCheckedItem(R.id.nav_home);
        }

        View header = navigationView.getHeaderView(0);
        ImageView navImage = (ImageView) header.findViewById(R.id.navImage);
        TextView navName = (TextView) header.findViewById(R.id.navName);
        TextView navEmail = (TextView) header.findViewById(R.id.navEmail);

        DBHelper dbHelper = new DBHelper(this);
        Cursor cursor = dbHelper.getUser();

        if (cursor.getCount() == 0){
            Toast.makeText(this, "No Profile Details", Toast.LENGTH_SHORT).show();
        } else {
            while (cursor.moveToNext()){
                navName.setText(""+cursor.getString(0));
                navEmail.setText(""+cursor.getString(1));
                byte[] imageByte = cursor.getBlob(2);

                Bitmap bitmap = BitmapFactory.decodeByteArray(imageByte,0,imageByte.length);
                navImage.setImageBitmap(bitmap);
            }
        }

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, UploadActivity.class);
                startActivity(intent);
            }
        });
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.nav_home:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new HomeFragment()).commit();
                break;
            case R.id.nav_settings:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new SettingsFragment()).commit();
                break;
            case R.id.nav_share:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new ShareFragment()).commit();
                break;
            case R.id.nav_about:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
                        new AboutFragment()).commit();
                break;
            case R.id.nav_logout:
                Toast.makeText(this, "Logout!", Toast.LENGTH_SHORT).show();
                break;
        }

        drawerLayout.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onBackPressed() {
        if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
            drawerLayout.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }
}

Output

navigation drawer menu android studio

AK Bonus Points

If you have any queries or errors, please feel free to comment below 😉

Check our previous post: Login and SignUp in Android Studio using Firebase

Check our Youtube Video: Navigation Drawer Menu in Android Studio using Java

Save Profile Data in SQLite Database and Display in Navigation Bar Menu in Android Studio