120 Responses to Android Login Registration Screen with SQLite Database Example

  1. Sameer says:

    Very useful post. I am looking for this simple post long time ago

  2. Meghali says:

    how to check whether the data has been stored in database or not?

    • SmrutiRanjan says:

      Dear Meghali,
      There are varieties of ways to check the stored data. Lets have discuss on Login Example.
      If you are running the app on device/emulator, then connect your device/emulator to your PC.
      Then start Eclipse->DDMS. Then select the connected device/emulator from left side pannel.
      Then goto ‘File Explorer’. then goto ‘data/data/com.techblogon.loginexample/database/login.db’. This file will be in your device and ‘com.techblogon.loginexample’ is the package name.
      Then pull the file and check it using SQLite Browser. I have attached the image below the post. pls see above.

      The best way:Also you can check all SQLite helper class function with try/catch block, if your data has been stored, then no exception will occurred.

    • vyshakh says:

      @Meghali: you can check the database contents from DDMS perpective in Eclipse. DDMs–>file explorer->data->name of your project–>databases–

  3. vyshakh says:

    Brilliant tutorial…Is it a good practice or will there be a problem if we call the signup activity from the main thread although we use intents?

    Btw,it would be great if you could post a tutorial on sending the sql data to remote server as JSON or XML data through a Rest webservice

    • SmrutiRanjan says:

      Dear Vyshakh,
      You can also call the signup activity from the main thread. No issue, but if you need to get some result back then pls use startActivityForResult(Intent, int).
      I will update the tutorial on sending the sql data to remote server as JSON or XML data through a Rest webservice very soon.

      br
      techblogon

  4. Meghali says:

    thank you so much :)

  5. ikhlas says:

    its telling R cannot resolve in HomeActivity

    • SmrutiRanjan says:

      Dear ikhlas,
      You can go through my article ‘Some Common Android Development Errors and Solutions’. that might help you.
      Link: http://techblogon.com/common-android-development-errors-solutions/

      However i have build the code using SDK version Android 4.0.3. your version might be different. so change the version.
      Also you can check the proper xml file names if you just copy the code snippet.
      Did you download the code? or copy paste from the code snippet?
      It is better to create a new project with given project and package name, then replace the content.

      br
      techblogon.

      • ikhlas says:

        Its ok now thANK you….
        Now i these error have pop up in….SignUPActivity.java

        editTextUserName=(EditText)findViewById(R.id.editTextUserName);
        editTextPassword=(EditText)findViewById(R.id.editTextPassword);
        editTextConfirmPassword=(EditText)findViewById(R.id.editTextConfirmPassword);

        btnCreateAccount=(Button)findViewById(R.id.buttonCreateAccount);
        //////////////
        editTextUserName
        editTextPassword
        editTextUserName cannot be resolved or is not a field
        buttonCreateAccountcannot be resolved or is not a field
        buttonCreateAccount
        Thank you in advance

        • SmrutiRanjan says:

          Dear ikhlas,
          You might forget to add these lines in the java file “SignUPActivity.Java” as in the above code.
          It may help you.

          EditText editTextUserName,editTextPassword,editTextConfirmPassword;
          Button btnCreateAccount;

        • ikhlas says:

          editTextUserName=(EditText)findViewById(R.id.editTextUserName);
          editTextPassword=(EditText)findViewById(R.id.editTextPassword);
          editTextConfirmPassword=(EditText)findViewById(R.id.editTextConfirmPassword);

          Now its i got problem with id…

          Can i also i have tutorial for splash screen please..
          THank you so much

        • IKHLAS says:

          nOWS ITS TELLING ME cANNOT solve ID,Layout,,

          • SmrutiRanjan says:

            Which sdk version is showing for your project?
            pleas send the exact error logs, so that i can say some solution.

          • IKHLAS says:

            API 17 version4.2.2

          • SmrutiRanjan says:

            change the SDK version as your,s. goto project and right click on it, then property. then choose SDK version. it might help you.

            But i suggest, make a new project and copy code to your project file. make sure all the packages are added in the project

          • Jeelan says:

            I got it bro thank you very much.Now it is working fine. all records got inserted.

            can u tell how to create auto login using shared preferences .I mean if we check the check box while login by the next time when we open the app it has to redirect to home page.

          • SmrutiRanjan says:

            Dear Jeelan,
            It is very simple. When user check the check box for auto login, save the checkbox state in a shared pref. When user open the app next time, first read the state of the checkbox in your homepage(login page)’s oncreate() method before showing the GUI, destroy the login page and then start the required activity directly.

            If you are new to android shared pref, then let me know, i will update an article with example for android shared preference

          • Jeelan says:

            Thank u very much for reply I am new to android could you plz update the code of shared preferences and one more thing is how to retrive feilds from database.

          • SmrutiRanjan says:

            Ok I will update sharedpref very soon.
            However for retrive feilds from database, you might like my article with example.Here in the code we retrieve username from the database
            Link: http://techblogon.com/android-login-registration-screen-with-sqlite-database-example/

          • jeelan says:

            Sqlite database was fantabilous.Is it possible to retive the values in one method {getsingleentry()} .

            Just modifiy the loginpage page using sharedpref so that it will redirect main page.

          • SmrutiRanjan says:

            delete the R.java file , clean project and rebuild.

          • SmrutiRanjan says:

            you can check the xml file name. make sure you don’t have any space in the file name.

  6. Tomjay says:

    this is nice post…
    But, can you help me about login in android with pattern code??

    Thanks… ^_^

  7. purnendu says:

    Nice code and i really thankful to you for helping me though you code…..

  8. sagar says:

    very nice …….so simple and easy to understand
    thank you…

  9. sagar says:

    Sir i am going to develop screen lock…..
    can u help ……??
    how to bring my login activity on screen when user press unlock button?
    pleas…
    thank u…

  10. DroidApp says:

    Thanks for the article. I am facing small problem with the code and wondering if you can help. The app runs fine on my phone but it does not create the database file. basically under Data there is nothing. Would you know what might cause it. I set android.debuggable=”true” in android manifest and put a break point at static final String DATABASE_CREATE but it does not even trigger when I create new account. Thanks for your help

  11. nila says:

    Sir how if i will add form change password?

    • SmrutiRanjan says:

      For change password, you can put an option menu or button, start a new activity, then get user input(like current, new, confirm password). search the new password it in database, then update it, the update function has already written in the code.

  12. balkiss says:

    good tuto

  13. Jeelan says:

    This is login page :Launcher Activity

    import android.os.Bundle;
    import android.app.Activity;
    import android.app.Dialog;
    import android.content.Intent;
    import android.content.SharedPreferences;
    import android.view.Menu;
    import android.view.View;
    import android.widget.Button;
    import android.widget.CheckBox;
    import android.widget.EditText;
    import android.widget.Toast;

    public class Login extends Activity
    {
    protected static final Bundle edt = null;
    Button btnSignIn1,btnSignUp;
    LoginDataBaseAdapter loginDataBaseAdapter;
    CheckBox ch=null;
    SharedPreferences pre;
    public static String filename=”Myfile”;
    //public static final String PREF_NAME=”store”;
    /*public static final String PREFS_NAME = “MyPrefsFile”;
    public static final String PREF_PWD = “MyPrefsFile”;
    private static final String PREF_USERNAME = “userName”;
    private static final String PREF_PASSWORD = “password”;
    String PROPERTY_CONTENT_TYPE = “Content-Type”;*/

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);
    pre=getSharedPreferences(filename,0);
    /* SharedPreferences pref = getSharedPreferences(PREFS_NAME,MODE_PRIVATE);
    final String userName = pref.getString(PREF_USERNAME, null);
    SharedPreferences pref1 = getSharedPreferences(PREF_PWD,MODE_PRIVATE);
    final String password = pref1.getString(PREF_PASSWORD, null); */
    ch=(CheckBox)findViewById(R.id.checkBox1);
    /* if(ch.isChecked()){
    SharedPreferences settings=getSharedPreferences(“PREF_NAME”,0);
    if(settings.getString(“log”,”").toString().equals(“log”));
    Intent intent = new Intent(Login.this, MainMenu.class);
    startActivity(intent);
    }*/
    // create a instance of SQLite Database
    loginDataBaseAdapter=new LoginDataBaseAdapter(this);
    loginDataBaseAdapter=loginDataBaseAdapter.open();

    // Get The Refference Of Buttons
    btnSignIn1=(Button)findViewById(R.id.buttonSignIn);
    btnSignUp=(Button)findViewById(R.id.buttonSignUP);

    // Set OnClick Listener on SignUp button
    btnSignUp.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
    // TODO Auto-generated method stub

    /// Create Intent for SignUpActivity and Start The Activity
    Intent intentSignUP=new Intent(getApplicationContext(),SignUPActivity.class);
    startActivity(intentSignUP);
    }
    });

    // Methos to handleClick Event of Sign In Button
    //public void signIn(View V)
    // {
    //final Dialog dialog = new Dialog(Login.this);
    //dialog.setContentView(R.layout.login);
    //dialog.setTitle(“Login”);

    // get the Refferences of views
    /* final EditText editTextUserName=(EditText)dialog.findViewById(R.id.editTextUserNameToLogin);
    final EditText editTextPassword=(EditText)dialog.findViewById(R.id.editTextPasswordToLogin);
    */
    Button btnSignIn1=(Button) findViewById(R.id.buttonSignIn);

    // Set On ClickListener
    btnSignIn1.setOnClickListener(new View.OnClickListener() {

    public void onClick(View v) {
    // get The User name and Password
    final EditText editTextUserName=(EditText) findViewById(R.id.editTextUserNameToLogin);
    final EditText editTextPassword=(EditText) findViewById(R.id.editTextPasswordToLogin);

    String userName=editTextUserName.getText().toString();
    String password=editTextPassword.getText().toString();

    // fetch the Password form database for respective user name
    String storedPassword=loginDataBaseAdapter.getSinlgeEntry(userName);

    // check if the Stored password matches with Password entered by user
    /*if(ch.isChecked())
    {
    SharedPreferences.Editor edt=pre.edit();
    edt.putString(“sharedata1″,userName);
    edt.putString(“sharedata2″,password);
    edt.commit();
    }*/
    /*if(ch.isChecked()){
    if(edt.getString(“sharedata1″,”").toString().equals(“userName”) && edt.getString(“sharedata2″,”").toString().equals(“passowrd”));
    {
    Intent intent = new Intent(Login.this, MainMenu.class);
    startActivity(intent);
    }*/
    /*getSharedPreferences(PREFS_NAME,MODE_PRIVATE)
    .edit()
    .putString(PREF_USERNAME, editTextUserName.getText().toString())
    .putString(PREF_PASSWORD, editTextPassword.getText().toString())
    .commit(); */

    if(password.equals(storedPassword))
    {
    Intent in=new Intent(getApplicationContext(),MainMenu.class);
    startActivity(in);
    finish();
    if(ch.isChecked())
    {
    SharedPreferences.Editor edt=pre.edit();
    edt.putString(“sharedata1″,userName);
    edt.putString(“sharedata2″,password);
    edt.commit();
    /*Intent in1=new Intent(getApplicationContext(),MainMenu.class);
    startActivity(in1);
    finish();*/
    }
    /*Toast.makeText(HomeActivity.this, “Congrats: Login Successfull”, Toast.LENGTH_LONG).show();
    dialog.dismiss();*/
    }
    else
    {
    Toast.makeText(Login.this, “User Name or Password does not match”, Toast.LENGTH_LONG).show();
    }
    }
    });
    }
    /*
    dialog.show();
    }*/

    @Override
    protected void onDestroy() {
    super.onDestroy();
    // Close The Database
    loginDataBaseAdapter.close();
    }
    }

    one more thing i was trying to make autologin using shared preferences but it is not redirecting to main menu when activty starts

    Can u please help me.

    • SmrutiRanjan says:

      Read the auto login state from the main page’s onCreate() function before showing your GUI, if it is true, then start your required activity and destroy the current activity.

  14. rajaa.gerges@hotmail.com says:

    hello man, its a great post. but when i click on the button of the create account everything is successfull but it doesnt take me to the main page.how to do it. thx

  15. gaurav kumar says:

    sir i am finding the error in login.xml & sifnup.xml
    thet net beans says error parsing xml
    so i want the solution of this error in netbeans ide
    where i hav to locate this 2 xml file ????

  16. IKHLAS says:

    hi…its finally working
    Can you please tell me how can i go to another page after login succesfully instead of HOMEactivity…please

    and also if i want to create a new registration form how should i do it…
    thx

    • SmrutiRanjan says:

      It is simple. For showing another page, just start a new activity.

    • IKHLAaS goods says:

      I HAVE ALREADY created a new activity,,,
      After login succesfully i want it to the new activity,,,,
      i have everything but it telling Application stop …..
      i have replace in the login page…where toast congrats login succesfully..
      i replase with the new activity still the same…

  17. Gaurav says:

    Sir i am using ur code for ths login app on device but it is not showing database values and even not picking up values stored in database.it is showing the toast message username or password did not match.please suggest

  18. veeresh sabanna says:

    Hi Smruthi Ranjan

    can you please help me in connecting SQLite database, here Iam using your SQLiteStorageOption project, its running in emulater but problem is it is not showing any data and if i try add option throwing some error.

  19. Urvi Parikh says:

    Sir, I m having a error of com.Linprog.LoginDatabaseAdapter.insertEntry(LoginDatabaseAdapter.java:53)
    plz help me to solve it out.

  20. omar says:

    I want to make a project using Android
    Helps users to chat and communicate with each other
    Can you help me so
    Thank you

  21. Jeelan says:

    could u please update the auto login page using check box (shared preferences).

  22. Jeelan says:

    i have gone through shared preferences tutorials.But am unable to make my requirement.

  23. Amardeep says:

    sir how can we read database table in this project

  24. Amardeep says:

    how to hosting an android project please help me
    Thank you

  25. Amardeep says:

    sir how can we connect android application with external database SQLite

  26. Amardeep says:

    sir how can we connect the android apps with external database

    • nagaraj says:

      Hi man….. I want to create a gps based vehicle tracker software needed…. please send me the code to me

  27. Bat says:

    i got an error for as follow :

    string password = password.getText().toString();

    it said that i have an error at the getText() baecause it is undefined to string. can u help me?

  28. aown raza says:

    Great Tutorial

  29. Nuziit says:

    my emulator shows LoginDataBaseAdapter cannot resilved to a type……….wii u plz help me

  30. gaurav says:

    what if i want to check if username already exists in my MYSQL database??

  31. gaurav says:

    what if i want to check if username already exists in my MYSQL database??And i also want my password to be of atleast 6 characters.

    help me guys…..

    • SmrutiRanjan says:

      if you want to check existing user name, then query the input user name. API function is already written in the code.
      If yo want to check for at least 6 chars, then it is very simple. Just add a check in your code like [if(6>count){} x)] by counting the input characters before save it into the database

      • GG says:

        i want to prevent insertion of entries if username and password are already inserted in database. I tried to query that but no luck..Any help??

  32. Nitin says:

    Thanks for such a wonderful article. I have a question here. Is the database (that we have created) local to the device where the app is installed? On my registration page I am collecting the user info the very first time the app is installed and I need to store it somewhere just to keep a track of the users. There is no login page or I would say no login is required to use the app (just one time registration during installation). If the SQLite db instance that we are creating above is local to the device that i won’t be able to access the list of users.

    I hope you got my question. Please let me know if you need futher info.

  33. Arina says:

    hi, it’s a great post that I’ve been looking for. it’s just when I tried it, it force close when I try the sign in.
    for the LoginDatabaseAdapter and DatabaseAdapter, I unite it into 1 file DBAdapter.
    when I look into logcat, it said the error was in method DBAdapter.getSingleEntry(userName).

    below is the code, hope u can help me fix the error.

    public class DBAdapter extends SQLiteOpenHelper{

    static final String DATABASE_NAME = “login.db”;
    static final int DATABASE_VERSION = 1;
    public static final int NAME_COLUMN = 1;
    public SQLiteDatabase db;
    public DBAdapter dbAdapter;

    public DBAdapter(Context context)
    {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    //create database
    public void onCreate(SQLiteDatabase db)
    {
    db.execSQL(“CREATE TABLE login (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT, password TEXT);”);
    }

    //upgrade database
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
    {
    //not called since the 2nd version will not be created
    Log.w(“TaskDBAdapter”, “Upgrading database version”);
    }

    public DBAdapter open(){
    db = dbAdapter.getWritableDatabase();
    return dbAdapter;
    }

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

    public SQLiteDatabase getDatabaseInstance()
    {
    return db;
    }

    public void insertEntry(String userName, String password)
    {
    ContentValues cv = new ContentValues();
    cv.put(“USERNAME”, userName);
    cv.put(“PASSWORD”, password);
    getWritableDatabase().insert(“login”, null, cv);
    }

    public String getSingleEntry(String userName)
    {
    Cursor cursor=db.query(“LOGIN”, null, “USERNAME=?”, new String[]{userName}, null, null, null);
    if(cursor.getCount()<1) // UserName Not Exist
    {
    cursor.close();
    return "NOT EXIST";
    }
    cursor.moveToFirst();
    String password= cursor.getString(cursor.getColumnIndex("PASSWORD"));
    cursor.close();
    return password;
    }

    }

  34. Manoj says:

    In one scenario I got force close i.e. :
    1.launch the app
    2.signup with some data
    3.login with that credential
    O/P : force close
    Is there any way so that i can signup and login with that .

  35. mas says:

    hai sir.. can i know how to call user who login in other screen.. something like – Welcome (username).. -

  36. rishika says:

    Just awesome :)

  37. eshaan says:

    hi sir, this is badly urgent,
    how can i create activity after clicking sign in button. i jus want to go to another screen, can u post that code please.

  38. Cristian says:

    hello, congratulations for the post!
    I have a problem and ask for your help.
    I’m supposed to connect the application to a database with json and php but do not know how to do. could you help me ..
    thanks in advance.

  39. dubdabasoduba says:

    tnks great code u have here

  40. alloice says:

    after log in successful,,where do you insert code in HomeActivity so that it will destroy the signup activity and start another activity e.g a listview activity?

  41. hasan khan says:

    hai sir i want to do my m.tech project on android…so please give me some ideas about any latest projects

  42. Rumit Jain says:

    Hi,
    Thanks for your tutorial.
    I am not able to open loginDb file placed under DDMS->FileExplorer->data->data->myProject->databases.
    Its neither giving any error too. Could you please help me on this.

  43. Sowmiyanarayanan, S says:

    Hi SmrutiRanjan,

    I have one doubt. Whether login.db retains it old value whenever i restarts the emulator.

    Thank you in advance.

    Regards,
    Sowmiyanarayanan, S

  44. ram says:

    How do I view the SQLite database once I enter the data ?

  45. leela says:

    evrything is correct.no error.bt wen i click on sign in button..error “unfortunately stops” and takes to the main page…login dialog is not displayed.please help asap.please please

  46. ndyamuhaki joseph says:

    i would like u to put for me the android chat application code that works like that of facebook chat or whatsup. thanks very much. please help me

  47. Abhishek Jha says:

    Thanks a lot to you sir!!! I am new to this platform and i understood reasonably much.

  48. Saquib says:

    Thanks Pal for a wonderful example. Really helps a lot to understand the concept.

    I wanted to ask that you have created LoginDataBaseAdapter class separately, so if I want to use this code for my project I need to try through DBAdapter class or have to implement your class or need to create one.

  49. Arul says:

    Hi can u pls tell me i have created userlogin page but when am storing the multiple user data in a folder it is been viewed by other users too. Is there any solution to privatize for a registered user to keep his own data secure.

  50. Abhishek says:

    If You do so can you give the explanation of what u’ve made in a requirement way..it would be quite helpful for freshers like me…
    Thanks in Advance

    P.S. I need it the most

  51. Khanes says:

    Hey guy. Thank for this example. It’s very useful.

    If i will create Forgot Password. How can I do?

  52. Chethan says:

    Can you please post the tutorial about using AsyncTask and Thread Handler with the usage of ProgreeDialog. It may help lots of peoples like.
    Thanks in advance.

  53. sreenivas says:

    Sir,
    I created a Log in form I installed that one in my android phone, it is working well but when i switch off my and start my phone that app asking again user name and password.How to write a code without asking again user name and password like as gmail app plese reply to me or send mail to me…..

    • SmrutiRanjan says:

      Dear Sreenivas,
      Just add an boolean variable and store it. if user will login then just make it true and store. when start the app, just read and check this boolean value if it is already treu, don’t need to show the login activity. like this you can do

  54. Prasoon says:

    how to see the saved username and password..i run your program and i checked this File explorer>data>data
    but i only got some folders named “con”… what i do?

  55. samir says:

    thanks…..it’s amazing !!!

  56. rajsekhar says:

    Sir SmrthiRanjan sir i have dought..please send to me this type of program i will try 5 days onwards but iam not getting output.

  57. rajsekhar says:

    json server data store to sqlite database and then retriving data in listview form from sqlite.I need this very urgently please help me

  58. shyam says:

    Sir..thanks a lot for this tutorial. ..but I have created database in MySQL server…do I need to do any modifications in code…I mean will this current code shows error or it will work? ??
    pls help..need urgently Sir. ..:)

  59. raj says:

    Nice tutorial,But can you explain the logic of forget password and why are you instantiating a new class (i.e loginadapter).Its code can be written in the databaseadapter file…so why?
    can you explain..thankyou

  60. raj says:

    nice tutuorial,but can you explain why are you using an extra class (i.e login adapter) that part of coding can be done in databasehelper class.please can you explain.As i am a beginner so i got stuck in that problem and also can you explain the logic of forget password if passible.
    thanks!!!

  61. Cherie says:

    sorry, i didnt see it earlier. thanks!

  62. prateek says:

    sir i want to know that is there any way that the sign up can be done only once per app and then for the rest time it doesnt store the data..only a single account can be created..and the code which you showed is working fine but there is an error that if a person creates acc without putting any info on Create account page,the data is saved and then at the time of log in without putting and info in the log in page by pressing the log in button it says log in succesfull..try doing this if you are having the code with u..

  63. sekar says:

    Hi ranjan….. your post are simple and effective… i need code for view user details individually by using signup email address… how to display user details and how to update registered user detail… pls kindly send me the idea about it….

  64. alvinsa says:

    please help, how to add tables / columns? for additional signup, 3 column again I need to put my data. although still only to login using a username and password, thank you very much

  65. Bibin says:

    Do u know how to store the Username and password into the database without using Edit text?
    and these users only allow to login.?
    plz help me…

  66. Mohamed Saleh says:

    Nice work
    but how can i open new activity when you logged in with a correct user name and password
    i try

    if(password.equals(storedPassword)) {
    dialog.dismiss();
    Intent n=new Intent(Login.this, Mainlist.class);
    startActivity(n);
    Toast.makeText(Login.this, “Successful Login :)”,Toast.LENGTH_LONG).show();

    }

    put it didn’t work

  67. Gulnaz says:

    i also want to create a registration table in this, this example create only login table in SQLite ..

  68. forex trading online says:

    This is my first time pay a quick visit at here and i am truly happy to read all at alone place.

  69. Abhishek says:

    Hello Smruti!

    I tried running your program on my device, but unfortunately as it says that the application has encountered some problems and shuts down. Would you happen to know of a fix for this?

    Thank you!
    Abhishek

  70. Ashwajit suryawanshi says:

    Thanks a lot this post is very useful and simple but i just want to know how to upload a file from the device

  71. SmrutiRanjan says:

    creating Service in Android is very easy, I am getting so many request to update android service example.
    I will update the same in my blog asap.

  72. Thanx a lot. waiting for ur help

  73. LuffyX says:

    hey men what if i add contact number, first name, last name ? how this data stored in database ? what is the code ?

  74. Sandy says:

    In my app in need to send a verification to email address before signing up….Can u please help me in this

Leave a Reply

Your email address will not be published. Required fields are marked *


one + 7 =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">