Sunday, November 18, 2012

Android Login System using SQLite



I have already written several posts regarding Android database applications. This post might be similar to those tuts. However this is more complete Android Login System which uses SQLite as its database. All files can be downloaded here or there

Let's create the view. first. But I'm not going to show it in the post. Just two text boxes for username and password, two buttons for login and register.

DBHelper.java

[sourcecode language="java"]
package com.my.members;

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

public class DBHelper extends SQLiteOpenHelper {

private static final String DATABASE_NAME = "membersdb";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE = "CREATE TABLE  (_id integer primary key autoincrement,username text not null,password text not null);";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);

}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);

}

@Override
public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
db.execSQL("DROP TABLE IF EXISTS members");
onCreate(db);

}

}
[/sourcecode]

DBAdapter.java

[sourcecode language="java"]
package com.my.members;

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

public class DBAdapter
{
private static final String DATABASE_TABLE = "members";
public static final String KEY_ROW_ID = "_id";
public static final String KEY_USERNAME = "username";
public static final String KEY_PASSWORD = "password";

SQLiteDatabase mDb;
Context mCtx;
DBHelper mDbHelper;

public DBAdapter(Context context)
{
this.mCtx = context;
}

public DBAdapter open() throws SQLException
{
mDbHelper = new DBHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}

public void close()
{
mDbHelper.close();
}

public long register(String user,String pw)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_USERNAME, user);
initialValues.put(KEY_PASSWORD, pw);

return mDb.insert(DATABASE_TABLE, null, initialValues);
}

public boolean Login(String username, String password) throws SQLException
{
Cursor mCursor = mDb.rawQuery("SELECT * FROM " + DATABASE_TABLE + " WHERE username=? AND password=?", new String[]{username,password});
if (mCursor != null) {
if(mCursor.getCount() > 0)
{
return true;
}
}
return false;
}
}
[/sourcecode]

MembersActivity

[sourcecode language="java"]
package com.my.members;

import android.app.Activity;
import android.content.Context;
import android.database.SQLException;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MembersActivity extends Activity {
DBAdapter dbAdapter;
EditText txtUserName;
EditText txtPassword;
Button btnLogin;
Button btnRegister;

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

txtUserName = (EditText) findViewById(R.id.et_user);
txtPassword = (EditText) findViewById(R.id.et_pw);
btnLogin = (Button) findViewById(R.id.btn_login);
btnRegister = (Button) findViewById(R.id.btn_reg);

dbAdapter = new DBAdapter(this);
dbAdapter.open();

btnLogin.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(txtUserName.getWindowToken(), 0);
imm.hideSoftInputFromWindow(txtPassword.getWindowToken(), 0);
String username = txtUserName.getText().toString();
String password = txtPassword.getText().toString();
if (username.length() > 0 && password.length() > 0) {
try {

if (dbAdapter.Login(username, password)) {
Toast.makeText(MembersActivity.this,
"Successfully Logged In", Toast.LENGTH_LONG)
.show();
} else {
Toast.makeText(MembersActivity.this,
"Invalid username or password",
Toast.LENGTH_LONG).show();
}

} catch (Exception e) {
Toast.makeText(MembersActivity.this, "Some problem occurred",
Toast.LENGTH_LONG).show();

}
} else {
Toast.makeText(MembersActivity.this,
"Username or Password is empty", Toast.LENGTH_LONG).show();
}
}
});

btnRegister.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(txtUserName.getWindowToken(), 0);
imm.hideSoftInputFromWindow(txtPassword.getWindowToken(), 0);
try {

String username = txtUserName.getText().toString();
String password = txtPassword.getText().toString();
long i = dbAdapter.register(username, password);
if(i != -1)
Toast.makeText(MembersActivity.this, "You have successfully registered",Toast.LENGTH_LONG).show();

} catch (SQLException e) {
Toast.makeText(MembersActivity.this, "Some problem occurred",
Toast.LENGTH_LONG).show();

}

}
});
}
}

[/sourcecode]

Donate & help live a developer

Donate Button with Credit Cards

