Check Phone number availabilty in firebase realtime || and store value in tiny DB & user already exist to open direct home screen


I am going to check in firebase realtime database whether the phone number is available in the database or not. 
If the user's phone number is already in the database then send the user directly to the home screen. If the user's phone number is not in the database then For that we have taken a textview and a button and on clicking the button the phone number is stored in firebase.

Step 1: Setup Your Android Studio Project

Paste the given XML code in activity_main.xml file.

1. Activity (activity_main.xml)
1. XML Layout (activity_main.xml)
   
    
    <<?xml version="1.0" encoding="utf-8"?>>
<<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android">
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:background="#000024"
    android:padding="1dp">

    <Toolbar
        android:layout_width="match_parent"
        android:layout_gravity="center"
        android:background="#f7e9f0"
        android:layout_height="70dp">
        <TextView
            android:layout_width="wrap_content"
            android:text="ADA Guide"
            android:textColor="#ff3399"
            style="@style/Base.CardView"
            android:textSize="22dp"
            android:textStyle="bold"
            android:layout_height="wrap_content">

        </TextView>
    </Toolbar>
    <Toolbar
        android:layout_width="match_parent"
        android:layout_gravity="center"
        android:background="@color/white"
        android:layout_height="1dp"/>


    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="vertical"
        android:padding="10dp"
        android:background="#f7e9f0"
        android:gravity="center_vertical"
        android:layout_height="match_parent">




        <!-- Phone Number Input -->

        <androidx.cardview.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="250dp"
            android:layout_gravity="center"
            app:cardCornerRadius="20dp"
            android:id="@+id/chemi"
            android:padding="20dp"
            android:layout_margin="10dp"
            android:elevation="20dp"
            app:cardUseCompatPadding="true"
            app:cardBackgroundColor="#DBF5F0">

            <androidx.cardview.widget.CardView
                android:layout_width="match_parent"
                android:layout_height="60dp"
                android:layout_gravity="center"
                app:cardCornerRadius="10dp"
                android:id="@+id/chem"
                android:padding="20dp"
                android:layout_margin="10dp"
                android:elevation="200dp"
                app:cardBackgroundColor="#f7e9f0">

                <EditText
                    android:id="@+id/editTextPhone"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="Enter Phone Number"
                    android:textColorHint="@color/black"
                    android:inputType="phone"
                    android:layout_marginTop="10dp"
                    android:textColor="@color/black"
                    android:padding="10dp"
                    android:textSize="16sp"/>



            </androidx.cardview.widget.CardView>

            <!-- Button to Check Phone Number -->
            <Button
                android:id="@+id/buttonCheck"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:text="Continue"
                android:layout_marginTop="160dp"/>

        </androidx.cardview.widget.CardView>








    </LinearLayout>
    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_height="wrap_content"
        android:layout_marginTop="-60dp"
        android:visibility="gone" />


</LinearLayout>

    
    
    
    
    

Paste the given XML code in mainactivity.java file.

2. Activity (mainactivity.java)
2. (mainactivity.java)
    
    
    import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

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 MainActivity extends AppCompatActivity {

    private EditText phoneNumberInput;
    private Button checkButton;
    private ProgressBar progressBar;
    private DatabaseReference databaseReference;


    // Shared Preferences for TinyDB-like functionality
    SharedPreferences sharedPreferences;
    String sharedPrefPhoneKey = "storedPhoneNumber";

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

        phoneNumberInput = findViewById(R.id.editTextPhone);
        checkButton = findViewById(R.id.buttonCheck);
        progressBar = findViewById(R.id.progressBar);







        sharedPreferences = getSharedPreferences("TinyDB", Context.MODE_PRIVATE);

        // Initialize Firebase Realtime Database reference
        databaseReference = FirebaseDatabase.getInstance().getReference("phoneNumbers");

        // Check if a phone number is stored in SharedPreferences
        String storedPhoneNumber = sharedPreferences.getString(sharedPrefPhoneKey, null);
        if (storedPhoneNumber != null) {
            // Show progress bar while checking the stored phone number
            progressBar.setVisibility(View.VISIBLE);
            phoneNumberInput.setEnabled(false);
            checkButton.setEnabled(false);

            checkPhoneNumberInFirebase(storedPhoneNumber, true);
        }

        // On button click, check the entered phone number
        checkButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String enteredPhoneNumber = phoneNumberInput.getText().toString().trim();
                if (!enteredPhoneNumber.isEmpty()) {
                    // Show progress bar when checking phone number
                    progressBar.setVisibility(View.VISIBLE);
                    checkPhoneNumberInFirebase(enteredPhoneNumber, false);
                } else {
                    Toast.makeText(MainActivity.this, "Please enter a phone number", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void checkPhoneNumberInFirebase(String phoneNumber, boolean isAppReopen) {
        databaseReference.child(phoneNumber).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                // Hide progress bar once the data is fetched
                progressBar.setVisibility(View.GONE);
                phoneNumberInput.setEnabled(true);
                checkButton.setEnabled(true);

                if (dataSnapshot.exists()) {
                    // Phone number exists in Firebase, store it in SharedPreferences (TinyDB)
                    String name = dataSnapshot.child("Name").getValue(String.class);
                    String email = dataSnapshot.child("Email").getValue(String.class);

                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putString(sharedPrefPhoneKey, phoneNumber);
                    editor.apply();

                    if (isAppReopen) {
                        // If it's an app reopen, move to the second activity
                        navigateToSecondActivity(name, email);
                    } else {
                        Toast.makeText(MainActivity.this, "Phone number verified!", Toast.LENGTH_SHORT).show();
                        navigateToSecondActivity(name, email);
                    }
                } else {
                    // Phone number does not exist
                    Toast.makeText(MainActivity.this, "Phone number not found!", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                // Hide progress bar in case of an error
                progressBar.setVisibility(View.GONE);
                phoneNumberInput.setEnabled(true);
                checkButton.setEnabled(true);
                Log.e("MainActivity", "Database error: " + databaseError.getMessage());
            }
        });
    }

    private void navigateToSecondActivity(String name, String email) {
        Intent intent = new Intent(MainActivity.this, MainActivity2.class);
        intent.putExtra("name", name);
        intent.putExtra("email", email);
        startActivity(intent);
        finish();  // Close the current activity
    }
}
    
    
    
    
    

Paste the given java code in  mainactivity.java file.

1. Activity (mainactivity.java)



Post a Comment

0 Comments