Skip to main content

Android PHP Mysql login tutorial using HttpURLConnection

Android PHP mysql login

Android has deprecated the Apache module(HttpPost and HttpGet) since API level 22, Now the alternate way is to use JAVA’s HttpURLConnection Class. This tutorial depict Android PHP Mysql login to deal with GET and POST data.

Android php mysql login system contains two android activities, MainActivity.java and SuccessActivity.java. MainActivity is actual login form where you can see username,password and a button whereas SuccessActivity is a plain form with success message which triggers after successful login. The functions of both activity are detailed in Android section below.

Apart from android part the mysql and php implimentation is considerably easy to do.

Download Code From Github

Android MySQL PHP LogIn demo

MySql

Table ‘tbl_login’ contains username and password of user.

CREATE TABLE 'tbl_login' (
  'email' varchar(255) NOT NULL,
  'password' varchar(255) NOT NULL
);

Table holds data row like this.

INSERT INTO 'tbl_login' ('email', 'password') VALUES
('gpkharvi@gmail.com', 'password');

PHP

  1. include config.inc.php file to connect database.
  2. Check if POST data is set from android.
  3. Query the database to see row exist or not.
  4. Return the result.

login.inc.php

<?php

     include 'config.inc.php';
	 
	 // Check whether username or password is set from android	
     if(isset($_POST['username']) && isset($_POST['password']))
     {
		  // Innitialize Variable
		  $result='';
	   	  $username = $_POST['username'];
          $password = $_POST['password'];
		  
		  // Query database for row exist or not
          $sql = 'SELECT * FROM tbl_login WHERE  email = :username AND password = :password';
          $stmt = $conn->prepare($sql);
          $stmt->bindParam(':username', $username, PDO::PARAM_STR);
          $stmt->bindParam(':password', $password, PDO::PARAM_STR);
          $stmt->execute();
          if($stmt->rowCount())
          {
			 $result="true";	
          }  
          elseif(!$stmt->rowCount())
          {
			  	$result="false";
          }
		  
		  // send result back to android
   		  echo $result;
  	}
	
?>

config.inc.php

<?php

$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "9tutorials";

try {
    	$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    	$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
catch(PDOException $e)
    {
    	die("OOPs something went wrong");
    }

?>

Android

The image on the top of page shows both MainActivity.java and SuccessActivity.java respectively.

MainActivity.java

  1. On LogIn button click checkLogin() function is triggered. Which innitiate AsyncLogin class to carry out Asynchronous task.
  2. onPreExecute(), invoked on the UI thread before the task is executed. Here We are displaying loading message.
  3. doInBackground(Params…), invoked on the background thread immediately after
    onPreExecute() finishes executing. The sending and recieving data from and to php file using HttpURLConnection class has done in this function.
  4. onPostExecute(Result), invoked on the UI thread after the background computation finishes. Here we are checking for recieved result.
  5. The parameters params[0] and params[1] is from AsyncLogin’s execute method.
package com.guru.login;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    // CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds

    public static final int CONNECTION_TIMEOUT=10000;
    public static final int READ_TIMEOUT=15000;
    private EditText etEmail;
    private EditText etPassword;

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

        // Get Reference to variables
        etEmail = (EditText) findViewById(R.id.email);
        etPassword = (EditText) findViewById(R.id.password);

    }

    // Triggers when LOGIN Button clicked
    public void checkLogin(View arg0) {

        // Get text from email and passord field
        final String email = etEmail.getText().toString();
        final String password = etPassword.getText().toString();

            // Initialize  AsyncLogin() class with email and password
            new AsyncLogin().execute(email,password);

    }

    private class AsyncLogin extends AsyncTask<String, String, String>
    {
        ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
        HttpURLConnection conn;
        URL url = null;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            //this method will be running on UI thread
            pdLoading.setMessage("\tLoading...");
            pdLoading.setCancelable(false);
            pdLoading.show();

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

                // Enter URL address where your php file resides
                url = new URL("http://localhost/test/login.inc.php");

            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return "exception";
            }
            try {
                // Setup HttpURLConnection class to send and receive data from php and mysql
                conn = (HttpURLConnection)url.openConnection();
                conn.setReadTimeout(READ_TIMEOUT);
                conn.setConnectTimeout(CONNECTION_TIMEOUT);
                conn.setRequestMethod("POST");

                // setDoInput and setDoOutput method depict handling of both send and receive
                conn.setDoInput(true);
                conn.setDoOutput(true);

                // Append parameters to URL
                Uri.Builder builder = new Uri.Builder()
                        .appendQueryParameter("username", params[0])
                        .appendQueryParameter("password", params[1]);
                String query = builder.build().getEncodedQuery();

                // Open connection for sending data
                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(os, "UTF-8"));
                writer.write(query);
                writer.flush();
                writer.close();
                os.close();
                conn.connect();

            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
                return "exception";
            }

            try {

                int response_code = conn.getResponseCode();

                // Check if successful connection made
                if (response_code == HttpURLConnection.HTTP_OK) {

                    // Read data sent from server
                    InputStream input = conn.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                    StringBuilder result = new StringBuilder();
                    String line;

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

                    // Pass data to onPostExecute method
                    return(result.toString());

                }else{

                    return("unsuccessful");
                }

            } catch (IOException e) {
                e.printStackTrace();
                return "exception";
            } finally {
                conn.disconnect();
            }


        }

        @Override
        protected void onPostExecute(String result) {

            //this method will be running on UI thread

            pdLoading.dismiss();

            if(result.equalsIgnoreCase("true"))
            {
                /* Here launching another activity when login successful. If you persist login state
                use sharedPreferences of Android. and logout button to clear sharedPreferences.
                 */

                Intent intent = new Intent(MainActivity.this,SuccessActivity.class);
                startActivity(intent);
                MainActivity.this.finish();

            }else if (result.equalsIgnoreCase("false")){

                // If username and password does not match display a error message
                Toast.makeText(MainActivity.this, "Invalid email or password", Toast.LENGTH_LONG).Show();

            } else if (result.equalsIgnoreCase("exception") || result.equalsIgnoreCase("unsuccessful")) {

                Toast.makeText(MainActivity.this, "OOPs! Something went wrong. Connection Problem.", Toast.LENGTH_LONG).Show();

            }
        }

    }
}

