Tuesday, March 12, 2013

Creating User Sign in Dialog In Android

Android Tutorials for Beginners

In this post we will develop an app in which a user can perform following task
1: User Can Create Account
2: User Can log in 

we will use and learn following this in this Post

Customized Dialog:  Here we have used  Customized Dialog   for User Login.
Creating DataBase:  Here we have created database for Storing   UserName and Password.
Writing functions for Inserting, Deleting, Updating and querying a Datbase.


we have create a Table with following Fields :

USERNAME :  to store the user name.
PASSWORD: to store the password of User

Table Name is LOGIN 


The Code is well commented  , just go through , you will understand easily.


Some More Good  Android Topics
Customizing Toast In Android 
 Showing Toast for Longer Time
Customizing Checkboxes In Android  
Customizing Progress Bar

 



  List of XMLs Used.



main.xml :   main screen
signup.xml : to create a new account
login.xml  :   to login


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:orientation="vertical"
    android:gravity="center_vertical" >



    <Button
        android:id="@+id/buttonSignIN"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
         android:text="Sign IN"
         android:onClick="signIn"/>

    <Button
        android:id="@+id/buttonSignUP"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Sign UP" />

</LinearLayout>


signup.xml




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center_vertical" >

    <EditText
        android:id="@+id/editTextUserName"
        android:hint="User Name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/editTextPassword"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
         android:hint="Password"
        android:inputType="textPassword" />

    <EditText
        android:id="@+id/editTextConfirmPassword"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="Confirm Password"
        android:inputType="textPassword" />

    <Button
        android:id="@+id/buttonCreateAccount"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Create Account"
        android:layout_marginBottom="60dp" />
   
</LinearLayout>



login.xml




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/editTextUserNameToLogin"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="User Name"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/editTextPasswordToLogin"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPassword"
        android:hint="Password" />

    <Button
        android:id="@+id/buttonSignIn"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Sign In" />

</LinearLayout>



Activities:


1:    HomeActivity.java


public class HomeActivity extends Activity
{
    
    Button btnSignIn,btnSignUp;
    LoginDataBaseAdapter loginDataBaseAdapter;
   
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
             super.onCreate(savedInstanceState);
             setContentView(R.layout.main);
            
             // create the instance of Databse
             loginDataBaseAdapter=new LoginDataBaseAdapter(this);
             loginDataBaseAdapter=loginDataBaseAdapter.open();
            
             // Get The Refference Of Buttons
             btnSignIn=(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  abd 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(HomeActivity.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 btnSignIn=(Button)dialog.findViewById(R.id.buttonSignIn);
               
                // Set On ClickListener
                btnSignIn.setOnClickListener(new View.OnClickListener() {
                   
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                       
                        // get The User name and Password
                        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(password.equals(storedPassword))
                        {
                            Toast.makeText(HomeActivity.this, "Login Successfull", Toast.LENGTH_LONG).show();
                            dialog.dismiss();
                        }
                        else
                        {
                           
                            Toast.makeText(HomeActivity.this, "User Name and Does Not Matches", Toast.LENGTH_LONG).show();
                        }
                       
                    }
                });
               
           
                 dialog.show();
               
               
               
    }



    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
       
        // Close The Database
        loginDataBaseAdapter.close();
    }
 
   
}

2:  SignUpActivity.java


public class SignUPActivity extends Activity
{
   
            EditText editTextUserName,editTextPassword,editTextConfirmPassword;
            Button btnCreateAccount;
           
            LoginDataBaseAdapter loginDataBaseAdapter;
            @Override
            protected void onCreate(Bundle savedInstanceState)
            {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.signup);
                   
                    // get Instance  of Database Adapter
                    loginDataBaseAdapter=new LoginDataBaseAdapter(this);
                    loginDataBaseAdapter=loginDataBaseAdapter.open();
                   
                    // Get Refferences of Views
                    editTextUserName=(EditText)findViewById(R.id.editTextUserName);
                    editTextPassword=(EditText)findViewById(R.id.editTextPassword);
                    editTextConfirmPassword=(EditText)findViewById(R.id.editTextConfirmPassword);
                   
                    btnCreateAccount=(Button)findViewById(R.id.buttonCreateAccount);
                   
                   
                    btnCreateAccount.setOnClickListener(new View.OnClickListener() {
                       
                        public void onClick(View v) {
                            // TODO Auto-generated method stub
                           
                            String userName=editTextUserName.getText().toString();
                            String password=editTextPassword.getText().toString();
                            String confirmPassword=editTextConfirmPassword.getText().toString();
                           
                            // check if any of the fields are vaccant
                            if(userName.equals("")||password.equals("")||confirmPassword.equals(""))
                            {
                                    Toast.makeText(getApplicationContext(), "Field Vaccant", Toast.LENGTH_LONG).show();
                                    return;
                            }
                            // check if both password matches
                            if(!password.equals(confirmPassword))
                            {
                                Toast.makeText(getApplicationContext(), "Password Does Not Matches", Toast.LENGTH_LONG).show();
                                return;
                            }
                            else
                            {
                                    // Save the Data in Database
                                    loginDataBaseAdapter.insertEntry(userName, password);
                                    Toast.makeText(getApplicationContext(), "Account Successfully Created ", Toast.LENGTH_LONG).show();
                            }
                           
                           
                        }
                    });
            }
            
           
            @Override
            protected void onDestroy() {
                // TODO Auto-generated method stub
                super.onDestroy();
               
                loginDataBaseAdapter.close();
            }

}

