Android Code for User Registration and Login

Hi friends, recently i met success in creating an android application for the user registration and login. am so happy to share this code with you all...


Here is my code, it containing a Database, User Interface and Coding part.




First we'll start with xml coding. 
this is the code for user login page.

main.xml 


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


    <TextView
        android:id="@+id/Luname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="User Name"
      
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:textAppearance="?android:attr/textAppearanceLarge" />


    <EditText
        android:id="@+id/Ledituname"
        
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
        android:singleLine="true"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp">


        <requestFocus />
    </EditText>


    <TextView
        android:id="@+id/Lpass"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Password"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:textAppearance="?android:attr/textAppearanceLarge" />


    <EditText
        android:id="@+id/Leditpw"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPassword" 
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"/>


    <RelativeLayout
        android:id="@+id/relativeLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
        
        <Button
        android:id="@+id/login"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:text="Login" />




    <Button
        android:id="@+id/register"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Register" 
        android:layout_toRightOf="@id/login"/>
    
    </RelativeLayout>


    
        
</LinearLayout>


register.xml


<?xml version="1.0" encoding="utf-8"?>



    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/scrollView1" 
        android:layout_width="match_parent" 
        android:layout_height="wrap_content">
        
        <LinearLayout 
            
            android:id="@+id/linearLayout1" 
            android:layout_width="match_parent" 
            android:layout_height="match_parent"
            android:orientation="vertical">
    <TextView
        android:id="@+id/fname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="First Name"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:textAppearance="?android:attr/textAppearanceLarge" />


    <EditText
        android:id="@+id/efname"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:singleLine="true">


        <requestFocus />
    </EditText>


    <TextView
        android:id="@+id/lname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Last Name"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:textAppearance="?android:attr/textAppearanceLarge" />


    <EditText
        android:id="@+id/elname"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:singleLine="true"/>


    <TextView
        android:id="@+id/rgender"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Gender"
         android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:textAppearance="?android:attr/textAppearanceLarge" />


    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        
        android:drawSelectorOnTop="true" />


    <TextView
        android:id="@+id/runame"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="User Name"
         android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:textAppearance="?android:attr/textAppearanceLarge" />


    <EditText
        android:id="@+id/reuname"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
         android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"/>


    <TextView
        android:id="@+id/rpass"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Password"
         android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:textAppearance="?android:attr/textAppearanceLarge" />


    <EditText
        android:id="@+id/repass"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPassword" 
         android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"/>


    <TextView
        android:id="@+id/email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Email"
         android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:textAppearance="?               android:attr/textAppearanceLarge" />


    <EditText
        android:id="@+id/eemail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress" 
         android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"/>


    


    <RelativeLayout
        android:id="@+id/relativeLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
        
         <Button
        android:id="@+id/submit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Submit" 
         android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"/>


    <Button
        android:id="@+id/cancel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Cancel" 
        android:layout_toRightOf="@id/submit"/>
    
    </RelativeLayout>
</LinearLayout>
   </ScrollView>


welcome1.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:background="@drawable/an"
    android:orientation="vertical" >


    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >


        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/edittext1"
            android:layout_alignBottom="@+id/edittext1"
            android:layout_alignParentLeft="true"
            android:text="@string/text"
            android:textAppearance="?android:attr/textAppearanceLarge" />


        


        <TextView
            android:id="@+id/textV"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:layout_marginLeft="100dp"
            
            android:textAppearance="?android:attr/textAppearanceLarge" />


    </RelativeLayout>


    <Button
        android:id="@+id/buttonSearch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="search"
        android:text="View Details" />


  


    <ListView
        android:id="@android:id/list"
        android:layout_width="wrap_content"
        android:layout_height="242dp"
        android:layout_weight="0.72" >
    </ListView>


</LinearLayout>




dtl.xml



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


    <TextView
        android:id="@+id/sfname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        
        android:textAppearance="?android:attr/textAppearanceLarge" android:textColorHighlight="#000000"/>


    <TextView
        android:id="@+id/slname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/sfname"
        android:paddingLeft="5dp"
        android:textAppearance="?android:attr/textAppearanceLarge" />
   
    
     <TextView
        android:id="@+id/sgender"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/slname"
        android:paddingLeft="5dp"
        android:textAppearance="?android:attr/textAppearanceLarge" />
    <TextView
        android:id="@+id/suname"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        
        android:layout_below="@id/sgender"
        android:textAppearance="?android:attr/textAppearanceLarge" />
    
    <TextView
        android:id="@+id/semail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#000000"
        android:layout_below="@id/suname"
        android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>