30 comments:

  1. Please tell me what is the use of these statements
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(txtUserName.getWindowToken(), 0);
    imm.hideSoftInputFromWindow(txtPassword.getWindowToken(), 0);

    ReplyDelete
  2. Hi Vivek,
    InputMethodManager basically controls the interaction between application and current input method. This happens in client side and within application context. You better try reading Android reference.
    http://developer.android.com/reference/android/view/inputmethod/InputMethodManager.html

    ReplyDelete
  3. Thank you so so so so so Much dear friends.....

    ReplyDelete
  4. Hi Qutub,
    Thanks for commenting.

    ReplyDelete
  5. Sir, I trying this project but, i get error on.
    the message android.database.sqlite.SQLiteException: near "(": syntax error: CREATE TABLE
    (_id integer primary key autoincrement,username text not null,password text not null)

    please tell me, where is the part make it error i'm newbe in android project

    thanks

    ReplyDelete
  6. Can you cpoy & paste the errorneous piece of code here?

    ReplyDelete
  7. i just download it from the complete source, and then i run it, but error. the message android.database.sqlite.SQLiteException: near “(“: syntax error: CREATE TABLE
    (_id integer primary key autoincrement,username text not null,password text not null)

    ReplyDelete
  8. am get error on syntax error: CREATE TABLE(..........)

    Help me

    ReplyDelete
  9. Ayas, try this code sure it will work


    private static final String DATABASE_TABLE = "users";
    private static final String DATABASE_CREATE = "create table users (_id integer primary key autoincrement, "
    + "username text not null, "
    + "password text not null);";

    ReplyDelete
  10. Help me!!!
    memberactivity get me error :: The method register(String, String) is undefined for the type DBAdapter!

    ReplyDelete
  11. i trying to create two dbtable in my app but problem is that 2nd table did't created...
    my logcat error:
    03-03 02:13:51.402: E/SQLiteLog(1473): (1) no such table: TRADE
    plz help me if anybody know this:

    ReplyDelete
  12. Hi,
    Don't know whether you solved that.
    Please find this function.
    public void onCreate(SQLiteDatabase db) {
    db.execSQL(DATABASE_CREATE);
    }
    When the function is executed, members table is created according to the example.

    private static final String DATABASE_CREATE = "CREATE TABLE (_id integer primary key autoincrement,username text not null,password text not null);";

    If your first table is created, then you may need to
    update database version

    Eg. private static final int DATABASE_VERSION = 2;.

    ReplyDelete
  13. Please La Aplication Dowmload.. Help Me!!

    ReplyDelete
  14. unfortunately stop of application is occuring when i am running the code???

    ReplyDelete
  15. Fernando CarriĆ³nJuly 15, 2014 at 1:45 PM

    Thanks for the help, just a couple of questions:

    What's the use of context? I just want to get that part clear.

    Thanks again for your help

    ReplyDelete
  16. Hi,
    Context is simply the current state of the application/object. You can get the context by invoking getApplicationContext(), getContext(), getBaseContext() or this (when in the activity class).
    Example usage:

    TextView tv = new TextView(getContext());
    ListAdapter adapter = new SimpleCursorAdapter(getApplicationContext(), ...);

    Its an entity that represents various environment data . Context helps the current activity to interact with out side android environment like local files, databases, class loaders associated to the environment, services including system-level services, and more.

    ReplyDelete
  17. How do I log out a user using this approach?

    ReplyDelete
  18. how do i get to a new activity after a successful login

    ReplyDelete
  19. please use .zip format for source code distribution, as because .zip can be open in windows/mac/ubuntu without installing additional software. while Members.rar format will need to install additional software in all these platforms.

    ReplyDelete
  20. Thanks Abhishek for your point. Yes, this is a mistake. I'll upload .zip file now.

    ReplyDelete
  21. MUCHAS GRACIAS me sirviĆ³ el LOGIN PERFECTO
    gracias por compartir tu conocimiento en android

    ReplyDelete
  22. THANK YOU SO MUCH. i do some modification for strings and class name but it not a big deal for my running login system. <3

    ReplyDelete
  23. Hi, I would like to know if this would work in different devices. For example, if I register in a device, could I access with that account to the app from another device without registering again?

    ReplyDelete
  24. you need the name of the table. Here it's members

    ReplyDelete
  25. Hi i tried working this entire project ... there is no error but the "application stops unfortunately "
    Could you please help me out

    ReplyDelete
  26. It shpws unfortunately stopped ... no error in the entire project

    ReplyDelete
  27. It displays unfortunately stopped

    ReplyDelete
  28. no layout R.name.xml ?????????????????????????????????????

    ReplyDelete
  29. how to get the username and password from register tables using android studio and download app sir

    ReplyDelete

How to enable CORS in Laravel 5

https://www.youtube.com/watch?v=PozYTvmgcVE 1. Add middleware php artisan make:middleware Cors return $next($request) ->header('Acces...