activity_main.xml

The xml file for MainActivity.java.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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: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=".MainActivity">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:ems="10"
        android:id="@+id/email"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:hint="Email"
        android:layout_marginTop="10dp"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        android:ems="10"
        android:id="@+id/password"
        android:layout_below="@+id/email"
        android:hint="Password"
        android:layout_marginTop="10dp"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="LOGIN"
        android:id="@+id/button"
        android:layout_below="@+id/password"
        android:layout_marginTop="10dp"
        android:onClick="checkLogin"/>

</RelativeLayout>

SuccessActivity.java

This Activity is launched from onPreExecute() method after login success.

package com.guru.login;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class SuccessActivity extends AppCompatActivity {

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

activity_success.xml

The xml file for SuccessActivity.java.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="WELCOME"
        android:id="@+id/textView"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="62dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Successfully LoggedIn"
        android:id="@+id/textView2"
        android:layout_marginTop="46dp"
        android:layout_below="@+id/textView"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

AndroidManifest.xml

Don’t forget to add uses-permission and SuccessActivity to your AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.guru.login" >

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity android:name=".MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />


                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        <activity android:name=".SuccessActivity" >
        </activity>
    </application>

</manifest>

Gururaj P Kharvi

An Entrepreneur, Web and Android developer from India.

73 thoughts on “Android PHP Mysql login tutorial using HttpURLConnection

  1. How i can get the response of the request ? For example the url i requested returns json.
    I want to get this json after i make request. I mean i want to get response.

    Thanks.

    1. @Nezih

      The method for fetching any get or post data is same as mentioned in above code( inside doInBackground(String… params)) but in above example we get plain text as response, in your case it’s a JSON data So you need to process that json data after fetching.

      Here is the example code to extract data from json array. and it should go into onPostExecute() method.

      // InformationOrdersFetch is a class which has order_id,name and address variables.
      List<InformationOrdersFetch> data=new ArrayList<>();
      
                  try {
      
                      // result is a variable which holds fetched json data.
                      JSONArray jArray = new JSONArray(result);
      
      
                      for(int i=0;i<jArray.length();i++){
      
                          JSONObject json_data = jArray.getJSONObject(i);
                          InformationOrdersFetch information = new InformationOrdersFetch();
                          information.orderId= json_data.getString("order_id");
                          information.name= json_data.getString("name");
                          information.address= json_data.getString("address");
      
                          data.add(information);
      
                      }catch (JSONException e) { }
      
      1. Hi Gururaj,
        Nice tutorial! Can you please give me the code to check if login username and password are valid after processing JSON? I got this so far, which is pretty much similar to your code-

        
        @Override
                protected void onPostExecute(String result) {
                    super.onPostExecute(result);
                    Log.i("Website Content", result);
        
                    try {
                       JSONArray arr = new JSONArray(result);
        
                      for (int i = 0; i < arr.length(); i++) {
        
                          JSONObject jsonPart = arr.getJSONObject(i);
        
        //                    Log.i("user", jsonPart.getString("email"));
        //                    Log.i("pass", jsonPart.getString("password"));
        
                         String dbUserName= jsonPart.getString("email");
                         String dbPassword= jsonPart.getString("password");
                       }
        

        I feel like I should do a query with for each loop but not sure though. Any kind of help would be appreciated. TIA 🙂

  2. i am getting error like this. please help me

    Error:Execution failed for task ‘:app:mergeDebugResources’.
    > /Users/venkatesh/Downloads/MiniProject/app/src/main/res/values-w820dp/dimens.xml: Error: In DataSet ‘main’, no data file for changedFile. This is an internal error in the incremental builds code; to work around it, try doing a full clean build.

    1. sorry actually error is this:
      /Users/venkatesh/Downloads/MiniProject/app/src/main/java/com/cse/miniproject/LoginActivity.java
      Error:(79, 9) error: method does not override or implement a method from a supertype
      Note: /Users/venkatesh/Downloads/MiniProject/app/src/main/java/com/cse/miniproject/LoginActivity.java uses unchecked or unsafe operations.
      Note: Recompile with -Xlint:unchecked for details.
      :app:compileDebugJavaWithJavac FAILED
      Error:Execution failed for task ‘:app:compileDebugJavaWithJavac’.
      > Compilation failed; see the compiler error output for details.

      1. You may be missing some parameter for AsyncTask ie. it should be AsyncTask<String, String, String> or you may be missed some functions inside AsyncTask namely onPreExecute(),onPostExecute() or DoInBackground().

  3. hello gururaj,
    i did check php and mysql connection with browser and result was okay. (using WAMP 3 server)

    where i get stucked when login in android device shows no result.
    its only shows loading onPreExecute but returns nothing, even if i enter correct login or not or blank,
    and also when i press login android monitoir doesnt produce any log, only when i select text field does.

    please help and thank you

      1. @Hyeran

        I hope you created database and tables mentioned above and copied both of config.inc.php and login.inc.php into your server(may be localhost) folder.

        Now, open your config.inc.php in notepad and enter username, password and database name of your mysql database and if you don’t know how test your app with localhost refer this tutorial.

        Please test your login.inc.php in your browser before inputting address into code.

    1. The queries in .sql file you need to execute in your database, i mean you need to create table and insert rows. Both of your MySQL database and PHP files resides in localhost or hosted somewhere on the internet. If you don’t know how to test your app with localhost then please refer below link(one of my article comment section).

      How to test your app with localhost(WAMP or XAMP)

  4. I tried many tutorials on the internet but this is the only tutorial works with me and it’s easy to understand

    thank you very much

  5. Hi,

    You have a very clean example that is well explained. I am inserting a row in my table. If I include the values in the URL string a paired parameters I am able to get my code to work. I am using $_POST on the .php side. If I add all of the code around the .appendQueryParameter and the BufferedWriter and remove the values from the URL string my .php acts as if no parameters are coming over. Do you know of something obvious that I could be missing that would cause something like that? I obviously do not want to create my code to use the parameters in the URL string, but it is the only way I can make it work right now.

    1. Sending parameter using .appendQueryParameter and BufferedWriter should work. There may be some minor mistakes you made in php or asynctask class, Please re-validate your both file. Even after you experiencing problem, please send your code snippet to analyze it further.

  6. Sir I have done this in webhost instead of local host .I have done all the things right but when i click on login button it loads and stops on the same main activity screen itself

    1. comment all code inside your onPostExecute() method and add toast method like this to check for what is returning from PHP.

      Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).Show();

        1. In your PHP file ‘login.inc.php’, You have syntax error ‘unexpexcted $end’ on line no 43, Please test your PHP file in browser to check for correctness.

  7. Can you provide example for “forgot password” ?

    If user is exist return success if user is not exist return error

    1. You can use above PHP file, by making some small changes like redefining query as SELECT * FROM tbl_login WHERE email = :username and as usual if $stmt->rowCount() return true then username/email exist else not exist.

  8. May i know any error you are getting? Let’s check your PHP file first, Test your droidIn.php on browser by removing if condition and assigning $username and $password the value which is present in your table. Remember, you need to get output as “true”.

    1. Possibly there may be exception or not connected to your remote server. All you need to do is, test your PHP file in browser for correct output.

  9. I have tried this example, but for some reason the next activity will not start. I am certain that I am in onPostExecute(), and I have a Log.d(message) to let me know when the app is in onCreate in the next activity. But it never happens.

    1. Inside if(result.equalsIgnoreCase("true")) block of onPostExecute() method of class AsyncLogin add following code.

      SharedPreferences sharedpreferences = getSharedPreferences(LOGIN_PREFERENCE, LoginActivity.this.MODE_PRIVATE);
      SharedPreferences.Editor editor = sharedpreferences.edit();
      editor.putString("isLogin", isLogin);
      

      onCreate() method of MainActivity delete last two lines of code and below code.

      SharedPreferences prefs = getSharedPreferences(LOGIN_PREFERENCE, this.MODE_PRIVATE);
      String isLogin = prefs.getString("isLogin", "false");
      if(isLogin.equals("true"))
      {
        Intent intent = new Intent(this,MainActivity.class);
        startActivity(intent);
        finish();
      
      }else{
      
        setContentView(R.layout.activity_login);
      
        emailEditText = (EditText) findViewById(R.id.username);
        passEditText = (EditText) findViewById(R.id.password);
      
      }
      

      Finally, on clicking logout button execute below code.

      this.getSharedPreferences(LOGIN_PREFERENCE, 0).edit().clear().commit();
      Intent intent = new Intent(this,LoginActivity.class);
      startActivity(intent);
      finish();
      
        1. Ok, it is not isLogin variable, it is result variable. Replace editor.putString(“isLogin”, isLogin); code with editor.putString(“isLogin”, result);

          1. giving error on this.getSharedPreferences(LOGIN_PREFERENCE, 0).edit().clear().commit();
            red underline getSharedPreferences

          2. giving error on this.getSharedPreferences(LOGIN_PREFERENCE, 0).edit().clear().commit();
            red underline getSharedPreferences

            on Mouse over error shown is Cannot resolve method ‘getSharedPreferences(java.lang.String, int)’

  10. pls help why while error
    cannot find symbol method show()

    direct to this source
    Toast.makeText(MainActivity.this, “Invalid email or password”, Toast.LENGTH_LONG).Show();

  11. I’m keeping catch the IOException. I’m guessing its when you want to create the OutputStreamWriter. Any suggestions on how to fix this?

  12. Oops Something went wrong.. Conection problem.

    this is my url http://localhost/cruds4/php/login.inc.php. I tested the url and worked, but not in the app. 🙁

  13. Hello, on our server running the nginx with SSL.
    Here I your program HttpsURLConnection to, I get no response from the server more. 🙁 In the program but no error message.

  14. plz ! any help ! I try your example to develop my application but i can’t connect my login activity with my data base mysql i have this toast : “OPPS problem of connexion ! !” ofcourse i change url to “http://10.0.3.2/….” because i use my tablet to test and run my application and i use android studio version 1.5 .

  15. why i click login nothing happen,

    and i got the error:

    09-18 10:14:37.779 2385-2400/com.example.user.newlogin1 E/Surface: getSlotFromBufferLocked: unknown buffer: 0xae4710e0

    Why??

  16. hi. 🙂 your tutorials are very helpful. Do you have tutorial for retrieving data of logged user from mysql database? I am working on an android application that shows the user’s subject and scores from mysql database. My php files for login and retrieving user data is already working, but i cant implement it to android studio.. pls help me. thank you.

  17. sir why “opps problem connection” i follow your tutorial. my database is working but icant connect . please help me 🙁

  18. Hi i have a Problem in runnig project :
    my error:

    C:\MyApplication\app\src\main\res\layout\activity_main.xml
    Error:(2) Error parsing XML: must not undeclare prefix

    C:\MyApplication\app\build\intermediates\res\merged\debug\layout\activity_main.xml
    Error:(2) Error parsing XML: must not undeclare prefix
    Error:Execution failed for task ‘:app:processDebugResources’.
    > com.android.ide.common.process.ProcessException: Failed to execute aapt

  19. Amazing Article. Thank you for your effort.
    1. in your code, we should change Show to show
    2. change localhost to ip address

    and that’s all, Next is CRUD. Did you publish article about it?

Leave a Reply

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