1 ) Activity Login
<?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:id="@+id/nestedScrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorBackground"
android:paddingBottom="20dp"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:paddingTop="20dp"
tools:context=".LoginActivity">
<android.support.v7.widget.LinearLayoutCompat
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.TextInputLayout
android:id="@+id/textInputLayoutEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp">
<android.support.design.widget.TextInputEditText
android:id="@+id/textInputEditTextEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/hint_email"
android:inputType="text"
android:maxLines="1"
android:textColor="@android:color/white" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/textInputLayoutPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp">
<android.support.design.widget.TextInputEditText
android:id="@+id/textInputEditTextPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/hint_password"
android:inputType="textPassword"
android:maxLines="1"
android:textColor="@android:color/white" />
</android.support.design.widget.TextInputLayout>
<android.support.v7.widget.AppCompatButton
android:id="@+id/appCompatButtonLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:background="@color/colorTextHint"
android:text="@string/text_login" />
<android.support.v7.widget.AppCompatTextView
android:id="@+id/textViewLinkRegister"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:gravity="center"
android:text="@string/text_not_member"
android:textSize="16dp" />
</android.support.v7.widget.LinearLayoutCompat>
</LinearLayout>
2 ) Activity Register
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/nestedScrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorBackground"
android:paddingBottom="20dp"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:paddingTop="20dp"
tools:context=".LoginActivity">
<android.support.v7.widget.LinearLayoutCompat
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.TextInputLayout
android:id="@+id/textInputLayoutName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp">
<android.support.design.widget.TextInputEditText
android:id="@+id/textInputEditTextName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/hint_name"
android:inputType="text"
android:maxLines="1"
android:textColor="@android:color/black" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/textInputLayoutEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp">
<android.support.design.widget.TextInputEditText
android:id="@+id/textInputEditTextEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/hint_email"
android:inputType="text"
android:maxLines="1"
android:textColor="@android:color/black" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/textInputLayoutPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp">
<android.support.design.widget.TextInputEditText
android:id="@+id/textInputEditTextPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/hint_password"
android:inputType="textPassword"
android:maxLines="1"
android:textColor="@android:color/black" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/textInputLayoutConfirmPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp">
<android.support.design.widget.TextInputEditText
android:id="@+id/textInputEditTextConfirmPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/hint_confirm_password"
android:inputType="textPassword"
android:maxLines="1"
android:textColor="@android:color/black" />
</android.support.design.widget.TextInputLayout>
<android.support.v7.widget.AppCompatButton
android:id="@+id/appCompatButtonRegister"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:background="@color/colorTextHint"
android:text="@string/text_register" />
<android.support.v7.widget.AppCompatTextView
android:id="@+id/appCompatTextViewLoginLink"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:gravity="center"
android:text="Already a member? Login"
android:textSize="16dp" />
</android.support.v7.widget.LinearLayoutCompat>
</android.support.v4.widget.NestedScrollView>
3 ) Database Handler
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.example.discusit.sqlitedatabasedemowithapicalling.model.User;
import java.util.ArrayList;
import java.util.List;
public class DatabaseHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "UserManager.db";
// User table name
private static final String TABLE_USER = "user";
// User Table Columns names
private static final String COLUMN_USER_ID = "user_id";
private static final String COLUMN_USER_NAME = "user_name";
private static final String COLUMN_USER_EMAIL = "user_email";
private static final String COLUMN_USER_PASSWORD = "user_password";
// create table sql query
private String CREATE_USER_TABLE = "CREATE TABLE " + TABLE_USER + "("
+ COLUMN_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COLUMN_USER_NAME + " TEXT,"
+ COLUMN_USER_EMAIL + " TEXT," + COLUMN_USER_PASSWORD + " TEXT" + ")";
// drop table sql query
private String DROP_USER_TABLE = "DROP TABLE IF EXISTS " + TABLE_USER;
/**
* Constructor
*
* @param context
*/
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_USER_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//Drop User Table if exist
db.execSQL(DROP_USER_TABLE);
// Create tables again
onCreate(db);
}
/**
* This method is to create user record
*
* @param user
*/
public void addUser(User user) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_USER_NAME, user.getName());
values.put(COLUMN_USER_EMAIL, user.getEmail());
values.put(COLUMN_USER_PASSWORD, user.getPassword());
// Inserting Row
db.insert(TABLE_USER, null, values);
db.close();
}
/**
* This method is to fetch all user and return the list of user records
*
* @return list
*/
public List<User> getAllUser() {
// array of columns to fetch
String[] columns = {
COLUMN_USER_ID,
COLUMN_USER_EMAIL,
COLUMN_USER_NAME,
COLUMN_USER_PASSWORD
};
// sorting orders
String sortOrder =
COLUMN_USER_NAME + " ASC";
List<User> userList = new ArrayList<User>();
SQLiteDatabase db = this.getReadableDatabase();
// query the user table
/**
* Here query function is used to fetch records from user table this function works like we use sql query.
* SQL query equivalent to this query function is
* SELECT user_id,user_name,user_email,user_password FROM user ORDER BY user_name;
*/
Cursor cursor = db.query(TABLE_USER, //Table to query
columns, //columns to return
null, //columns for the WHERE clause
null, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
sortOrder); //The sort order
// Traversing through all rows and adding to list
if (cursor.moveToFirst()) {
do {
User user = new User();
user.setId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(COLUMN_USER_ID))));
user.setName(cursor.getString(cursor.getColumnIndex(COLUMN_USER_NAME)));
user.setEmail(cursor.getString(cursor.getColumnIndex(COLUMN_USER_EMAIL)));
user.setPassword(cursor.getString(cursor.getColumnIndex(COLUMN_USER_PASSWORD)));
// Adding user record to list
userList.add(user);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
// return user list
return userList;
}
/**
* This method to update user record
*
* @param user
*/
public void updateUser(User user) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_USER_NAME, user.getName());
values.put(COLUMN_USER_EMAIL, user.getEmail());
values.put(COLUMN_USER_PASSWORD, user.getPassword());
// updating row
db.update(TABLE_USER, values, COLUMN_USER_ID + " = ?",
new String[]{String.valueOf(user.getId())});
db.close();
}
/**
* This method is to delete user record
*
* @param user
*/
public void deleteUser(User user) {
SQLiteDatabase db = this.getWritableDatabase();
// delete user record by id
db.delete(TABLE_USER, COLUMN_USER_ID + " = ?",
new String[]{String.valueOf(user.getId())});
db.close();
}
/**
* This method to check user exist or not
*
* @param email
* @return true/false
*/
public boolean checkUser(String email) {
// array of columns to fetch
String[] columns = {
COLUMN_USER_ID
};
SQLiteDatabase db = this.getReadableDatabase();
// selection criteria
String selection = COLUMN_USER_EMAIL + " = ?";
// selection argument
String[] selectionArgs = {email};
// query user table with condition
/**
* Here query function is used to fetch records from user table this function works like we use sql query.
* SQL query equivalent to this query function is
* SELECT user_id FROM user WHERE user_email = 'jack@androidtutorialshub.com';
*/
Cursor cursor = db.query(TABLE_USER, //Table to query
columns, //columns to return
selection, //columns for the WHERE clause
selectionArgs, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
null); //The sort order
int cursorCount = cursor.getCount();
cursor.close();
db.close();
if (cursorCount > 0) {
return true;
}
return false;
}
/**
* This method to check user exist or not
*
* @param email
* @param password
* @return true/false
*/
public boolean checkUser(String email, String password) {
// array of columns to fetch
String[] columns = {
COLUMN_USER_ID
};
SQLiteDatabase db = this.getReadableDatabase();
// selection criteria
String selection = COLUMN_USER_EMAIL + " = ?" + " AND " + COLUMN_USER_PASSWORD + " = ?";
// selection arguments
String[] selectionArgs = {email, password};
// query user table with conditions
/**
* Here query function is used to fetch records from user table this function works like we use sql query.
* SQL query equivalent to this query function is
* SELECT user_id FROM user WHERE user_email = 'jack@androidtutorialshub.com' AND user_password = 'qwerty';
*/
Cursor cursor = db.query(TABLE_USER, //Table to query
columns, //columns to return
selection, //columns for the WHERE clause
selectionArgs, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
null); //The sort order
int cursorCount = cursor.getCount();
cursor.close();
db.close();
if (cursorCount > 0) {
return true;
}
return false;
}
}
4 ) Model Class
public class User {
private int id;
private String name;
private String email;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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 String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
5 ) Login Activity
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.AppCompatTextView;
import android.view.View;
import android.widget.Toast;
import com.example.discusit.sqlitedatabasedemowithapicalling.db.DatabaseHelper;
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
private final AppCompatActivity activity = LoginActivity.this;
private NestedScrollView nestedScrollView;
private TextInputLayout textInputLayoutEmail;
private TextInputLayout textInputLayoutPassword;
private TextInputEditText textInputEditTextEmail;
private TextInputEditText textInputEditTextPassword;
private AppCompatButton appCompatButtonLogin;
private AppCompatTextView textViewLinkRegister;
private DatabaseHelper databaseHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
getSupportActionBar().hide();
initViews();
initListeners();
initObjects();
}
/**
* This method is to initialize views
*/
private void initViews() {
textInputLayoutEmail = (TextInputLayout) findViewById(R.id.textInputLayoutEmail);
textInputLayoutPassword = (TextInputLayout) findViewById(R.id.textInputLayoutPassword);
textInputEditTextEmail = (TextInputEditText) findViewById(R.id.textInputEditTextEmail);
textInputEditTextPassword = (TextInputEditText) findViewById(R.id.textInputEditTextPassword);
appCompatButtonLogin = (AppCompatButton) findViewById(R.id.appCompatButtonLogin);
textViewLinkRegister = (AppCompatTextView) findViewById(R.id.textViewLinkRegister);
}
/**
* This method is to initialize listeners
*/
private void initListeners() {
appCompatButtonLogin.setOnClickListener(this);
textViewLinkRegister.setOnClickListener(this);
}
/**
* This method is to initialize objects to be used
*/
private void initObjects() {
databaseHelper = new DatabaseHelper(activity);
}
/**
* This implemented method is to listen the click on view
*
* @param v
*/
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.appCompatButtonLogin:
verifyFromSQLite();
break;
case R.id.textViewLinkRegister:
// Navigate to RegisterActivity
Intent intentRegister = new Intent(getApplicationContext(), RegisterActivity.class);
startActivity(intentRegister);
break;
}
}
/**
* This method is to validate the input text fields and verify login credentials from SQLite
*/
private void verifyFromSQLite() {
if (databaseHelper.checkUser(textInputEditTextEmail.getText().toString().trim()
, textInputEditTextPassword.getText().toString().trim())) {
Intent accountsIntent = new Intent(activity, MainActivity.class);
accountsIntent.putExtra("EMAIL", textInputEditTextEmail.getText().toString().trim());
emptyInputEditText();
startActivity(accountsIntent);
} else {
Toast.makeText(activity, LoginActivity.this.getResources().getString(R.string.error_message_email), Toast
.LENGTH_SHORT)
.show();
}
}
/**
* This method is to empty all input edit text
*/
private void emptyInputEditText() {
textInputEditTextEmail.setText(null);
textInputEditTextPassword.setText(null);
}
}
6 ) Register Activity
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.AppCompatTextView;
import android.view.View;
import com.example.discusit.sqlitedatabasedemowithapicalling.db.DatabaseHelper;
import com.example.discusit.sqlitedatabasedemowithapicalling.model.User;
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {
private final AppCompatActivity activity = RegisterActivity.this;
private NestedScrollView nestedScrollView;
private TextInputLayout textInputLayoutName;
private TextInputLayout textInputLayoutEmail;
private TextInputLayout textInputLayoutPassword;
private TextInputLayout textInputLayoutConfirmPassword;
private TextInputEditText textInputEditTextName;
private TextInputEditText textInputEditTextEmail;
private TextInputEditText textInputEditTextPassword;
private TextInputEditText textInputEditTextConfirmPassword;
private AppCompatButton appCompatButtonRegister;
private AppCompatTextView appCompatTextViewLoginLink;
private DatabaseHelper databaseHelper;
private User user;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
getSupportActionBar().hide();
initViews();
initListeners();
initObjects();
}
/**
* This method is to initialize views
*/
private void initViews() {
nestedScrollView = (NestedScrollView) findViewById(R.id.nestedScrollView);
textInputLayoutName = (TextInputLayout) findViewById(R.id.textInputLayoutName);
textInputLayoutEmail = (TextInputLayout) findViewById(R.id.textInputLayoutEmail);
textInputLayoutPassword = (TextInputLayout) findViewById(R.id.textInputLayoutPassword);
textInputLayoutConfirmPassword = (TextInputLayout) findViewById(R.id.textInputLayoutConfirmPassword);
textInputEditTextName = (TextInputEditText) findViewById(R.id.textInputEditTextName);
textInputEditTextEmail = (TextInputEditText) findViewById(R.id.textInputEditTextEmail);
textInputEditTextPassword = (TextInputEditText) findViewById(R.id.textInputEditTextPassword);
textInputEditTextConfirmPassword = (TextInputEditText) findViewById(R.id.textInputEditTextConfirmPassword);
appCompatButtonRegister = (AppCompatButton) findViewById(R.id.appCompatButtonRegister);
appCompatTextViewLoginLink = (AppCompatTextView) findViewById(R.id.appCompatTextViewLoginLink);
}
/**
* This method is to initialize listeners
*/
private void initListeners() {
appCompatButtonRegister.setOnClickListener(this);
appCompatTextViewLoginLink.setOnClickListener(this);
}
/**
* This method is to initialize objects to be used
*/
private void initObjects() {
databaseHelper = new DatabaseHelper(activity);
user = new User();
}
/*
* This implemented method is to listen the click on view
*
* @param v
*/
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.appCompatButtonRegister:
postDataToSQLite();
break;
case R.id.appCompatTextViewLoginLink:
finish();
break;
}
}
/**
* This method is to validate the input text fields and post data to SQLite
*/
private void postDataToSQLite() {
if (!databaseHelper.checkUser(textInputEditTextEmail.getText().toString().trim())) {
user.setName(textInputEditTextName.getText().toString().trim());
user.setEmail(textInputEditTextEmail.getText().toString().trim());
user.setPassword(textInputEditTextPassword.getText().toString().trim());
databaseHelper.addUser(user);
// Snack Bar to show success message that record saved successfully
Snackbar.make(nestedScrollView, getString(R.string.success_message), Snackbar.LENGTH_LONG).show();
emptyInputEditText();
} else {
// Snack Bar to show error message that record already exists
Snackbar.make(nestedScrollView, getString(R.string.error_email_exists), Snackbar.LENGTH_LONG).show();
}
}
/**
* This method is to empty all input edit text
*/
private void emptyInputEditText() {
textInputEditTextName.setText(null);
textInputEditTextEmail.setText(null);
textInputEditTextPassword.setText(null);
textInputEditTextConfirmPassword.setText(null);
}
}
7 ) String XML
<resources>
<string name="app_name">SQLiteDatabaseDemoWithAPICalling</string>
<string name="text_accounts">All Accounts</string>
<string name="hint_name">Name</string>
<string name="hint_email">Email</string>
<string name="hint_password">Password</string>
<string name="hint_confirm_password">Confirm Password</string>
<string name="text_login">Login</string>
<string name="text_register">Register</string>
<string name="error_message_name">Enter Full Name</string>
<string name="error_message_email">Enter Valid Email</string>
<string name="error_message_age">Enter Age</string>
<string name="error_message_password">Enter Password</string>
<string name="success_message">Registration Successful</string>
<string name="text_not_member">No account yet? Create one</string>
<string name="text_already_member">Already a member? Login</string>
<string name="error_email_exists">Email Already Exists</string>
<string name="error_password_match">Password Does Not Matches</string>
<string name="error_valid_email_password">Wrong Email or Password</string>
<string name="action_settings">Settings</string>
<string name="text_hello">Hello,</string>
<string name="text_title">Android Demo</string>
</resources>
<?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:id="@+id/nestedScrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorBackground"
android:paddingBottom="20dp"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:paddingTop="20dp"
tools:context=".LoginActivity">
<android.support.v7.widget.LinearLayoutCompat
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.TextInputLayout
android:id="@+id/textInputLayoutEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp">
<android.support.design.widget.TextInputEditText
android:id="@+id/textInputEditTextEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/hint_email"
android:inputType="text"
android:maxLines="1"
android:textColor="@android:color/white" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/textInputLayoutPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp">
<android.support.design.widget.TextInputEditText
android:id="@+id/textInputEditTextPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/hint_password"
android:inputType="textPassword"
android:maxLines="1"
android:textColor="@android:color/white" />
</android.support.design.widget.TextInputLayout>
<android.support.v7.widget.AppCompatButton
android:id="@+id/appCompatButtonLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:background="@color/colorTextHint"
android:text="@string/text_login" />
<android.support.v7.widget.AppCompatTextView
android:id="@+id/textViewLinkRegister"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:gravity="center"
android:text="@string/text_not_member"
android:textSize="16dp" />
</android.support.v7.widget.LinearLayoutCompat>
</LinearLayout>
2 ) Activity Register
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/nestedScrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorBackground"
android:paddingBottom="20dp"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:paddingTop="20dp"
tools:context=".LoginActivity">
<android.support.v7.widget.LinearLayoutCompat
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.TextInputLayout
android:id="@+id/textInputLayoutName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp">
<android.support.design.widget.TextInputEditText
android:id="@+id/textInputEditTextName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/hint_name"
android:inputType="text"
android:maxLines="1"
android:textColor="@android:color/black" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/textInputLayoutEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp">
<android.support.design.widget.TextInputEditText
android:id="@+id/textInputEditTextEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/hint_email"
android:inputType="text"
android:maxLines="1"
android:textColor="@android:color/black" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/textInputLayoutPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp">
<android.support.design.widget.TextInputEditText
android:id="@+id/textInputEditTextPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/hint_password"
android:inputType="textPassword"
android:maxLines="1"
android:textColor="@android:color/black" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/textInputLayoutConfirmPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp">
<android.support.design.widget.TextInputEditText
android:id="@+id/textInputEditTextConfirmPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/hint_confirm_password"
android:inputType="textPassword"
android:maxLines="1"
android:textColor="@android:color/black" />
</android.support.design.widget.TextInputLayout>
<android.support.v7.widget.AppCompatButton
android:id="@+id/appCompatButtonRegister"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:background="@color/colorTextHint"
android:text="@string/text_register" />
<android.support.v7.widget.AppCompatTextView
android:id="@+id/appCompatTextViewLoginLink"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:gravity="center"
android:text="Already a member? Login"
android:textSize="16dp" />
</android.support.v7.widget.LinearLayoutCompat>
</android.support.v4.widget.NestedScrollView>
3 ) Database Handler
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.example.discusit.sqlitedatabasedemowithapicalling.model.User;
import java.util.ArrayList;
import java.util.List;
public class DatabaseHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "UserManager.db";
// User table name
private static final String TABLE_USER = "user";
// User Table Columns names
private static final String COLUMN_USER_ID = "user_id";
private static final String COLUMN_USER_NAME = "user_name";
private static final String COLUMN_USER_EMAIL = "user_email";
private static final String COLUMN_USER_PASSWORD = "user_password";
// create table sql query
private String CREATE_USER_TABLE = "CREATE TABLE " + TABLE_USER + "("
+ COLUMN_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COLUMN_USER_NAME + " TEXT,"
+ COLUMN_USER_EMAIL + " TEXT," + COLUMN_USER_PASSWORD + " TEXT" + ")";
// drop table sql query
private String DROP_USER_TABLE = "DROP TABLE IF EXISTS " + TABLE_USER;
/**
* Constructor
*
* @param context
*/
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_USER_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//Drop User Table if exist
db.execSQL(DROP_USER_TABLE);
// Create tables again
onCreate(db);
}
/**
* This method is to create user record
*
* @param user
*/
public void addUser(User user) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_USER_NAME, user.getName());
values.put(COLUMN_USER_EMAIL, user.getEmail());
values.put(COLUMN_USER_PASSWORD, user.getPassword());
// Inserting Row
db.insert(TABLE_USER, null, values);
db.close();
}
/**
* This method is to fetch all user and return the list of user records
*
* @return list
*/
public List<User> getAllUser() {
// array of columns to fetch
String[] columns = {
COLUMN_USER_ID,
COLUMN_USER_EMAIL,
COLUMN_USER_NAME,
COLUMN_USER_PASSWORD
};
// sorting orders
String sortOrder =
COLUMN_USER_NAME + " ASC";
List<User> userList = new ArrayList<User>();
SQLiteDatabase db = this.getReadableDatabase();
// query the user table
/**
* Here query function is used to fetch records from user table this function works like we use sql query.
* SQL query equivalent to this query function is
* SELECT user_id,user_name,user_email,user_password FROM user ORDER BY user_name;
*/
Cursor cursor = db.query(TABLE_USER, //Table to query
columns, //columns to return
null, //columns for the WHERE clause
null, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
sortOrder); //The sort order
// Traversing through all rows and adding to list
if (cursor.moveToFirst()) {
do {
User user = new User();
user.setId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(COLUMN_USER_ID))));
user.setName(cursor.getString(cursor.getColumnIndex(COLUMN_USER_NAME)));
user.setEmail(cursor.getString(cursor.getColumnIndex(COLUMN_USER_EMAIL)));
user.setPassword(cursor.getString(cursor.getColumnIndex(COLUMN_USER_PASSWORD)));
// Adding user record to list
userList.add(user);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
// return user list
return userList;
}
/**
* This method to update user record
*
* @param user
*/
public void updateUser(User user) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_USER_NAME, user.getName());
values.put(COLUMN_USER_EMAIL, user.getEmail());
values.put(COLUMN_USER_PASSWORD, user.getPassword());
// updating row
db.update(TABLE_USER, values, COLUMN_USER_ID + " = ?",
new String[]{String.valueOf(user.getId())});
db.close();
}
/**
* This method is to delete user record
*
* @param user
*/
public void deleteUser(User user) {
SQLiteDatabase db = this.getWritableDatabase();
// delete user record by id
db.delete(TABLE_USER, COLUMN_USER_ID + " = ?",
new String[]{String.valueOf(user.getId())});
db.close();
}
/**
* This method to check user exist or not
*
* @param email
* @return true/false
*/
public boolean checkUser(String email) {
// array of columns to fetch
String[] columns = {
COLUMN_USER_ID
};
SQLiteDatabase db = this.getReadableDatabase();
// selection criteria
String selection = COLUMN_USER_EMAIL + " = ?";
// selection argument
String[] selectionArgs = {email};
// query user table with condition
/**
* Here query function is used to fetch records from user table this function works like we use sql query.
* SQL query equivalent to this query function is
* SELECT user_id FROM user WHERE user_email = 'jack@androidtutorialshub.com';
*/
Cursor cursor = db.query(TABLE_USER, //Table to query
columns, //columns to return
selection, //columns for the WHERE clause
selectionArgs, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
null); //The sort order
int cursorCount = cursor.getCount();
cursor.close();
db.close();
if (cursorCount > 0) {
return true;
}
return false;
}
/**
* This method to check user exist or not
*
* @param email
* @param password
* @return true/false
*/
public boolean checkUser(String email, String password) {
// array of columns to fetch
String[] columns = {
COLUMN_USER_ID
};
SQLiteDatabase db = this.getReadableDatabase();
// selection criteria
String selection = COLUMN_USER_EMAIL + " = ?" + " AND " + COLUMN_USER_PASSWORD + " = ?";
// selection arguments
String[] selectionArgs = {email, password};
// query user table with conditions
/**
* Here query function is used to fetch records from user table this function works like we use sql query.
* SQL query equivalent to this query function is
* SELECT user_id FROM user WHERE user_email = 'jack@androidtutorialshub.com' AND user_password = 'qwerty';
*/
Cursor cursor = db.query(TABLE_USER, //Table to query
columns, //columns to return
selection, //columns for the WHERE clause
selectionArgs, //The values for the WHERE clause
null, //group the rows
null, //filter by row groups
null); //The sort order
int cursorCount = cursor.getCount();
cursor.close();
db.close();
if (cursorCount > 0) {
return true;
}
return false;
}
}
4 ) Model Class
public class User {
private int id;
private String name;
private String email;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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 String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
5 ) Login Activity
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.AppCompatTextView;
import android.view.View;
import android.widget.Toast;
import com.example.discusit.sqlitedatabasedemowithapicalling.db.DatabaseHelper;
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
private final AppCompatActivity activity = LoginActivity.this;
private NestedScrollView nestedScrollView;
private TextInputLayout textInputLayoutEmail;
private TextInputLayout textInputLayoutPassword;
private TextInputEditText textInputEditTextEmail;
private TextInputEditText textInputEditTextPassword;
private AppCompatButton appCompatButtonLogin;
private AppCompatTextView textViewLinkRegister;
private DatabaseHelper databaseHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
getSupportActionBar().hide();
initViews();
initListeners();
initObjects();
}
/**
* This method is to initialize views
*/
private void initViews() {
textInputLayoutEmail = (TextInputLayout) findViewById(R.id.textInputLayoutEmail);
textInputLayoutPassword = (TextInputLayout) findViewById(R.id.textInputLayoutPassword);
textInputEditTextEmail = (TextInputEditText) findViewById(R.id.textInputEditTextEmail);
textInputEditTextPassword = (TextInputEditText) findViewById(R.id.textInputEditTextPassword);
appCompatButtonLogin = (AppCompatButton) findViewById(R.id.appCompatButtonLogin);
textViewLinkRegister = (AppCompatTextView) findViewById(R.id.textViewLinkRegister);
}
/**
* This method is to initialize listeners
*/
private void initListeners() {
appCompatButtonLogin.setOnClickListener(this);
textViewLinkRegister.setOnClickListener(this);
}
/**
* This method is to initialize objects to be used
*/
private void initObjects() {
databaseHelper = new DatabaseHelper(activity);
}
/**
* This implemented method is to listen the click on view
*
* @param v
*/
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.appCompatButtonLogin:
verifyFromSQLite();
break;
case R.id.textViewLinkRegister:
// Navigate to RegisterActivity
Intent intentRegister = new Intent(getApplicationContext(), RegisterActivity.class);
startActivity(intentRegister);
break;
}
}
/**
* This method is to validate the input text fields and verify login credentials from SQLite
*/
private void verifyFromSQLite() {
if (databaseHelper.checkUser(textInputEditTextEmail.getText().toString().trim()
, textInputEditTextPassword.getText().toString().trim())) {
Intent accountsIntent = new Intent(activity, MainActivity.class);
accountsIntent.putExtra("EMAIL", textInputEditTextEmail.getText().toString().trim());
emptyInputEditText();
startActivity(accountsIntent);
} else {
Toast.makeText(activity, LoginActivity.this.getResources().getString(R.string.error_message_email), Toast
.LENGTH_SHORT)
.show();
}
}
/**
* This method is to empty all input edit text
*/
private void emptyInputEditText() {
textInputEditTextEmail.setText(null);
textInputEditTextPassword.setText(null);
}
}
6 ) Register Activity
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.AppCompatTextView;
import android.view.View;
import com.example.discusit.sqlitedatabasedemowithapicalling.db.DatabaseHelper;
import com.example.discusit.sqlitedatabasedemowithapicalling.model.User;
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {
private final AppCompatActivity activity = RegisterActivity.this;
private NestedScrollView nestedScrollView;
private TextInputLayout textInputLayoutName;
private TextInputLayout textInputLayoutEmail;
private TextInputLayout textInputLayoutPassword;
private TextInputLayout textInputLayoutConfirmPassword;
private TextInputEditText textInputEditTextName;
private TextInputEditText textInputEditTextEmail;
private TextInputEditText textInputEditTextPassword;
private TextInputEditText textInputEditTextConfirmPassword;
private AppCompatButton appCompatButtonRegister;
private AppCompatTextView appCompatTextViewLoginLink;
private DatabaseHelper databaseHelper;
private User user;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
getSupportActionBar().hide();
initViews();
initListeners();
initObjects();
}
/**
* This method is to initialize views
*/
private void initViews() {
nestedScrollView = (NestedScrollView) findViewById(R.id.nestedScrollView);
textInputLayoutName = (TextInputLayout) findViewById(R.id.textInputLayoutName);
textInputLayoutEmail = (TextInputLayout) findViewById(R.id.textInputLayoutEmail);
textInputLayoutPassword = (TextInputLayout) findViewById(R.id.textInputLayoutPassword);
textInputLayoutConfirmPassword = (TextInputLayout) findViewById(R.id.textInputLayoutConfirmPassword);
textInputEditTextName = (TextInputEditText) findViewById(R.id.textInputEditTextName);
textInputEditTextEmail = (TextInputEditText) findViewById(R.id.textInputEditTextEmail);
textInputEditTextPassword = (TextInputEditText) findViewById(R.id.textInputEditTextPassword);
textInputEditTextConfirmPassword = (TextInputEditText) findViewById(R.id.textInputEditTextConfirmPassword);
appCompatButtonRegister = (AppCompatButton) findViewById(R.id.appCompatButtonRegister);
appCompatTextViewLoginLink = (AppCompatTextView) findViewById(R.id.appCompatTextViewLoginLink);
}
/**
* This method is to initialize listeners
*/
private void initListeners() {
appCompatButtonRegister.setOnClickListener(this);
appCompatTextViewLoginLink.setOnClickListener(this);
}
/**
* This method is to initialize objects to be used
*/
private void initObjects() {
databaseHelper = new DatabaseHelper(activity);
user = new User();
}
/*
* This implemented method is to listen the click on view
*
* @param v
*/
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.appCompatButtonRegister:
postDataToSQLite();
break;
case R.id.appCompatTextViewLoginLink:
finish();
break;
}
}
/**
* This method is to validate the input text fields and post data to SQLite
*/
private void postDataToSQLite() {
if (!databaseHelper.checkUser(textInputEditTextEmail.getText().toString().trim())) {
user.setName(textInputEditTextName.getText().toString().trim());
user.setEmail(textInputEditTextEmail.getText().toString().trim());
user.setPassword(textInputEditTextPassword.getText().toString().trim());
databaseHelper.addUser(user);
// Snack Bar to show success message that record saved successfully
Snackbar.make(nestedScrollView, getString(R.string.success_message), Snackbar.LENGTH_LONG).show();
emptyInputEditText();
} else {
// Snack Bar to show error message that record already exists
Snackbar.make(nestedScrollView, getString(R.string.error_email_exists), Snackbar.LENGTH_LONG).show();
}
}
/**
* This method is to empty all input edit text
*/
private void emptyInputEditText() {
textInputEditTextName.setText(null);
textInputEditTextEmail.setText(null);
textInputEditTextPassword.setText(null);
textInputEditTextConfirmPassword.setText(null);
}
}
7 ) String XML
<resources>
<string name="app_name">SQLiteDatabaseDemoWithAPICalling</string>
<string name="text_accounts">All Accounts</string>
<string name="hint_name">Name</string>
<string name="hint_email">Email</string>
<string name="hint_password">Password</string>
<string name="hint_confirm_password">Confirm Password</string>
<string name="text_login">Login</string>
<string name="text_register">Register</string>
<string name="error_message_name">Enter Full Name</string>
<string name="error_message_email">Enter Valid Email</string>
<string name="error_message_age">Enter Age</string>
<string name="error_message_password">Enter Password</string>
<string name="success_message">Registration Successful</string>
<string name="text_not_member">No account yet? Create one</string>
<string name="text_already_member">Already a member? Login</string>
<string name="error_email_exists">Email Already Exists</string>
<string name="error_password_match">Password Does Not Matches</string>
<string name="error_valid_email_password">Wrong Email or Password</string>
<string name="action_settings">Settings</string>
<string name="text_hello">Hello,</string>
<string name="text_title">Android Demo</string>
</resources>
Comments
Post a Comment