3:  DataBaseHelper.java


package com.example.login;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DataBaseHelper extends SQLiteOpenHelper
{
    public DataBaseHelper(Context context, String name,CursorFactory factory, int version)
    {
               super(context, name, factory, version);
    }
    // Called when no database exists in disk and the helper class needs
    // to create a new one.
    @Override
    public void onCreate(SQLiteDatabase _db)
    {
            _db.execSQL(LoginDataBaseAdapter.DATABASE_CREATE);
           
    }
    // Called when there is a database version mismatch meaning that the version
    // of the database on disk needs to be upgraded to the current version.
    @Override
    public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion)
    {
            // Log the version upgrade.
            Log.w("TaskDBAdapter", "Upgrading from version " +_oldVersion + " to " +_newVersion + ", which will destroy all old data");
   
   
            // Upgrade the existing database to conform to the new version. Multiple
            // previous versions can be handled by comparing _oldVersion and _newVersion
            // values.
            // The simplest case is to drop the old table and create a new one.
            _db.execSQL("DROP TABLE IF EXISTS " + "TEMPLATE");
            // Create a new one.
            onCreate(_db);
    }
   

}

4: LoginDataBaseAdapter.java


public class LoginDataBaseAdapter
{
            static final String DATABASE_NAME = "login.db";
     
            static final int DATABASE_VERSION = 1;

            public static final int NAME_COLUMN = 1;
            // TODO: Create public field for each column in your table.
            // SQL Statement to create a new database.
            static final String DATABASE_CREATE = "create table "+"LOGIN"+
                                         "( " +"ID"+" integer primary key autoincrement,"+ "USERNAME  text,PASSWORD text); ";
                                        
            // Variable to hold the database instance
            public  SQLiteDatabase db;
            // Context of the application using the database.
            private final Context context;
            // Database open/upgrade helper
            private DataBaseHelper dbHelper;
            public  LoginDataBaseAdapter(Context _context)
            {
                    context = _context;
                    dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
            }

             // Method to openthe Database 
            public  LoginDataBaseAdapter open() throws SQLException
            {
                    db = dbHelper.getWritableDatabase();
                    return this;
            }
         
            // Method to close the Database 
            public void close()
            {
                    db.close();
            }
  
             // method returns an Instance of the Database
            public  SQLiteDatabase getDatabaseInstance()
            {
                    return db;
            }
   
              // method to insert a record in Table
            public void insertEntry(String userName,String password)
            {
                      
                    
                       ContentValues newValues = new ContentValues();
                        // Assign values for each column.
                        newValues.put("USERNAME", userName);
                        newValues.put("PASSWORD",password);
                      
                      
                      
                        // Insert the row into your table
                        db.insert("LOGIN", null, newValues);
                        Toast.makeText(context, "User Info Saved", Toast.LENGTH_LONG).show();
          
      
            }
          
           // method to delete a Record of UserName
            public int deleteEntry(String UserName)
            {
                    
                   String where="USERNAME=?";
                   int numberOFEntriesDeleted= db.delete("LOGIN", where, new String[]{UserName}) ;
                   Toast.makeText(context, "Number fo Entry Deleted Successfully : "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show();
                return numberOFEntriesDeleted;
              
            }
      
       // method to get the password  of userName
        public String getSinlgeEntry(String userName)
        {
          
              
                Cursor cursor=db.query("LOGIN", null, " USERNAME=?", new String[]{userName}, null, null, null);
                if(cursor.getCount()<1) // UserName Not Exist
                    return "NOT EXIST";
                cursor.moveToFirst();
                String password= cursor.getString(cursor.getColumnIndex("PASSWORD"));
                return password;
              
          
        }

     // Method to Update an Existing Record
        public void  updateEntry(String userName,String password)
        {
                //  create object of ContentValues
                ContentValues updatedValues = new ContentValues();
                // Assign values for each Column.
                updatedValues.put("USERNAME", userName);
                updatedValues.put("PASSWORD",password);
              
                String where="USERNAME = ?";
                db.update("LOGIN",updatedValues, where, new String[]{userName});
             
        }
      
      
}




 

Advance Android Topics


                   Customizing Toast In Android 
                   Showing Toast for Longer Time
                   Customizing the Display Time of Toast
                   Using TimePickerDialog and DatePickerDialog In android
                   Animating A Button In Android
                    Populating ListView With DataBase

                    Customizing Checkboxes In Android 
                    Increasin Size of Checkboxes
                    Android ProgressBar
                    Designing For Different Screen Sizes
                    Handling Keyboard Events


More Android Topics:

Android : Introduction


       Eclipse Setup for Android Development

                     Configuring Eclipse for Android Development

