Php Full Code with Login and Registration in Android

How to build complete login and registration in android using PHP.


Create a New Php Database and table in PHP XAMPP and link url to android code(For Local us) Keep connected your phone with android studio.


Create a New Android Project


build.gradle(Module: app)

									   
    compile 'com.mcxiaoke.volley:library-aar:1.0.0'

AndroidManifest.xml


<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
	

Create a Login php file.


jnulogin.php

									   
<?php

$con=mysqli_connect("localhost","root","","jnuproject");

if (mysqli_connect_errno($con))
{
   echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//$username="admin";
//$password = "123";

$user = $_POST['username'];
$pass = $_POST['password'];
$result = mysqli_query($con,"SELECT * FROM register WHERE username='$user' AND password='$pass'");
$row = mysqli_fetch_array($result);
$data = $row[0];

if($data!=null){
echo "success";
}
else
{

echo "fail";
}
mysqli_close($con);
?>

Create a Registration php file.


jnuproject.php

									   
<?php

define('HOST','localhost');
 define('USER','root');
 define('PASS','');
 define('DB','jnuproject');

$con=mysqli_connect("localhost","root","","jnuproject");

if (mysqli_connect_errno($con))
{
   echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

 $name = $_POST['name'];
 $email = $_POST['email'];
 $mobile = $_POST['mobile']; 
 $username = $_POST['username'];
 $password = $_POST['password'];
 
 if($name == '' || $email == '' || $mobile == '' ||$username == '' || $password == ''){
 echo "please fill all values";
 }else{
 //require_once('dbConnect.php');
 $sql = "SELECT * FROM register WHERE username='$username' AND mobile='$mobile'";
 
 $check = mysqli_fetch_array(mysqli_query($con,$sql));
 
 if(isset($check)){
 echo 'username  and mobile already exist';
 }else{ 
 $sql = "INSERT INTO register (name,email,mobile,username,password) VALUES('$name','$email','$mobile','$username','$password')";
 if(mysqli_query($con,$sql)){
 echo "success";
 }else{
 echo "oops! Please try again!";
 }
 }
 mysqli_close($con);
 }
 ?>

Config.java

									   
   package com.narendra.phpforgotpassuser;

public class Config {

    public static final String LOGIN_URL = "http://192.168.2.3/Android/jnulogin.php";

    public static final String username = "username";
    public static final String password = "password";

    //If server response is equal to this that means login is successful
    public static final String LOGIN_SUCCESS = "success";

    //Keys for Sharedpreferences
    //This would be the name of our shared preferences
    public static final String SHARED_PREF_NAME = "myloginapp";

    //This would be used to store the email of current logged in user
    public static final String USER_SHARED_PREF = "username";

    //We will use this to store the boolean in sharedpreference to track user is loggedin or not
    public static final String LOGGEDIN_SHARED_PREF = "loggedin";
}

activity_main.xml

									   						   
   <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mainContainer"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/loginback"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight=".2"
        android:src="@drawable/login1" />

    <TextView
        android:id="@+id/log"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight=".1"
        android:gravity="center"
        android:text="Login"
        android:textColor="#086"
        android:textSize="25dp" />

    <EditText
        android:id="@+id/euser"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_below="@+id/log"
        android:layout_weight=".1"
        android:hint="Username"
        android:paddingLeft="15dp" />

    <EditText
        android:id="@+id/epass"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_alignEnd="@+id/euser"
        android:layout_alignStart="@+id/euser"
        android:layout_below="@+id/euser"
        android:layout_weight=".1"
        android:hint="Password"
        android:paddingLeft="15dp"
        android:password="true" />

    <Button
        android:id="@+id/blog"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_below="@+id/epass"
        android:layout_weight=".1"
        android:text="Login"
        android:textSize="20dp" />

    <TextView
        android:id="@+id/tvregister"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_below="@+id/for1"
        android:layout_weight=".1"
        android:gravity="center"
        android:onClick="register"
        android:text="New Registration"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#086" />

</LinearLayout>

Mainactivity.java

									   
   package com.narendra.phploginandregistration;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    Context context;
    private EditText editTextUser;
    private EditText editTextPassword;
    private Button buttonLogin;
    private boolean loggedIn = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;
        editTextUser = (EditText) findViewById(R.id.euser);
        editTextPassword = (EditText) findViewById(R.id.epass);

        buttonLogin = (Button) findViewById(R.id.blog);

        //Adding click listener
        buttonLogin.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        login();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //In onresume fetching value from sharedpreference
        SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);

        //Fetching the boolean value form sharedpreferences
        loggedIn = sharedPreferences.getBoolean(Config.LOGGEDIN_SHARED_PREF, false);

        //If we will get true
        if (loggedIn) {
            //We will start the Profile Activity
            Intent intent = new Intent(context, Home.class);
            startActivity(intent);

        }
    }

    private void login() {
        //Getting values from edit texts
        final String username = editTextUser.getText().toString().trim();
        final String password = editTextPassword.getText().toString().trim();

        //Creating a string request
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Config.LOGIN_URL,
                new Response.Listener() {

                    @Override
                    public void onResponse(String response) {
                        //If we are getting success from server
                        if (response.equalsIgnoreCase(Config.LOGIN_SUCCESS)) {
                            //Creating a shared preference
                            SharedPreferences sharedPreferences = context.getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);

                            //Creating editor to store values to shared preferences
                            SharedPreferences.Editor editor = sharedPreferences.edit();

                            //Adding values to editor
                            editor.putBoolean(Config.LOGGEDIN_SHARED_PREF, true);
                            editor.putString(Config.USER_SHARED_PREF, username);

                            //Saving values to editor
                            editor.commit();
                            //Starting profile activity
                            Intent intent = new Intent(context, Home.class);
                            startActivity(intent);

                        } else {
                            //If the server response is not success
                            //Displaying an error message on toast
                            Toast.makeText(context, "Invalid username or password", Toast.LENGTH_LONG).show();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        //You can handle error here if you want
                    }
                }) {
            @Override
            protected Map <String, String > getParams() throws AuthFailureError {
                Map params = new HashMap<>();
                //Adding parameters to request
                params.put(Config.username, username);
                params.put(Config.password, password);

                //returning parameter
                return params;
            }
        };
        //Adding the string request to the queue
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }

    public void register(View view) {
        startActivity(new Intent(context, Registration.class));
        Toast.makeText(context, "You Click Registration", Toast.LENGTH_SHORT).show();
    }
}

