Sadaqat Academy provides free learning courses, scholarships, guidance, Test Preparations, videos lectures, past papers for all class.

No More Tension: All is here

Guidances, TimeTable, News etc.

Wednesday, March 25, 2020

Development of Android MCQs App

In this project, we shall build an android MCQs App

Module 1: 

         We will using Firebase to store data (Question, Answer, User, Ranking...etc)

Be ready for learning

 - Firebase setup
 - Sign Up/ Sign In layout
 - Register / Login functional

Now create new Empty Project from Android Studio. Then,

Now we need to create new project on Firebase.

Click on Add Project
Create a project
Enter Project Name


Setting of android studio on Firebase and Vice Versa:
Create new android app on Firebase
While create new android app on Firebase, copy package name from MainActivity.java and put in Firebase as per requirement.
Now Steps to Read SHA1: open on android studio as

Copy SHA1 from 

Paste on Firebase as

Add FireBase to Your Android App
Download file when the above screen is come and put into your android studio as shown in above.

When you click on Continue Gradle, you need to follow Gradle instructions...

Copy code and paste as 

Next Step
    

Next Step:


Paste of file into android studio after downloading from Firebase


Now Make Sync Gradle.

We had done Firebase to our Android Project.

Now, we need to add some  required Libraries to add into android project such as firebase, design, etc... then we need to work with xml file and finally with java file... 


Libraries includes:
  • Firebase core
  • Firebase database
  • Material Edit Text
  • Card View


apply plugin: 'com.android.application'
android {
    compileSdkVersion 29    buildToolsVersion "29.0.3"
    defaultConfig {
        applicationId "com.example.generalknowledgequizapp"        minSdkVersion 16        targetSdkVersion 29        versionCode 1        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"    }

    buildTypes {
        release {
            minifyEnabled false            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'        }
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation 'com.google.firebase:firebase-core:17.2.3'    implementation 'com.google.firebase:firebase-database:19.2.1'    implementation 'com.google.firebase:firebase-analytics:17.2.3'    implementation 'com.rengwuxian.materialedittext:library:2.1.4'    implementation 'androidx.appcompat:appcompat:1.1.0'    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'    testImplementation 'junit:junit:4.13'    androidTestImplementation 'androidx.test.ext:junit:1.1.1'    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'    implementation 'androidx.cardview:cardview:1.0.0'}
apply plugin: 'com.google.gms.google-services'


Next, we will create Model

our user will have three main information
- User name
- password
- Email

Hence, Java-->Model-->User.java


package Model;

import android.text.Editable;

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;
    }
}



Now we will create layout for signup


<?xml version="1.0" encoding="utf-8"?><androidx.cardview.widget.CardView    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:layout_margin="8dp"
    app:cardElevation="4dp"    >
<LinearLayout    android:orientation="vertical"    android:layout_width="match_parent"    android:layout_height="wrap_content">

    <com.rengwuxian.materialedittext.MaterialEditText        android:id="@+id/edtNewUserName"        android:hint="User name"        android:textColorHint="@color/colorPrimary"        android:textColor="@color/colorPrimary"        android:textSize="24sp"        android:layout_width="match_parent"        android:layout_height="wrap_content"        app:met_baseColor="@color/colorPrimary"        app:met_floatingLabel="highlight"        app:met_singleLineEllipsis="true"        />

    <com.rengwuxian.materialedittext.MaterialEditText        android:id="@+id/edtNewPassword"        android:hint="Password"        android:textColorHint="@color/colorPrimary"        android:textColor="@color/colorPrimary"        android:textSize="24sp"        android:inputType="textPassword"        android:layout_width="match_parent"        android:layout_height="wrap_content"        app:met_baseColor="@color/colorPrimary"        app:met_floatingLabel="highlight"        app:met_singleLineEllipsis="true"        />

    <com.rengwuxian.materialedittext.MaterialEditText        android:id="@+id/edtNewEmail"        android:hint="Email"        android:textColorHint="@color/colorPrimary"        android:textColor="@color/colorPrimary"        android:textSize="24sp"        android:inputType="textEmailAddress"        android:layout_width="match_parent"        android:layout_height="wrap_content"        app:met_baseColor="@color/colorPrimary"        app:met_floatingLabel="highlight"        app:met_singleLineEllipsis="true"        />
</LinearLayout>


</androidx.cardview.widget.CardView>


Now, coding start...

package com.example.generalknowledgequizapp;

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

import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

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;
import com.rengwuxian.materialedittext.MaterialEditText;

import Model.User;

public class MainActivity extends AppCompatActivity
{
    MaterialEditText edtNewUser, edtNewPassword, edtNewEmail; // For Sign Up    MaterialEditText edtUser, edtPassword; // For Sign In
    Button btnSignUp, btnSignIn;

    FirebaseDatabase database;
    DatabaseReference users;

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

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

        edtUser = (MaterialEditText)findViewById(R.id.edtUser);
        edtPassword = (MaterialEditText)findViewById(R.id.edtPassword);

        btnSignIn = (Button)findViewById(R.id.btn_sign_in);
        btnSignUp = (Button)findViewById(R.id.btn_sign_up);

        btnSignUp.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {
                showSignUpDialog();
            }
        });
        btnSignIn.setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View v) {
                signIn(edtUser.getText().toString(),edtPassword.getText().toString());
            }
        });
    }

    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(MainActivity.this, "Login ok!", Toast.LENGTH_SHORT).show();
                        else                            Toast.makeText(MainActivity.this, "Wrong password", Toast.LENGTH_SHORT).show();
                    }
                    else                        {
                        Toast.makeText(MainActivity.this, "Please enter your user name", Toast.LENGTH_SHORT).show();
                    }
                }
                else                {
                    Toast.makeText(MainActivity.this, "User is not exists", Toast.LENGTH_SHORT).show();
                }

            }

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

            }
        });
    }



    private void showSignUpDialog() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
        alertDialog.setTitle("Sign Up");
        alertDialog.setMessage("Please Enter Required Information");

        LayoutInflater inflater = this.getLayoutInflater();
        View sign_up_layout = inflater.inflate(R.layout.sign_up_layout,null);


        edtNewUser = (MaterialEditText)sign_up_layout.findViewById(R.id.edtNewUserName);
        edtNewEmail = (MaterialEditText)sign_up_layout.findViewById(R.id.edtNewEmail);
        edtNewPassword = (MaterialEditText)sign_up_layout.findViewById(R.id.edtNewPassword);

        alertDialog.setView(sign_up_layout);
        alertDialog.setIcon(R.drawable.ic_account_circle_black_24dp);

        alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
            @Override            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        });

        alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
            @Override            public void onClick(DialogInterface dialogInterface, int i) {
                final User user = new User(edtNewUser.getText().toString(),
                        edtNewPassword.getText().toString(),
                        edtNewEmail.getText().toString());

                users.addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                        if (dataSnapshot.child(user.getUserName()).exists())
                            Toast.makeText(MainActivity.this, "User already exists !", Toast.LENGTH_SHORT).show();
                        else {
                            users.child(user.getUserName())
                                    .setValue(user);
                            Toast.makeText(MainActivity.this, "User registration success!", Toast.LENGTH_SHORT).show();
                        }

                    }

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

                    }
                });
                dialogInterface.dismiss();

            }

        });
        alertDialog.show();
        }
}

All had been done. Now go to firebase, click on database and update rules to true value and start signup work.










Share:

0 comments:

Post a Comment

Search This Blog

Recent Posts