Like Us on Facebook

Android Registration And Login with PHP and MYSQL

Welcome to the  tutorial  Android  Registration and login with  PHP and  MYSQL .here  we will create an app  where user can register   with their   specific  details  and  can login to the system . If any user  have already registerd  they can login to the system  And after the logout  from the system user will redirect  to the login page . If any user enter wrong  user details during login then he or she  will get error message.This application can be further  improved  with the  the reset password or the forgot password  facility.


Prerequisites:
 
  • JDK 7.0 or above
  • Android Studio 2.0


Steps to follow:  
 
  1. Create a New Android Studio project name Androidlogin.
  2. Select minimum  API level 16 so it will run maximum of Android device that are Active on google Play then click next.
  3. Select Blank Activity and your Activity name is MainActivityclick next.
  4. Give your layout xml name is activity_main  and Click finish.
  5. Now create two more java class  Register.java and Login .java  and the corresponding Xml files of this two java class is  activity_register.xml and activity_login.xml .
  6. Now  your activity_main.xml file will be like the following 
 
<RelativeLayoutxmlns: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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.tutorial.androidlogin.Login">
 
 
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:ems="10"
android:id="@+id/et_email"
android:layout_below="@+id/et_Name"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="30dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
 
 
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Logout"
android:id="@+id/bt_logout"
android:textColor="#ffffff"
android:background="#5882FA"
android:layout_below="@+id/et_email"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="44dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>



7. Configure your activity_register.xml like below
 
<RelativeLayoutxmlns: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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.tutorial.androidlogin.Login">
 
<TextViewandroid:text="@string/title_activity_register"
android:textSize="25sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView" />
 
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="@+id/et_Name"
android:layout_below="@+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="40dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
 
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:ems="10"
android:id="@+id/et_email"
android:layout_below="@+id/et_Name"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="30dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
 
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="phone"
android:ems="10"
android:id="@+id/et_phone"
android:layout_below="@+id/et_email"
android:layout_marginTop="30dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
 
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:id="@+id/et_pwd"
android:layout_below="@+id/et_phone"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="30dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
 
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Register"
android:id="@+id/bt_register"
android:textColor="#ffffff"
android:background="#5882FA"
android:layout_below="@+id/et_pwd"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="30dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
 
 
 
8. Configure your activity_login.xml like below .
 
<RelativeLayoutxmlns: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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.tutorial.androidlogin.Login">
 
<TextView
android:text="@string/title_activity_login"
android:textSize="25sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView"/>
 
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/et_UserName"
android:layout_below="@+id/textView"
android:layout_marginTop="30dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"/>
 
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:id="@+id/et_password"
android:layout_below="@+id/et_UserName"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="34dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
 
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="login"
android:textColor="#ffffff"
android:background="#5882FA"
android:id="@+id/bt_login"
android:layout_below="@+id/et_password"
android:layout_marginTop="34dp"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
 
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Register Here"
android:textSize="20sp"
android:id="@+id/registerLink"
android:layout_below="@+id/bt_login"
android:layout_centerHorizontal="true"
android:layout_marginTop="42dp"/>
 
</RelativeLayout>



9. Now inside main Activity write the following code
 
public class MainActivity extends Activity implements View.OnClickListener{
 
    Button bt_logout;
EditTextet_email,et_Name,et_phone;
 
UserLocalStoreuserLocalStore;
 
 
    @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_Name = (EditText)findViewById(R.id.et_Name);
et_email= (EditText)findViewById(R.id.et_email);
et_phone = (EditText)findViewById(R.id.et_phone);
bt_logout = (Button)findViewById(R.id.bt_logout);
et_email = (EditText)findViewById(R.id.et_email);
 
 
bt_logout.setOnClickListener(this);
 
userLocalStore = new UserLocalStore(this);
    }
 
    @Override
protected void onStart() {
super.onStart();
if(authenticate()==true){
 
DisplayUserDetails();
 
}else{
 
startActivity(new Intent(MainActivity.this , Login.class));
 
        }
 
 
 
    }
 
private void DisplayUserDetails() {
 
        User user = userLocalStore.getLoggedInUser();
 
et_Name.setText(user.name);
et_email.setText(user.email);
et_phone.setText(user.phone+ "");
 
 
    }
 
publicboolean authenticate(){
 
returnuserLocalStore.getUserLoggedIn();
 
 
    }
 
 
 
 
 
    @Override
public void onClick(View v) {
 
switch(v.getId()){
 
caseR.id.bt_logout:
 
userLocalStore.clearUserdata();
userLocalStore.setUserLoggedIn(false);
 
startActivity(new Intent(this, Login.class));
 
break;
 
 
 
        }
 
 
    }
}



10. Inside Register.java write the following code  .
 
public class Register extends Activity implements View.OnClickListener {
 
    Button bt_register;
EditTextet_Name, et_email,et_phone,et_pwd;
 