Now we'll code our database helper file.


DBHelper.java


package my.DataBase;


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


public class DBHelper extends SQLiteOpenHelper 


{
private SQLiteDatabase db;
public static final String KEY_ROWID = "_id";
    public static final String KEY_FNAME = "firstname";
    public static final String KEY_LNAME = "lastname";
    public static final String KEY_GENDER = "gender";
    public static final String KEY_USER = "username";
    public static final String KEY_EMAIL = "email";
    


DBHelper DB = null;
private static final String DATABASE_NAME = "srikanth1.db";
private static final int DATABASE_VERSION = 2;
    public static final String DATABASE_TABLE_NAME = "sri1";
    
    private static final String DATABASE_TABLE_CREATE =
            "CREATE TABLE " + DATABASE_TABLE_NAME + "(" +
            "_id INTEGER PRIMARY KEY AUTOINCREMENT,"+
            "firstname TEXT NOT NULL, lastname TEXT NOT NULL, gender TEXT NOT NULL, username TEXT NOT NULL, password TEXT NOT NULL, email TEXT NOT NULL);";
public DBHelper(Context context) {

super(context, DATABASE_NAME, null, DATABASE_VERSION);
System.out.println("In constructor");
}




@Override
public void onCreate(SQLiteDatabase db) {

try{

db.execSQL(DATABASE_TABLE_CREATE);



}catch(Exception e){
e.printStackTrace();
}
}






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

}




public Cursor rawQuery(String string, String[] strings) {
// TODO Auto-generated method stub
return null;
}




public void open() {

getWritableDatabase();
}


public Cursor getDetails(String text) throws SQLException 
{

    Cursor mCursor =
            db.query(true, DATABASE_TABLE_NAME, 
            new String[]{KEY_ROWID, KEY_FNAME, KEY_LNAME, KEY_GENDER, KEY_USER, KEY_EMAIL}, 
            KEY_USER + "=" + text, 
            null, null, null, null, null);
    if (mCursor != null) 
    {
        mCursor.moveToFirst();
    }
    return mCursor;


}


}







Here are my Registration and login classes.


Registration.java



package my.DataBase;


import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;


public class Registration extends Activity implements OnClickListener, OnItemSelectedListener


{
// Variable Declaration should be in onCreate()
private Button mSubmit;
private Button mCancel;

private EditText mFname;
private EditText mLname;
private EditText mUsername;
private EditText mPassword;
private EditText mEmail;
private Spinner mGender;
private String Gen;

protected DBHelper DB = new DBHelper(Registration.this); 

@Override
protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.register);

//Assignment of UI fields to the variables
mSubmit = (Button)findViewById(R.id.submit);
mSubmit.setOnClickListener(this);

mCancel = (Button)findViewById(R.id.cancel);
mCancel.setOnClickListener(this);

mFname = (EditText)findViewById(R.id.efname);
mLname = (EditText)findViewById(R.id.elname);

mUsername = (EditText)findViewById(R.id.reuname);
mPassword = (EditText)findViewById(R.id.repass);
mEmail = (EditText)findViewById(R.id.eemail);


mGender = (Spinner)findViewById(R.id.spinner1);

// Spinner method to read the on selected value
ArrayAdapter<State> spinnerArrayAdapter = new ArrayAdapter<State>(this,
             android.R.layout.simple_spinner_item, new State[] {
        new State("Male"), 
        new State("Female")});
mGender.setAdapter(spinnerArrayAdapter);
mGender.setOnItemSelectedListener(this);
}



