Tuesday, March 1, 2011

Login Based Application in Android using SQLite DataBase

Hi , Let us See how to Create a Login Based Application in Android.

My Aim is , i have to display SignUp Page,when the User access my application for the first time,after that i want to display login page and make a check on it.

Step 1: How to Know that the device interacting with my application for first time.
For that, we have to get DeviceId of that Device. With the Help of Telephony Manager it's possible to get the Device Id of a Device.
The code is

String device_id;
TelephonyManager telemngr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
device_id=telemngr.getDeviceId();

Step2:  How to Create DataBase in Android
I had used SQLite Open Browser to create my database file in assets folder of my project. I had created a table namely login_details with fileds such as username and password and confpassword and deviceid. To Download SQLite Open Browser, pls click this link  http://sourceforge.net/projects/sqlitebrowser/

Step 3: Create a Class which is extends from SQLiteOpenHelper, this is the class which help us to create and mange database. A Sample Code Snippet of this Class

public class MyDBHelper extends SQLiteOpenHelper{
//Declaring Local Variables for database name , and database path and sqlite object and my context
private static String DB_PATH = "";
private static final String DB_NAME = "frnd.db"; // i had created this in my assets folder
private SQLiteDatabase myDataBase;
private final Context myContext;
private static MyDBHelper mDBConnection;
static int version_val=1; // version of my table

//Constructor which sends db name to SQLiteOpenHelper
public MyDBHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
this.myContext = context;
DB_PATH = "/data/data/"
+ context.getApplicationContext().getPackageName()
+ "/databases/";
}

// Used to get the Object

public static synchronized MyDBHelper getDBAdapterInstance(Context context) {
if (mDBConnection == null) {
mDBConnection = new MyDBHelper(context,DB_NAME,null,version_val);
}
return mDBConnection;
}

@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub

}

public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
// do nothing - database already exist
} else {

// By calling following method
// 1) an empty database will be created into the default system path of your application
// 2) than we overwrite that database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}

private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
Log.d("MyPath",myPath);
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);

} catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}

private void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}

public void openDataBase() throws SQLException {
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}

@Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}


public ArrayList<ArrayList<String>> selectRecordsFromDBList(String query, String[] selectionArgs) {
ArrayList<ArrayList<String>> retList = new ArrayList<ArrayList<String>>();
ArrayList<String> list = new ArrayList<String>();
Cursor cursor = myDataBase.rawQuery(query, selectionArgs);
if (cursor.moveToFirst()) {
do {
list = new ArrayList<String>();
for(int i=0; i<cursor.getColumnCount(); i++){
list.add( cursor.getString(i) );
}
retList.add(list);
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return retList;
}


public long insertRecordsInDB(String tableName, String nullColumnHack,
ContentValues initialValues) {
return myDataBase.insert(tableName, nullColumnHack, initialValues);
}

public int deleteRecordInDB(String tableName, String whereClause,
String[] device_id) {
return myDataBase.delete(tableName, whereClause, device_id);
}
}

 Step 4: Creating a Class which helps me to Store my database values in a Variables

public class StoreValue {

String dev_id="";
String username="";
String password="";

public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDev_id() {
return dev_id;
}
public void setDev_id(String dev_id) {
this.dev_id = dev_id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}


}


Step5: Now i had created an Activity, which retervies the device id from my table, here what i had did, if the deviceid from the table matches with my the deviceid of current device which is given  by telephony manager,then i call Login Page instead of SignUp page.

Now cerating my Object for StoreVal class ,declare it and intiallize it

public class MyActivity extends Activity {

Intent Loginjump;
static String device_id;
String default_deviceid=null;
static int version_val=1;
private static final String DB_NAME = "frnd.db";
private ArrayList<StoreValue> mydata=null;
int i=0;
boolean mymatch=false;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mysplashscreen);

MyDBHelper db = new MyDBHelper(getApplicationContext(),DB_NAME,null,version_val);

Log.d("Flow Starts ","0");

TelephonyManager telemngr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
device_id=telemngr.getDeviceId();

mydata= getDeviceID(); // initialize the Object of StoreValue Class

Log.d("MyData Size",Integer.toString(mydata.size()));
for(i=0;i<mydata.size();i++)
{
System.out.println("Mydata of i"+(mydata.get(i).getDev_id()));
Log.d("My Device Id",device_id);
if(mydata.get(i).getDev_id().equals(device_id))
{
mymatch=true;
Log.d("MY Data ",mydata.get(i).toString());
Log.d("Device _ id",device_id);
break;
}


}

if(mymatch == true)
{
Loginjump= new Intent(MyActivity.this,LoginActivity.class);
startActivity(Loginjump);
}

else
{
Loginjump= new Intent(MyActivity.this,Sign.class);
startActivity(Loginjump);


}

}