          Begging With Android

                     Creating Your First Android Project
                     Understanding Android Manifest File of your android app


         Working With Layouts

                      Understanding Layouts in Android
                          Working with Linear Layout (With Example)
                                Nested Linear Layout (With Example)
                          Table Layout
                          Frame Layout(With Example)
                         Absolute Layout
                         Grid Layout


       Activity

                     Activity In Android
                     Activity Life Cycle
                     Starting Activity For Result
                     Sending Data from One Activity to Other in Android
                     Returning Result from Activity

     Working With Views

                     Using Buttons and EditText in Android 
                     Using CheckBoxes in Android 
                     Using AutoCompleteTextView in Android
                     Grid View

       Toast

                     Customizing Toast In Android
                     Customizing the Display Time of Toast
                     Customizing Toast At Runtime
                     Adding Image in Toast
                     Showing Toast for Longer Time

     Dialogs In Android

                     Working With Alert Dialog
                     Adding Radio Buttons In Dialog
                     Adding Check Boxes In Dialog
                     Creating Customized Dialogs in Android
                    Adding EditText in Dialog

                   Creating Dialog To Collect User Input

                 DatePicker and TimePickerDialog

                              Using TimePickerDialog and DatePickerDialog In android

    Working With SMS

                  How to Send SMS in Android
                  How To Receive SMS
                  Accessing Inbox In Android

    ListView:

               Populating ListView With DataBase

      Menus In Android

                    Creating Option Menu
                    Creating Context Menu In Android

      TelephonyManager

                    Using Telephony Manager In Android

     Working With Incoming Calls

                    How To Handle Incoming Calls in Android
                    How to Forward an Incoming Call In Android
                   CALL States In Android
 

    Miscellaneous

                   Notifications In Android
                   How To Vibrate The Android Phone
                   Sending Email In Android
                  Opening a webpage In Browser
                   How to Access PhoneBook In Android
                   Prompt User Input with an AlertDialog

   Storage:  Storing Data In Android


               Shared Prefferences  In Android

                             SharedPreferences In Android

               Files: File Handling In Android

                              Reading and Writing files to Internal Stoarage
                              Reading and Writing files to SD Card 
                           

                DataBase : Working With Database

                             Working With Database in Android
                             Creating Table In Android
                             Inserting, Deleting and Updating Records In Table in Android
                             How to Create DataBase in Android
                             Accessing Inbox In Android

     Animation In Android:

                  Animating A Button In Android





22 comments:

  1. Excellent post. This post is really very useful.Thanks a lot for sharing.


    android application development

    ReplyDelete
  2. Thanks for sharing
    Good working

    ReplyDelete
  3. Superb post..dude...very helpful thanksss.

    ReplyDelete
  4. thanks for the post really helpfull

    ReplyDelete
  5. i resolved the error on the main page of Not opening of SIGN iN page as i have created the SIGN IN class but now i am having another error..at the dialog box while entering the username and password..when i click on log in..its gives an error and force closes..and rest is working fine..i think it is not able to fetch the data from the database.. i am providing you with the three files in which the error could recide..plz tell me what should i do..


    ReplyDelete
  6. hey..hi there i want to ask you that is there no need to add the SignINActivity..as you added SignUPActivity,HomeActivity,DataBaseHelper,LoginDatabaseAdapter..i think there is also a need of SignINActivity.java without which the log in Option of The dialog Box is not working just at clicking it force closes..plzzz do helppp

    ReplyDelete
  7. Hello Kamlesh.
    this is realy a great help. thank you very much.
    could you please help me out with telneting/ remote login codes for android app?? any telnet/remote login project will be of great help.

    ReplyDelete
  8. I used this code and getting error on line "LoginDataBaseAdapter loginDataBaseAdapter" as LoginDataBaseAdapter cannot be resolved or is not a field..Is this because of version using..? (i am using java 1.7_45 and Eclipse Indigo service 2)

    ReplyDelete
  9. You have done a great work Mr Kamalesh ... How could i develop logout funcutionality

    ReplyDelete
  10. The App was clear coded. But I think you should also post the "manifest.xml" to people get to the point.

    ReplyDelete
  11. Sir, my sign up button is not functioning even though there is no error. Please help me.

    ReplyDelete
  12. Sir, my sign up button is not functioning even though there is no error. Please help me.

    ReplyDelete
    Replies
    1. You need to add the Sign Up activity in your Project's AndroidManifest.xml file

      Delete
  13. how do i change to next page upon successful login in ?

    ReplyDelete
  14. how do i change to another page upon successful login in ?

    ReplyDelete
  15. I have tried this several times but it is not running I don't know why yet everything is joust the same I don't know if you can help in any way

    ReplyDelete
  16. Today, I went to the beach with my children. I found a sea
    shell annd gave it to myy 4 year old daughter and said "You can hear the ocean if you put this to your ear." She placed
    the shell to her eaar and screamed. There was a hermit crab inside and it pinched herr ear.
    She nevsr wants to go back! LoL I knnow this is totally off topic but I
    had to tell someone!

    ReplyDelete