Hello friends, in this blog, we will see how we can make User Authentication and apply Rules in Android by using Firebase as our Application back end.
package com.samset.firebaseauthentication;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.AppCompatButton;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private EditText etUserId, etPassword;
private AppCompatButton btnLogin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
initView();
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String userId = etUserId.getText().toString();
String password = etPassword.getText().toString();
loginUser(userId, password);
}
});
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.e("TAG", "User:signed_in:" + user.getUid());
startActivity(new Intent(MainActivity.this, DataUploadActivity.class));
} else {
// User is signed out
Log.e("TAG", "User:signed_out");
}
}
};
}
private void loginUser(String user, String pass) {
mAuth.signInWithEmailAndPassword(user, pass)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
Log.e("TAG", "signInWithEmail:onComplete:" + task.isSuccessful());
if (!task.isSuccessful()) {
Toast.makeText(MainActivity.this, "Login failed", Toast.LENGTH_SHORT).show();
Log.e("TAG", "signInWithEmail:failed", task.getException());
} else {
Log.e("TAG", "signInWithEmail:success");
Toast.makeText(MainActivity.this, "Successfully Login", Toast.LENGTH_SHORT).show();
startActivity(new Intent(MainActivity.this, DataUploadActivity.class));
}
}
});
}
@Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
@Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
private void initView() {
etPassword = (EditText) findViewById(R.id.et_password);
etUserId = (EditText) findViewById(R.id.et_username);
btnLogin = (AppCompatButton) findViewById(R.id.btnLogin);
}
}
Now see three tab go to SIGN IN METHOD
Integrating Firebase Auth
If you integrate firebase auth in your app so follow all instruction carefully. Fist you create a new Android Project.
Now you go to Tool menu Tool>Firebase and now you see right side open Firebase Assistense and now go to Authentication options and click "Email and password authentication".
Now you click Connect to firebase . When click Connect to Firebase then open browser if you not login, now login your account then click "Add firebase Authentication to your app". See your gradle and left side project structure add json file and code is automatic integrated and create your project on firebase check your project https://firebase.google.com/
Now add some code in your app's
MainActivity.java
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.AppCompatButton;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private EditText etUserId, etPassword;
private AppCompatButton btnLogin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
initView();
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String userId = etUserId.getText().toString();
String password = etPassword.getText().toString();
loginUser(userId, password);
}
});
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.e("TAG", "User:signed_in:" + user.getUid());
startActivity(new Intent(MainActivity.this, DataUploadActivity.class));
} else {
// User is signed out
Log.e("TAG", "User:signed_out");
}
}
};
}
private void loginUser(String user, String pass) {
mAuth.signInWithEmailAndPassword(user, pass)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
Log.e("TAG", "signInWithEmail:onComplete:" + task.isSuccessful());
if (!task.isSuccessful()) {
Toast.makeText(MainActivity.this, "Login failed", Toast.LENGTH_SHORT).show();
Log.e("TAG", "signInWithEmail:failed", task.getException());
} else {
Log.e("TAG", "signInWithEmail:success");
Toast.makeText(MainActivity.this, "Successfully Login", Toast.LENGTH_SHORT).show();
startActivity(new Intent(MainActivity.this, DataUploadActivity.class));
}
}
});
}
@Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
@Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
private void initView() {
etPassword = (EditText) findViewById(R.id.et_password);
etUserId = (EditText) findViewById(R.id.et_username);
btnLogin = (AppCompatButton) findViewById(R.id.btnLogin);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context="com.samset.firebaseauthentication.MainActivity">
<TextView
android:textColor="#000"
android:text="Firebase Authentication"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:id="@+id/et_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="100dp"
android:hint="User Id" />
<EditText
android:id="@+id/et_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="10dp"
android:hint="Password" />
<android.support.v7.widget.AppCompatButton
android:id="@+id/btnLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:text="Login" />
</LinearLayout>
<LinearLayout 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"
android:orientation="vertical"
tools:context="com.samset.firebaseauthentication.MainActivity">
<TextView
android:textColor="#000"
android:text="Firebase Authentication"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:id="@+id/et_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="100dp"
android:hint="User Id" />
<EditText
android:id="@+id/et_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="10dp"
android:hint="Password" />
<android.support.v7.widget.AppCompatButton
android:id="@+id/btnLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:text="Login" />
</LinearLayout>
Go to firebase console and click left menu Authentication.........
Now see three tab go to SIGN IN METHOD
Now click Email and Passsword row and enable toggle see below screenshot
Finally go to USERS tab and add your user account like abc@gmailcom and password 123456. see below screenshot
Now you complete authentication process launch your app and test firebase auth.
DataUploadActivity.java
package com.samset.firebaseauthentication;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.AppCompatButton;
import android.view.View;
import android.widget.EditText;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.HashMap;
import java.util.Map;
public class DataUploadActivity extends AppCompatActivity {
private DatabaseReference database;
private FirebaseAuth mAuth;
private EditText etUser, etcontact;
private AppCompatButton btnRegi,btnLogout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data_upload);
mAuth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance().getReference("Testing");
etcontact = (EditText) findViewById(R.id.et_contact);
etUser = (EditText) findViewById(R.id.et_user);
btnRegi = (AppCompatButton) findViewById(R.id.btnRegi);
btnLogout = (AppCompatButton) findViewById(R.id.btnlogout);
btnRegi.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Map<String,String> map=new HashMap<String, String>();
map.put("test",etUser.getText().toString());
database.child("User").setValue(map);
}
});
btnLogout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mAuth.signOut();
startActivity(new Intent(DataUploadActivity.this, MainActivity.class));
finish();
}
});
}
}
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.AppCompatButton;
import android.view.View;
import android.widget.EditText;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.HashMap;
import java.util.Map;
public class DataUploadActivity extends AppCompatActivity {
private DatabaseReference database;
private FirebaseAuth mAuth;
private EditText etUser, etcontact;
private AppCompatButton btnRegi,btnLogout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data_upload);
mAuth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance().getReference("Testing");
etcontact = (EditText) findViewById(R.id.et_contact);
etUser = (EditText) findViewById(R.id.et_user);
btnRegi = (AppCompatButton) findViewById(R.id.btnRegi);
btnLogout = (AppCompatButton) findViewById(R.id.btnlogout);
btnRegi.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Map<String,String> map=new HashMap<String, String>();
map.put("test",etUser.getText().toString());
database.child("User").setValue(map);
}
});
btnLogout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mAuth.signOut();
startActivity(new Intent(DataUploadActivity.this, MainActivity.class));
finish();
}
});
}
}
dataupload_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
tools:context="com.samset.firebaseauthentication.DataUploadActivity">
<LinearLayout
android:gravity="center"
android:layout_gravity="center"
android:orientation="vertical"
android:layout_width="368dp"
android:layout_height="wrap_content"
tools:layout_editor_absoluteY="0dp"
tools:layout_editor_absoluteX="8dp">
<EditText
android:id="@+id/et_user"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:hint="Name" />
<EditText
android:id="@+id/et_contact"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="10dp"
android:inputType="number"
android:hint="Contact" />
<android.support.v7.widget.AppCompatButton
android:id="@+id/btnRegi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:text="Send Data" />
<android.support.v7.widget.AppCompatButton
android:id="@+id/btnlogout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:text="Logout" />
</LinearLayout>
</android.support.constraint.ConstraintLayout>
<android.support.constraint.ConstraintLayout 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"
tools:context="com.samset.firebaseauthentication.DataUploadActivity">
<LinearLayout
android:gravity="center"
android:layout_gravity="center"
android:orientation="vertical"
android:layout_width="368dp"
android:layout_height="wrap_content"
tools:layout_editor_absoluteY="0dp"
tools:layout_editor_absoluteX="8dp">
<EditText
android:id="@+id/et_user"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:hint="Name" />
<EditText
android:id="@+id/et_contact"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="10dp"
android:inputType="number"
android:hint="Contact" />
<android.support.v7.widget.AppCompatButton
android:id="@+id/btnRegi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:text="Send Data" />
<android.support.v7.widget.AppCompatButton
android:id="@+id/btnlogout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:text="Logout" />
</LinearLayout>
</android.support.constraint.ConstraintLayout>
See firebase database if user login with auth
Thank you