Android material design Programming Blog

Android PHP Mysql login tutorial using HttpURLConnection

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" >



Add yours

  1. very good tutorial . thank you

  2. The tutorial is nice but I was using source code from Github still my android app did not display a success message how can I fix this problem

  3. url = new URL(“”);

    oops .shows something went wrong
    i dont exactly what is the problem.

    import; –> shows error in v7.

    what should i do ??

  4. It is not working connection problem

  5. Muito obrigado pelo post. Ajudou muito!!

  6. thanks so much sir

  7. hi iam new to android studio, I have gone through ur code and created same thing in my android studio application , the problem iam getting oops something went wrong .connection error , I have gone through this comments changed localhost into ip ,now its not displaying anything. iam using apk in my mobile .can u please help me with this

  8. Great tutorial. If anyone getting “OOPs! Something went wrong. Connection Problem”‘ then make sure that the mobile and pc is connected to same network. Eg: if you have connected your pc with mobile hotspot then go to to network and sharing center , you will find your device name click on it, a pop up “wifi status” appears ,click on details and there you go ! You have the ip address now. In your put the found ip address in url = new URL("http://***.***.***.***/");

  9. Hello Gururaj P Kharvi, thanks for this tutorial. I have try to change your Android and Php code to insert a new member in my database but it does not work. Do you have a tutorial for insert?

  10. Thank you for this tutorial, it works good, but i try to create a new member from my App. How can i change your php so that i can check and insert a new? From my server (Html and Php) it works.

    Hello Gururaj P Kharvi, viele Dank für das Tutorial, es klappt wirklich gut aber ich wollte nun aus meiner App ein neun Benutzer anlegen. Wie kann ich deine Code anpassen um ein neuen Acc zu prüfen und anzulegen?

  11. What if the database is coming from online? like go daddy, what is the connection path on it? please reply as soon as possible. Thanks

  12. Hi Gaurav, please tell me how to fetch the ID of the user being authenticated in

  13. bonjour, j’ai un soucis avec mon apk monté a partir de votre code. le code il est le meme, mais a chaque fois que j’essaie de me logger, toujours ce message s’affiche
    Toast.makeText(MainActivity.this, "OOPs! Something went wrong. Connection Problem.", Toast.LENGTH_LONG).show();

    j’aimerais savoir comment remedier a ce probleme, j’ai pourtant bien mis les permission dans le fichier manifeste

  14. Kindly send/post code for Signup through http connection, or remaning part of this video of signup Activity.

    • The steps what are specified in the tutorials are same for registration/signup process. Only difference is sending extra parameters and in the backend/server inserting those data(use insert query).

  15. I can’t connect to Database: Failed to connect to /

    • The URL/IP you are referring to may not exist. Check that IP from your mobile phone browser before integrating into android.

  16. When I run the code, all are ok. But in android phone, I found connection problem in toast message. So I print the value of message in the toast and delete connection problem message. At the time, I found exception error. I think this error is occurred when passing url. Please help urgently.
    Thanks for your helpful post

  17. Please help in solving an error
    Undefined index: id in /storage/ssd1/005/5813005/public_html/loginphp.php on line 3
    Undefined index: name in /storage/ssd1/005/5813005/public_html/loginphp.php on line 4

    • You are not passing id and name from URL(get/post) or else you misspelled parameters name. Before assigning a variable from POST/GET method, execute your code by assigning some dummy values to your variables, say $id=5 and $name='john'.

  18. After entering the data in the app, the loading dialog opens up and closes with no message. Later nothing happens. I am not redirected to next activity.

  19. Wow great tutorial ! And working fine.. Thank you for sharing this.
    Please suggest me how will i match encrypted user password from android login?

    • The best way is sending username and password through authentication header. Look out on the internet for basic authentication header tutorial.

  20. This worked properly. Thanks a lot!!.
    But Can I do same without using PDO!!

    • You can also use the MySQLi or traditional method of PHP to fetch data from tables. PDO is an object-oriented way of accessing data. Compare to the traditional method, MySQLi and PDO are somehow secure.

  21. Excellent post for beginners. Thanks a lot, Sir.

  22. wow, this worked perfectly fine! thanks.

  23. Help me with this error, .Show() is not recognized.

  24. This works like a charm.

  25. I used this tutorial and successfully followed it to make a login system:

    But I want to expand upon it. After successful login I’d like to echo the username of the person that logged on. And then I’d like to store that username so that I can search that user’s specific SQL table within the same database that the login credentials are stored. I think I know how to do the last part from another tutorial:

    But it’s the step in the middle that I can’t find anything about. Because the search tutorial isn’t searching for a user’s specific table, but just a particular table that is preset. My goal is to search the within the same database as that I used to verify login credentials, but based on who logged in, use their specific table within the same database.

    I already have the tables made within mysql, I’m just having trouble adapting the second tutorial to meet my specific requirements. Could you point me in the right direction, or show me how I can adapt the second tutorial?

    • Store username in SharedPreferences. Retrieve username whenever required and send it to server side as GET/POST parameter.

      • Can you explain how to adapt the search view? My search bar is not in the title bar but on the main screen like this login page.

  26. Hi, Can you Please Suggest me which database among SQL server or Mysql of XAMPP server is best to use with Android application and desktop application develop in that both to be link and database will be common. Its my final year project . i need guidance for my project
    Please help me

  27. Awesome man. Minimal effort done and went classical. U saved me man!!

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

  29. 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! 🙂

  30. I want to make Register activity places

  31. Thanks GPK My app running well Sorry means your app……

  32. thanks for tutorial,
    I want register code if you can help me

  33. 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 🙂

  34. A great help for starter like me. 🙂

  35. Very nice tuts, go ahead. Please give a tuts about android barcode recognize to query from php to mysql db .

  36. 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?

  37. Very nice tutorial. Here i got one more but data is being populated into RecyclerView. Hope it helps someine.

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

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

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

  41. opps problem connection !!!! but all code run nicely and i change url ! it’s fine but i can’t connect ! 🙁

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


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

  44. thanks for shared this 😀

  45. Cornélio José Wiedemann

    September 14, 2016 at 5:07 pm

    Amazing article
    tks brow

    i love it

    Cornélio José Wiedemann ( TI & DBA )

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

  47. 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. 🙁

  48. I am getting unsuccessful when i press the button, what to do ?

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

  50. it dont running with me and make this Toast OOPs! Something went wrong. Connection Problem.

  51. How to write insert php

  52. 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();

  53. would you please share a code for sharedPreferences.
    i want autologin when ever user open the app and logout code.

    • 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);
      • giving error on editor.putString(“isLogin”, isLogin);
        red underline isLogin

        • Ok, it is not isLogin variable, it is result variable. Replace editor.putString(“isLogin”, isLogin); code with editor.putString(“isLogin”, result);

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

          • Mouse over to see which error it is.

          • 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)’

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

  55. how to fix connection is failed i need your help please

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

  56. ça m’a vraiment aidé.. merci 🙂

  57. Hello, how I could to do to read data from database ?

  58. 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”.

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

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

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

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

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

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

  62. Thanks for sharing nice tutorials.

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

  64. Thank you so much for this tutorial. It works very well! 🙂

  65. i didnt undertstand where i will put mysql and php file? please tell me

    • 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)

  66. im sorry, my was set

    then i change to

    now its works like charm !!

    thank you again

    • hi, I have same problem
      how change please help thank you.

      • @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.

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

  68. Yes. I missed parameters in AsyncTask. Thank you for your valuable comment.

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

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

      • Gururaj P Kharvi

        May 6, 2016 at 8:14 pm

        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().

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


    • @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) { }
      • hi, do you have any example of how to communicate two players of a board game via server?

      • 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 🙂

Leave a Reply

Your email address will not be published.


About | Policy | Disclaimer

Creative Commons LicenceUp ↑