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, and 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


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
('', 'password');


  1. include 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.


     include '';
	 // Check whether username or password is set from android	
     if(isset($_POST['username']) && isset($_POST['password']))
		  // Innitialize Variable
	   	  $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);
		  // send result back to android
   		  echo $result;


$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");



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

  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.
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

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;

    protected void onCreate(Bundle savedInstanceState) {

        // Get Reference to variables
        etEmail = (EditText) findViewById(;
        etPassword = (EditText) findViewById(;


    // 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;

        protected void onPreExecute() {

            //this method will be running on UI thread

        protected String doInBackground(String... params) {
            try {

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

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

                // setDoInput and setDoOutput method depict handling of both send and receive

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

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

            } catch (IOException e1) {
                // TODO Auto-generated catch block
                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) {

                    // Pass data to onPostExecute method



            } catch (IOException e) {
                return "exception";
            } finally {


        protected void onPostExecute(String result) {

            //this method will be running on UI thread


                /* 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);

            }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();




The xml file for

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=""
    xmlns:tools="" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">





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


import android.os.Bundle;

public class SuccessActivity extends AppCompatActivity {

    protected void onCreate(Bundle savedInstanceState) {


The xml file for

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=""
    xmlns:tools="" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"

        android:layout_marginTop="62dp" />

        android:text="Successfully LoggedIn"
        android:layout_centerHorizontal="true" />



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

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""
    package="" >

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

        android:theme="@style/AppTheme" >
        <activity android:name=".MainActivity" >
                <action android:name="android.intent.action.MAIN" />

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


Gururaj P Kharvi

An Entrepreneur, Web and Android developer from India.

84 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.


    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.address= json_data.getString("address");
                      }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-

                protected void onPostExecute(String 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:
      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/ 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 and into your server(may be localhost) folder.

        Now, open your 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 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 ‘’, 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");
        Intent intent = new Intent(this,MainActivity.class);
        emailEditText = (EditText) findViewById(;
        passEditText = (EditText) findViewById(;

      Finally, on clicking logout button execute below code.

      this.getSharedPreferences(LOGIN_PREFERENCE, 0).edit().clear().commit();
      Intent intent = new Intent(this,LoginActivity.class);
        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/ 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 “….” 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


  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:

    Error:(2) Error parsing XML: must not undeclare prefix

    Error:(2) Error parsing XML: must not undeclare prefix
    Error:Execution failed for task ‘:app:processDebugResources’.
    > 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?

  20. Dude you are the best!!!!!!!, i literally have been having headaches with this but you just made it so simple thanks!!!!.

    Looking for alot more work from you 🙂

  21. So far a very nice tutorial! We’ve got a problem with our server. It’s a raspberry pi webserver we are trying to connect to. Our response code is 500, not 200 for HTTP_OK. The connection to other websites have been successful! Do you have an idea how to solve our problem?
    Looking forward to your answer!
    Greetings from Germany! 🙂

  22. hi! I copied all your codes even the database itself. when I run this on genymotion emulator the app has stopped working. what do you think is the problem? can you please help me. I badly need your answer.

Leave a Reply

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