public void onClick(View v) 
{

switch(v.getId()){

case R.id.cancel:
Intent i = new Intent(getBaseContext(), LoginActivity.class);
startActivity(i);
//finish();
break;

case R.id.submit:


String fname = mFname.getText().toString();
String lname = mLname.getText().toString();

String uname = mUsername.getText().toString();
String pass = mPassword.getText().toString();
String email = mEmail.getText().toString();


boolean invalid = false;

if(fname.equals(""))
{
invalid = true;
Toast.makeText(getApplicationContext(), "Enter your Firstname", Toast.LENGTH_SHORT).show();
}
else

if(lname.equals(""))
{
invalid = true;
Toast.makeText(getApplicationContext(), "Please enter your Lastname", Toast.LENGTH_SHORT).show();
}
else

if(uname.equals(""))
{
invalid = true;
Toast.makeText(getApplicationContext(), "Please enter your Username", Toast.LENGTH_SHORT).show();
}
else


if(pass.equals(""))
{
invalid = true;
Toast.makeText(getApplicationContext(), "Please enter your Password", Toast.LENGTH_SHORT).show();

}
else 
if(email.equals(""))
{
invalid = true;
Toast.makeText(getApplicationContext(), "Please enter your Email ID", Toast.LENGTH_SHORT).show();
}
else
if(invalid == false)
{
addEntry(fname, lname, Gen, uname, pass, email);
Intent i_register = new Intent(Registration.this, LoginActivity.class);
startActivity(i_register);
//finish();
}

break;
}
}





public void onDestroy()
{
super.onDestroy();
DB.close();
}



private void addEntry(String fname, String lname, String Gen, String uname, String pass, String email) 
{

SQLiteDatabase db = DB.getWritableDatabase();

ContentValues values = new ContentValues();
values.put("firstname", fname);
values.put("lastname", lname);
values.put("gender", Gen);
values.put("username", uname);
values.put("password", pass);
values.put("email", email);

try
{
db.insert(DBHelper.DATABASE_TABLE_NAME, null, values);

Toast.makeText(getApplicationContext(), "your details submitted Successfully...", Toast.LENGTH_SHORT).show();
}
catch(Exception e)
{
e.printStackTrace();
}
}


public void onItemSelected(AdapterView<?> parent, View view, int position, long id) 
   {
    // Get the currently selected State object from the spinner
    State st = (State)mGender.getSelectedItem();
   
    // Show it via a toast
  toastState( "onItemSelected", st );
   } 


public void toastState(String name, State st) 
{
if ( st != null )
    {
Gen = st.name;
//Toast.makeText(getBaseContext(), Gen, Toast.LENGTH_SHORT).show();

    }

}


public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub

}

}


LoginActivity.java

package my.DataBase;

import my.DataBase.R;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends Activity implements OnClickListener 
{
Button mLogin;
Button mRegister;
EditText muname;
EditText mpassword;
DBHelper DB = null;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    
        mRegister = (Button)findViewById(R.id.register);
        mRegister.setOnClickListener(this);
        
        mLogin = (Button)findViewById(R.id.login);
        mLogin.setOnClickListener(this); 
        
    }


public void onClick(View v) 
{
switch(v.getId())
{
case R.id.register:
Intent i = new Intent(getBaseContext(), Registration.class);
startActivity(i);
break;
case R.id.login:
muname = (EditText)findViewById(R.id.Ledituname);
mpassword = (EditText)findViewById(R.id.Leditpw);
String username = muname.getText().toString();
String password = mpassword.getText().toString();
if(username.equals("") || username == null)
{
Toast.makeText(getApplicationContext(), "Please enter User Name", Toast.LENGTH_SHORT).show();
}
else if(password.equals("") || password == null)
{
Toast.makeText(getApplicationContext(), "Please enter your Password", Toast.LENGTH_SHORT).show();
}
else
{
boolean validLogin = validateLogin(username, password, getBaseContext());
if(validLogin)
{
//System.out.println("In Valid");
Intent in = new Intent(getBaseContext(), Welcome1.class);
in.putExtra("UserName", muname.getText().toString());
startActivity(in);
//finish();
}
}
break;
}
}


private boolean validateLogin(String username, String password, Context baseContext) 
{
DB = new DBHelper(getBaseContext());
SQLiteDatabase db = DB.getReadableDatabase();
String[] columns = {"_id"};
String selection = "username=? AND password=?";
String[] selectionArgs = {username,password};
Cursor cursor = null;
try{
cursor = db.query(DBHelper.DATABASE_TABLE_NAME, columns, selection, selectionArgs, null, null, null);
startManagingCursor(cursor);
}
catch(Exception e)
{
e.printStackTrace();
}
int numberOfRows = cursor.getCount();
if(numberOfRows <= 0)
{
Toast.makeText(getApplicationContext(), "User Name and Password miss match..\nPlease Try Again", Toast.LENGTH_LONG).show();
Intent intent = new Intent(getBaseContext(), LoginActivity.class);
startActivity(intent);
return false;
}
return true;
}
public void onDestroy()
{
super.onDestroy();
DB.close();
}
}


