Android Simple Login Example Using SQLite

MainActivity.java

package com.androidruler.databasesample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

EditText uname,pswd;
Button login;
DbHandler db;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uname=(EditText)findViewById(R.id.uname);
pswd=(EditText)findViewById(R.id.password);
login=(Button)findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name=uname.getText().toString();
String password=pswd.getText().toString();

int id= checkUser(new User(name,password));
if(id==-1)
{
Toast.makeText(MainActivity.this,"User Does Not Exist",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this,"User Exist "+name,Toast.LENGTH_SHORT).show();
}
}
});

db=new DbHandler(MainActivity.this);
//inserting dummy users
db.addUser(new User("Ankur", "Bansal"));
db.addUser(new User("Vibhor", "Tayal"));
db.addUser(new User("Jatin", "Garg"));

}

public int checkUser(User user)
{
return db.checkUser(user);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

User.java

package com.androidruler.databasesample;


//this is model class
public class User {

 //variables
 int id;
 String name;
 String password;


 // Constructor with two parameters name and password
 public User(String name,String password)
 {
 this.name=name;
 this.password=password;
 }
 //Parameter constructor containing all three parameters
 public User(int id,String name,String psd)
 {
 this.id=id;
 this.name=name;
 this.password=psd;

 }
 //getting id
 public int getId() {
 return id;
 }
 //setting id
 public void setId(int id) {
 this.id = id;
 }
 //getting name
 public String getName() {
 return name;
 }
 //setting name
 public void setName(String name) {
 this.name = name;
 }

 //getting password
 public String getPassword() {
 return password;
 }

 //setting password
 public void setPassword(String password) {
 this.password = password;
 }
}

 DbHandler.java

package com.androidruler.databasesample;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.List;


public class DbHandler extends SQLiteOpenHelper {

 //all constants as they are static and final(Db=Database)
 //Db Version
 private static final int Db_Version=1;
 //Db Name
 private static final String Db_Name="users";
 //table name
 private static final String Table_Name="user";
 //Creating mycontacts Columns
 private static final String User_id="id";
 private static final String User_name="name";
 private static final String User_password="password";


 //constructor here
 public DbHandler(Context context)
 {
 super(context,Db_Name,null,Db_Version);
 }

 //creating table
 @Override
 public void onCreate(SQLiteDatabase db) {
 // writing command for sqlite to create table with required columns
 String Create_Table="CREATE TABLE " + Table_Name + "(" + User_id
 + " INTEGER PRIMARY KEY," + User_name + " TEXT," + User_password + " TEXT" + ")";
 db.execSQL(Create_Table);
 }

 //Upgrading the Db
 @Override
 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
 //Drop table if exists
 db.execSQL("DROP TABLE IF EXISTS " + Table_Name);
 //create the table again
 onCreate(db);
 }

 //Add new User by calling this method
 public void addUser(User usr)
 {
 // getting db instance for writing the user
 SQLiteDatabase db=this.getWritableDatabase();
 ContentValues cv=new ContentValues();
 // cv.put(User_id,usr.getId());
 cv.put(User_name,usr.getName());
 cv.put(User_password,usr.getPassword());

 //inserting row
 db.insert(Table_Name, null, cv);
 //close the database to avoid any leak
 db.close();
 }

 public int checkUser(User us)
 {
 int id=-1;
 SQLiteDatabase db=this.getReadableDatabase();
 Cursor cursor=db.rawQuery("SELECT id FROM user WHERE name=? AND password=?",new String[]{us.getName(),us.getPassword()});
 if(cursor.getCount()>0) {
 cursor.moveToFirst();
 id=cursor.getInt(0);
 cursor.close();
 }
 return id;
 }
}

//layout for MainActivity.java

activity_main.xml

<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:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 android:paddingBottom="@dimen/activity_vertical_margin"
 tools:context=".MainActivity"
 android:orientation="vertical">

 <TextView
 android:id="@+id/totalcount"
 android:layout_margin="10dp"
 android:text="UserName"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content" />
 <EditText
 android:id="@+id/uname"
 android:layout_width="fill_parent"
 android:layout_height="50dp" />

 <TextView
 android:id="@+id/psw"
 android:layout_margin="10dp"
 android:text="Password"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content" />
 <EditText
 android:id="@+id/password"
 android:layout_width="fill_parent"
 android:layout_height="50dp" />


 <Button
 android:id="@+id/login"
 android:padding="20dp"
 android:text="Login"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content" />

</LinearLayout>

AndroidManifest.xml

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

 <application
 android:allowBackup="true"
 android:icon="@mipmap/ic_launcher"
 android:label="@string/app_name"
 android:theme="@style/AppTheme" >
 <activity
 android:name=".MainActivity"
 android:label="@string/app_name" >
 <intent-filter>
 <action android:name="android.intent.action.MAIN" />

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

</manifest>