    @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
bt_register = (Button)findViewById(R.id.bt_register);
et_Name = (EditText)findViewById(R.id.et_Name);
et_email= (EditText)findViewById(R.id.et_email);
et_phone = (EditText)findViewById(R.id.et_phone);
et_pwd = (EditText)findViewById(R.id.et_pwd);
 
bt_register.setOnClickListener(this);
 
    }
 
 
    @Override
public void onClick(View v) {
 
switch(v.getId()){
 
caseR.id.bt_register:
 
                String name = et_Name.getText().toString();
                String email = et_email.getText().toString();
int phone  =Integer.parseInt(et_phone.getText().toString());
                String password = et_pwd.getText().toString();
 
                User user = new User(name,email,password,phone);
 
registerUser(user);
 
break;
 
        }
 
    }
 
private void registerUser(User user) {
 
ServerRequestsserverRequests = new ServerRequests(this);
serverRequests.storeUserDataInBackground(user, new GetUserCallback() {
               @Override
public void done(User returnedUser) {
 
startActivity(new Intent(Register.this , Login.class));
 
               }
           });
 
 
    }
 


11. Inside Login.java write the following code.
 
public class Login extends Activity implements View.OnClickListener{
    Button bt_login;
EditTextet_username;
EditTextet_password;
TextViewregisterlink;
UserLocalStoreuserLocalStore;
 
 
    @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
 
bt_login = (Button)findViewById(R.id.bt_login);
et_username=(EditText)findViewById(R.id.et_UserName);
et_password=(EditText)findViewById(R.id.et_password);
registerlink =(TextView)findViewById(R.id.registerLink);
 
bt_login.setOnClickListener( this);
 
registerlink.setOnClickListener(this);
 
userLocalStore = new UserLocalStore(this);
 
    }
 
 
    @Override
public void onClick(View v) {
 
switch(v.getId()){
 
caseR.id.bt_login:
                String username = et_username.getText().toString();
                String password = et_password.getText().toString();
 
                User user = new User(username,password);
 
 
authenticate(user);
break;
 
caseR.id.registerLink:
 
startActivity(new Intent(this,Register.class));
 
break;
 
 
        }
 
    }
 
private void authenticate(User user) {
 
ServerRequestsserverrequests = new ServerRequests(this);
serverrequests.fetchUserDataInBackground(user, new GetUserCallback() {
            @Override
public void done(User returnedUser) {
 
if(returnedUser == null){
 
showErrorMessage();
}else{
 
LogUserIn(returnedUser);
 
                }
 
            }
        });
    }
 
private void showErrorMessage(){
 
AlertDialog.Builderdialogbuilder = new AlertDialog.Builder(Login.this);
 
dialogbuilder.setMessage("Incorrect Details ");
dialogbuilder.setPositiveButton("ok" , null);
dialogbuilder.show();
 
    }
 
private void LogUserIn(User returnedUser){
 
userLocalStore.setUserLoggedIn(true);
userLocalStore.storeUserData(returnedUser);
 
startActivity(new Intent(this , MainActivity.class));
 
    }
 
 
 
}
 


12. Now you need to create three more java class for the Application User.java, ServerRequestes.java, UserLocalstore.java
 

13. Inside User.java write the following code
 
public class User {
 
    String name,email,password ;
int phone;
 
 
public User(String name ,String email ,String password ,int phone){
 
         this.name = name;
this.email = email;
this.password = password;
this.phone = phone;
 
 
     }
 
 
public User(String name ,String password){
 
         this.name = name;
this.password = password;
this.phone = -1;
this.email = "";
 
 
     }
 
     }
 


14. InsideServerRequests.java write the following code 
 
public class ServerRequests {
 
ProgressDialogprogressDialog;
public static final int CONNECTION_TIMEOUT = 1000 * 15;
public static  final String SERVER_ADDRESS = "http://lok8.hostingsiteforfree.com";
 
public  ServerRequests(Context context){
progressDialog = new ProgressDialog(context);
progressDialog.setCancelable(false);
progressDialog.setTitle("Processing");
progressDialog.setMessage("Please Wait...");
 
    }
 
public void storeUserDataInBackground(User user, GetUserCallbackuserCallback){
progressDialog.show();
newStoreUserDataAsyncTask(user,userCallback).execute();
    }
 
public void fetchUserDataInBackground(User user, GetUserCallback callback) {
progressDialog.show();
newfetchUserDataAsyncTask(user, callback).execute();
 
    }
 
public class StoreUserDataAsyncTask extends AsyncTask<Void, Void, Void>{
        User user;
GetUserCallbackuserCallback;
 
publicStoreUserDataAsyncTask(User user, GetUserCallbackuserCallback){
this.user = user;
this.userCallback = userCallback;
        }
 