Here is State.java class for reading the spinner values.

public class State 
{
public String name = "";
public State(String _name)
{
name = _name;
}
public String toString()
{
return name;
}
}


Welcome1.java

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

public class Welcome1 extends ListActivity
{

protected TextView eun;
protected SQLiteDatabase DB;
protected Cursor cursor;
protected ListAdapter adapter;
protected TextView mUname;
protected TextView mFname;
protected TextView mLname;
protected TextView mEmail;
@Override
   public void onCreate(Bundle savedInstanceState) 
   {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.welcome1);
       
       
      DB = (new DBHelper(this)).getWritableDatabase();
      // searchText = (EditText) findViewById (R.id.searchText);
       
       eun = (TextView)findViewById(R.id.textV);
Bundle bundle = getIntent().getExtras();
String UName = bundle.getString("UserName");
eun.setText(UName);
   }
 
public void search(View view)
{
cursor = DB.rawQuery("SELECT _id, firstname, lastname, gender, username, email FROM sri1 WHERE username LIKE ?", 
new String[] {"%" + eun.getText().toString() + "%"});
adapter = new SimpleCursorAdapter(
this,
R.layout.dtl,
cursor,
new String[] {"firstname", "lastname", "gender","username", "email"},
new int[] {R.id.sfname, R.id.slname, R.id.sgender , R.id.suname, R.id.semail});
 
setListAdapter(adapter);
}
 
@Override
public void onBackPressed() 
{
super.onBackPressed();
Intent i = new Intent(Welcome1.this, LoginActivity.class);
startActivity(i);
}
 }





Comments

  1. it is very good but it will be the best if u have also given a screen shots....

    ReplyDelete
  2. plz do put screen shots after each possible place if possible in 2 days....

    ReplyDelete
  3. Application Force Closes :(. Help pls .. Here is my code

    https://docs.google.com/open?id=0B8MQ5JswY4IiRHVJZkt4WDF3cTg

    ReplyDelete
    Replies
    1. You Should declare each activity in the Manifest.xml file. Add both the activities in your Manifest. It'll work.

      Delete
    2. i hope you put a screenhots...

      Delete
    3. the registration form...u did it all in eclipse??

      Delete
  4. It works for the most part. However, if one registers as a new user, it is not allowing to login with the information you just registered with.

    ReplyDelete
    Replies
    1. when i click on login button after registration is succesful, the app stops running it shows force close? what should i do

      Delete
    2. registration code i dont no
      what is the code ...tankyou...

      Delete
  5. Is this better or worse than using AsyncTask?

    ReplyDelete
    Replies
    1. You can use this for small database operations.

      Delete
    2. You can use this for small database operations.

      Delete
  6. Whenever I run the app and click on either Login or Register button, it takes me to no where!
    It feels like, I have only created the layout! I hope you reply asap!

    ReplyDelete
    Replies
    1. You know why? because this code in the blog is incomplete, he gave us the main.xml code file but he didnt post the code in main.java file. thats why when you run it, nothing will happen

      Delete
  7. Error:Execution failed for task ':app:mergeDebugResources'.
    > Some file crunching failed, see logs for details
    plse solve my problem and describe this type of error how to find

    ReplyDelete
  8. this code is incomplete. you have main.xml code file but you dont have main.java code. Thats why when you click log in or register, nothing happens.

    ReplyDelete
  9. How to retrive password from listview satish

    ReplyDelete
  10. When i click on register button iam getting unfortunately my app has been stopped and there are no errors in my code.

    ReplyDelete
  11. is this better than first making the mysql API for ANdroid?

    ReplyDelete
  12. Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more ... good luck.
    Android Training in chennai | Android Training

    ReplyDelete
  13. its good and also include the screen short of each pages

    ReplyDelete
  14. Great Work, still lot more to do but it is very helpful. Thanks

    ReplyDelete

Post a Comment