public ArrayList<StoreValue> getDeviceID(){

MyDBHelper dbAdapter=MyDBHelper.getDBAdapterInstance(this);
try {
dbAdapter.createDataBase();
} catch (IOException e) {
Log.i("*** select ",e.getMessage());
}
dbAdapter.openDataBase();
String query="SELECT deviceid FROM login_details;";
ArrayList<ArrayList<String>> stringList = dbAdapter.selectRecordsFromDBList(query, null);
dbAdapter.close();

ArrayList<StoreValue> usersList = new ArrayList<StoreValue>();
for (int i = 0; i < stringList.size(); i++) {
ArrayList<String> list = stringList.get(i);
StoreValue user = new StoreValue();
try {
user.dev_id = list.get(0);
   
} catch (Exception e) {
Log.i("***" + MyActivity.class.toString(), e.getMessage());
}
usersList.add(user);
}
return usersList;
}

}

Step 6: If the Boolean Variable mymatch retruns false,means that's the device id of this device is not in database,at that time we have to call SignUp page and store the username and password and confpassword and deviceid in our login_details table. The Sample Code Sinnpet

public class Sign extends Activity {
EditText u_name=null,pwd=null,confpwd=null;
Button mysign_submit;
String username="",password="",confpassword="";
static Context c;
Intent Loginjump;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fetch_mydetails);

u_name=(EditText)findViewById(R.id.userval);
pwd=(EditText)findViewById(R.id.mypwdval);
confpwd=(EditText)findViewById(R.id.myconfpwdval);
mysign_submit=(Button)findViewById(R.id.mysubmit);

c= this;

mysign_submit.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.d("I am fired","ok");
username=u_name.getText().toString();
password=pwd.getText().toString();
confpassword=confpwd.getText().toString();

//if(UserName)
Log.d("UserName",username);
Log.d("Password",password);
Log.d("ConfPassword",confpassword);

if(password != confpassword)
{
displayAlert();
}

MyDBHelper dbAdapter = MyDBHelper.getDBAdapterInstance(Sign.this);
dbAdapter.openDataBase();

ContentValues initialValues = new ContentValues();

initialValues.put("username", username);
initialValues.put("password",password);
initialValues.put("confpassword",confpassword);
initialValues.put("deviceid", MyActivity.device_id);

long n = dbAdapter.insertRecordsInDB("login_details", null, initialValues);
Toast.makeText(Sign.this, "new row inserted with id = "+n, Toast.LENGTH_SHORT).show();
if(n>0)
{
Loginjump= new Intent(Sign.this,MyProfile.class);
startActivity(Loginjump);
}
}
}); 
}
public static void displayAlert()
{
new AlertDialog.Builder(c).setMessage(" Your Password and Confrim Password are not Same ")
.setTitle("Password Alert")
.setCancelable(true)
.setNeutralButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){
System.exit(0);
}
})
.show();
}
}

Step 7:  If the Boolean Variable mymatch retruns true,means that's the device id of this device is  in database,so we have to call Login page and reterives the username and password and check that username and password.