        @Override
protected Void doInBackground(Void... params) {
 
ArrayList<NameValuePair>dataToSend = new ArrayList<>();
dataToSend.add(new BasicNameValuePair("name", user.name));
dataToSend.add(new BasicNameValuePair("phone", user.phone + ""));
dataToSend.add(new BasicNameValuePair("email", user.email));
dataToSend.add(new BasicNameValuePair("password", user.password));
 
 
 
            /*possible alternative code found on stack overflow don't know exactly what to do from here.
ContentValues values= new ContentValues();
values.put("firstname", user.name);
values.put("lastname", user.email);
values.put("age", user.phone + "");
values.put("password",user.password);
            */
 
HttpParamshttpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);
 
HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpClient post = new HttpPost(SERVER_ADDRESS + "Register.php");
 
try{
post.setEntity(new URLEncoderFormEntity(values));
client.execute(post);
}catch (Exception e){
e.printStackTrace();
            }
 
 
return null;
        }
 
        @Override
protected void onPostExecute(Void aVoid) {
progressDialog.dismiss();
userCallback.done(null);
 
super.onPostExecute(aVoid);
        }
    }
 
public class fetchUserDataAsyncTask extends AsyncTask<Void, Void, User> {
        User user;
GetUserCallbackuserCallback;
 
publicfetchUserDataAsyncTask(User user, GetUserCallbackuserCallback) {
this.user = user;
this.userCallback = userCallback;
        }
 
        @Override
protected User doInBackground(Void... params) {
ArrayList<NameValuePair>dataToSend = new ArrayList<>();
 
dataToSend.add(new BasicNameValuePair("emailaddress", user.name));
dataToSend.add(new BasicNameValuePair("password", user.password));
 
HttpParamshttpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);
 
HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpClient post = new HttpPost(SERVER_ADDRESS + "FetchUserData.php");
 
            User returnedUser = null;
try{
post.setEntity(new URLEncoderFormEntity(dataToSend));
HttpResponsehttpResponse = client.execute(post);
 
HttpEntity entity = httpResponse.getEntity();
                String result = EntityUtils.toString(entity);
JSONObjectjObject = new JSONObject(result);
 
if(jObject.length()== 0){
returnedUser = null;
                } else {
                    String name1 = jObject.getString("firstname");
int phone1 = jObject.getInt("phone");
 
returnedUser = new User(name1 ,user.email );
                }
 
}catch (Exception e){
e.printStackTrace();
            }
 
 
 
returnreturnedUser;
        }
        @Override
protected void onPostExecute(User returnedUser) {
progressDialog.dismiss();
userCallback.done(returnedUser);
super.onPostExecute(returnedUser);
        }
    }
 
}
 
 



15. Inside UserLocalstore.java write the followingcode
 
public class UserLocalStore {
 
public static final String SP_NAME = "UserDetails";
SharedPreferenceslocaldatabase;
 
publicUserLocalStore(Context context) {
 
localdatabase = context.getSharedPreferences(SP_NAME ,0);
 
    }
 
 
public void storeUserData(User user){
 
SharedPreferences.EditorspEditor  =localdatabase.edit();
 
spEditor.putString("name",user.name);
spEditor.putString("email",user.email);
spEditor.putString("password",user.password);
spEditor.putInt("phone", user.phone);
 
 
    }
 
 
public User getLoggedInUser(){
 
        String name = localdatabase.getString("name", " ");
        String email = localdatabase.getString("email", " ");
        String password = localdatabase.getString("password", " ");
int phone = localdatabase.getInt("phone",-1);
        User storeduser = new User(name,email,password,phone);
return  storeduser;
    }
 
 
public void setUserLoggedIn(booleanloggedIn){
 
SharedPreferences.EditorspEditor  =localdatabase.edit();
spEditor.putBoolean("loggedIn", loggedIn);
spEditor.commit();
 
 
      }
 
 
publicbooleangetUserLoggedIn(){
 
if(localdatabase.getBoolean("LoggedIn",false)== true){
 
return true;
 
}else{
 
return false;
 
 
          }
 
      }
 
public void clearUserdata(){
 
SharedPreferences.EditorspEditor = localdatabase.edit();
spEditor.clear();
spEditor.commit();
 
 
        }
 
}



16. Now to connect with database you need to  create two more php  file  Register.php and FetchUserData.php  to connect with the  database. you can create your database by installing wamp server  in your PC or you can create your Online database from  db4free.net or freemysqlhosting.net or 000webhost.com. You can download  fullsource code from below.
 

Posted By UandBlog

UandBlog is a Global Leading source of Finance, Health, Lifestyle, Technology, Gaming and Programing and other information, it is a fastest growing blog for all , for latest post or information like us on facebook , follow on Twitter, Google+ and Pinterest.

Comments ( 8 )

suneel jam:
i didnt find any thing about getuser call back function i got error at that point GetUserCallback
Admin:
you have done something wrong .. have u use the source code?
mohamed elagamy:
I need source code files ??
Admin:
yah I am going to upload source code file
mohamed elagamy:
please upload the whole project ??
Admin:
yah I am going to upload source code file
mikandy ify:
pls source code
Pranali Pardhe:
where do i find the source code?
Sandeep Yohans:
Hi, your tutorial is a very good, thanks so much! Could you please also share the source code download link for your tutorial?
Nimmiya Roy:
Can i have the source code?
menna ali:
where do i find the source code?

    Leave a comment..

    Click to login.

    Subscribe Latest Information

    Most Popular Posts

    You May Like Also