activity_registration.xml

									   
 <?xml version="1.0" encoding="utf-8"?>
<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:alpha=".7"
    android:background="@drawable/register1"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight=".2"
        android:gravity="center"
        android:text="Registration"
        android:textColor="#12090d"
        android:textSize="25dp" />

    <EditText
        android:id="@+id/etName"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight=".1"
        android:gravity="center_vertical"
        android:hint="Name"
        android:paddingLeft="15dp"
        android:textColorHint="#12090d"
        android:textSize="20dp" />

    <EditText
        android:id="@+id/etemail"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight=".1"
        android:gravity="center_vertical"
        android:hint="E-Mail"
        android:paddingLeft="15dp"
        android:textColorHint="#12090d"
        android:textSize="20dp" />

    <EditText
        android:id="@+id/etphone"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight=".1"
        android:gravity="center_vertical"
        android:hint="Mobile Number"
        android:inputType="phone"
        android:paddingLeft="15dp"
        android:textColorHint="#12090d"
        android:textSize="20dp" />

    <EditText
        android:id="@+id/etUsername"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight=".1"
        android:gravity="center_vertical"
        android:hint="Username"
        android:paddingLeft="15dp"
        android:textColorHint="#12090d"
        android:textSize="20dp" />

    <EditText
        android:id="@+id/etPassword"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight=".1"
        android:gravity="center_vertical"
        android:hint="Password"
        android:inputType="textPassword"
        android:paddingLeft="15dp"
        android:textColorHint="#12090d"
        android:textSize="20dp" />

    <Button
        android:id="@+id/bRegister"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight=".1"
        android:onClick="login"
        android:text="Register"
        android:textColor="#12090d" />

    <TextView
        android:id="@+id/retologin"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight=".1"
        android:gravity="center"
        android:onClick="registerlogin"
        android:text="Already account! Please Login"
        android:textColor="#12090d"
        android:textSize="17dp" />

</LinearLayout>