public class LoginActivity extends Activity{
EditText u_name=null,pwd=null;
Button mylogin_submit;
String username="",password="";
private ArrayList<StoreValue> mydata=null;
int i=0;
Intent Loginjump;
static Context c;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.logingui);
u_name=(EditText)findViewById(R.id.userval);
pwd=(EditText)findViewById(R.id.mypwdval);
mylogin_submit = (Button)findViewById(R.id.submit);
c= this;

mylogin_submit.setOnTouchListener(new OnTouchListener (){
@Override public boolean onTouch(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
username=u_name.getText().toString();
Log.d("UserName",username);
password=pwd.getText().toString();
mydata=getValue();
Log.d("MyData Size",Integer.toString(mydata.size()));
for(i=0;i<mydata.size();i++)
{
System.out.println("Mydata of i"+(mydata.get(0).username));

if(mydata.get(i).getPassword().equals(password) && mydata.get(i).getUsername().equals(username))
{

Log.d("Success","Boss");
Loginjump= new Intent(LoginActivity.this,MyProfile.class);
startActivity(Loginjump);

}
else
{
Log.d("Failure","1");
displayAlert();
}
}
return false;
}});
}

public static void displayAlert()
{
new AlertDialog.Builder(c).setMessage(" Your Password and Confrim Password are not Same ")
.setTitle("Password Alert")
.setCancelable(true)
.setNeutralButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){
System.exit(0);
}
})
.show();
}

public ArrayList<StoreValue> getValue(){

MyDBHelper dbAdapter=MyDBHelper.getDBAdapterInstance(this);
try {
dbAdapter.createDataBase();
} catch (IOException e) {
Log.i("*** select ",e.getMessage());
}
dbAdapter.openDataBase();
String query="SELECT * FROM login_details;";
ArrayList<ArrayList<String>> stringList = dbAdapter.selectRecordsFromDBList(query, null);
dbAdapter.close();

ArrayList<StoreValue> usersList = new ArrayList<StoreValue>();
for (int i = 0; i < stringList.size(); i++) {
ArrayList<String> list = stringList.get(i);
StoreValue user = new StoreValue();
try {
final StoreValue listItem = mydata.get(i); // --CloneChangeRequired
if (listItem != null) {

user.username = list.get(0);
//Log.d("list.get 0",list.get(0));
System.out.println("List get 0"+list.get(0));

user.password = list.get(1);
System.out.println("List get 1"+list.get(1));
System.out.println("List get 2"+list.get(2));
System.out.println("List get 3"+list.get(3));
// Log.d("list.get 1",list.get(1));
}
} catch (Exception e) {
//Log.i("***" + LoginActivity.class.toString(), e.getMessage());
}
usersList.add(user);
}
return usersList;
}
}







4 comments:

  1. This shows error even though xml file is created correctly:
    Sign Activity
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fetch_mydetails);

    u_name=(EditText)findViewById(R.id.userval);
    pwd=(EditText)findViewById(R.id.mypwdval);
    confpwd=(EditText)findViewById(R.id.myconfpwdval);
    mysign_submit=(Button)findViewById(R.id.mysubmit);
    c= this;
    mysign_submit.setOnClickListener(new OnClickListener(){


    Login Activity
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.logingui);
    u_name=(EditText)findViewById(R.id.userval);
    pwd=(EditText)findViewById(R.id.mypwdval);
    mylogin_submit = (Button)findViewById(R.id.submit);
    c= this;

    ReplyDelete
  2. Hi, Mc, can you post the full code of Sign Activity and post your error which shown by Logcat in pastebin.com and post that pastebin link, here, Thanks

    ReplyDelete
  3. can u please give me the complete code Mc,

    Thanking you!
    Manoj

    ReplyDelete
  4. Can we create sqlite database on local muchine???

    ReplyDelete

Notification in Android Using AlarmManager, BoradCastReceiver & Services

    Our aim is to show notification message to user in a specific time.     Say For example , I have planned to show Notification ...