Registration.java

									   
package com.narendra.phploginandregistration;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.util.Patterns;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class Registration extends AppCompatActivity {

    boolean login;
    EditText name, email, mobile, username, password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registration);
    }

    public void login(View view) {
        name = (EditText) findViewById(R.id.etName);
        email = (EditText) findViewById(R.id.etemail);
        mobile = (EditText) findViewById(R.id.etphone);
        username = (EditText) findViewById(R.id.etUsername);
        password = (EditText) findViewById(R.id.etPassword);

        String strname = name.getText().toString();
        if (TextUtils.isEmpty(strname)) {
            name.setError("Your message");
            return;
        }

        String stremail = email.getText().toString();
        if (TextUtils.isEmpty(stremail) || !Patterns.EMAIL_ADDRESS.matcher(stremail).matches()) {
            email.setError("Your message");
            return;
        }

        String strmobile = mobile.getText().toString();
        if (TextUtils.isEmpty(strmobile)) {
            mobile.setError("Your message");
            return;
        }
        if (mobile.length() != 10) {
            Toast.makeText(Registration.this, "Please Enter Correct moblile No.", Toast.LENGTH_SHORT).show();
        }


        String struser = username.getText().toString();
        if (TextUtils.isEmpty(struser)) {
            username.setError("Your message");
            return;
        }
        // if(username.length()>=5)
        //{
        //  Toast.makeText(Registration.this,"Username length 7",Toast.LENGTH_SHORT).show();
        // }

        String strpass = password.getText().toString();
        if (TextUtils.isEmpty(strpass)) {
            password.setError("Your message");
            return;
        }

        LoginAsy loginAsy = new LoginAsy(this);
        loginAsy.execute(name.getText().toString(), email.getText().toString(), mobile.getText().toString(), username.getText().toString(), password.getText().toString());

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (login) {

                    Toast.makeText(Registration.this, "Sucessfully Added data", Toast.LENGTH_SHORT).show();

                    startActivity(new Intent(Registration.this, MainActivity.class));
                } else {
                    Toast.makeText(Registration.this, "Not Save Data", Toast.LENGTH_SHORT).show();
                }
            }
        }, 2000);
    }

    public void registerlogin(View view) {
        startActivity(new Intent(Registration.this, MainActivity.class));
    }

    public class LoginAsy extends AsyncTask <String, Void, String > {
        Context myContext;
        String result;

        public LoginAsy(Context c) {
            myContext = c;
        }

        @Override
        protected String doInBackground(String... params) {

            String myurldata = "name=" + params[0] + "&email=" + params[1] + "&mobile=" + params[2] + "&username=" + params[3] + "&password=" + params[4];

            try {
                //  URL url = new URL("http://10.0.3.2/Android/jnuproject.php");
                URL url = new URL("http://192.168.2.3/Android/jnuproject.php");
                //  URL url=new URL("http://yctransport.freevar.com/jnuproject.php");
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("POST");
                connection.getOutputStream().write(myurldata.getBytes());

                int responce = connection.getResponseCode();

                Log.d("Responce code ", "" + responce);

                if (responce == HttpURLConnection.HTTP_OK) {
                    String line;
                    StringBuilder builder = new StringBuilder();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

                    while ((line = reader.readLine()) != null) {
                        builder.append(line);
                    }

                    Log.d("Result value is ", builder.toString());
                    result = builder.toString();
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (result.equals("success")) {
                login = true;
            } else {
                login = false;
            }
            return null;
        }
    }
}

activity_home.xml


									   
									   
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_home"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <TextView
        android:id="@+id/tvhome"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="name"
        android:textColor="#f97516"
        android:textSize="25dp" />

    <Button
        android:id="@+id/logout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Logout" />

</RelativeLayout>
	

Home.java


									   
package com.narendra.phpforgotpassuser;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class Home extends AppCompatActivity {

    Button logout;
    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        logout = (Button) findViewById(R.id.logout);
        textView = (TextView) findViewById(R.id.tvhome);

        //Fetching email from shared preferences
        SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
        String username = sharedPreferences.getString(Config.USER_SHARED_PREF, "Not Available");

        //Showing the current logged in email to textview
        textView.setText("Username : " + username);

        logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                logout();
            }
        });
    }

    private void logout() {
        //Creating an alert dialog to confirm logout
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setMessage("Are you sure you want to logout?");
        alertDialogBuilder.setPositiveButton("Yes",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {

                        //Getting out sharedpreferences
                        SharedPreferences preferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
                        //Getting editor
                        SharedPreferences.Editor editor = preferences.edit();

                        //Puting the value false for loggedin
                        editor.putBoolean(Config.LOGGEDIN_SHARED_PREF, false);

                        //Putting blank value to username
                        editor.putString(Config.USER_SHARED_PREF, "");

                        //Saving the sharedpreferences
                        editor.commit();

                        //Starting login activity
                        Intent intent = new Intent(Home.this, MainActivity.class);
                        startActivity(intent);
                    }
                });

        alertDialogBuilder.setNegativeButton("No",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                    }
                });
        //Showing the alert dialog
        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }
}


	

Tags

  • Android

  • Android Studio

  • Android development

  • Java