Android MySQL Database Tutorial – Android Login with PHP MySQL

Android Tutorial
Android Tutorial
package com.example.programmingknowledge.mysqldemo;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {
    EditText UsernameEt, PasswordEt;
    protected void onCreate(Bundle savedInstanceState) {
        UsernameEt = (EditText)findViewById(;
        PasswordEt = (EditText)findViewById(;

public void OnLogin(View view) {
    String username = UsernameEt.getText().toString();
    String password = PasswordEt.getText().toString();
    String type = "login";
    BackgroundWorker backgroundWorker = new BackgroundWorker(this);
    backgroundWorker.execute(type, username, password);


MySQL DBA Online Training by Edureka

package com.example.programmingknowledge.mysqldemo;

import android.content.Context;
import android.os.AsyncTask;


 * Created by ProgrammingKnowledge on 1/5/2016.
public class BackgroundWorker extends AsyncTask<String,Void,String> {
    Context context;
    AlertDialog alertDialog;
    BackgroundWorker (Context ctx) {
        context = ctx;
    protected String doInBackground(String... params) {
        String type = params[0];
        String login_url = "";
        if(type.equals("login")) {
            try {
                String user_name = params[1];
                String password = params[2];
                URL url = new URL(login_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
                OutputStream outputStream = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
                String post_data = URLEncoder.encode("user_name","UTF-8")+"="+URLEncoder.encode(user_name,"UTF-8")+"&"
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
                String result="";
                String line="";
                while((line = bufferedReader.readLine())!= null) {
                    result += line;
                return result;
            } catch (MalformedURLException e) {
            } catch (IOException e) {
        return null;

    protected void onPreExecute() {
        alertDialog = new AlertDialog.Builder(context).create();
        alertDialog.setTitle("Login Status");

    protected void onPostExecute(String result) {

    protected void onProgressUpdate(Void... values) {
<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"

        android:layout_marginTop="47dp" />

        android:layout_alignParentStart="true" />

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""
    package="com.example.programmingknowledge.mysqldemo" >
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>"
        android:theme="@style/AppTheme" >
            android:label="@string/app_name" >
                <action android:name="android.intent.action.MAIN" />

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

$db_name = "employee101";
$mysql_username = "root";
$mysql_password = "";
$server_name = "localhost";
$conn = mysqli_connect($server_name, $mysql_username, $mysql_password,$db_name);

require "conn.php";
$user_name = $_POST["user_name"];
$user_pass = $_POST["password"];
$mysql_qry = "select * from employee_data where username like '$user_name' and password like '$user_pass';";
$result = mysqli_query($conn ,$mysql_qry);
if(mysqli_num_rows($result) > 0) {
echo "login success !!!!! Welcome user";
else {
echo "login not success";



Video Instructions

Partner Sites


  1. Hey Prabeesh
    I have used your codes to learn. Just the way it is . The program installand when I try to run ,The screen is stuck with ‘Login Status’

  2. Hello, I just watched your “Android MySQL Database Tutorial – Android Login with PHP MySQL” video on youtube. it’s awesome.
    bt problem is i have done like yours bt when i click on login button it shows alert box bt not successful msg

    • You can use the android studio virtual device then may be it will work.
      Actually i m also using genymotion but in that the same code is not working.
      but when i thought to run with android own vitual device then it is working fine so do that may be it will work for u too as it is working for me.

  3. please i have the same error When i click the LOgin Button the AlertDialog is empty!! there is only the title that i set in onPreExecute()..and throw IO Exception . Any ideas about my problem?

  4. Hello,
    Very useful code. Thank you for that! I have a problem though and I cannot manage to find the reason. As I have a hosting account I did this tutorial directly on a sql data base that I created online. My hosting is with Ipage. They have a Cpanel but is not exactly how you show it in your video. I have followed every step created everything without any error but now when I launch the app on my phone and I introduce the username and password the answer is always the Alert dialog (Login Status) and the message from login.php login not success. Where do you think could be the problem? Once I get the message from the login.php it means that the app connects to the online files but somewhere here there is a problem $result = mysqli_query($conn ,$mysql_qry);
    if(mysqli_num_rows($result) > 0)

    Please any suggestion is welcomed!

  5. with the same code i have a error Handshake failed
    Caused by: SSL handshake aborted: ssl=0xad51f980: Failure in SSL library, usually a protocol error
    error:100bd10c:SSL routines:ssl3_get_record:WRONG_VERSION_NUMBER
    any ideas?

  6. Very very good. Everything it’s fine..The only parts I had to change were in php (maybe a version issue):
    1- conn.php file

    This works fine:

    $link = mysql_connect($host, $username, $password);
    if (!$link) {
    die(‘Error al conectarse a mysql: ‘ . mysql_error());

    $db_selected = mysql_select_db($database, $link);

    2- login.php file
    $mysql_qry = “select * from employee_data where user_name ='”.$user_name.”‘ and password='”.$user_pass.”‘”;

    $result = mysql_query($mysql_qry) ;

    if(mysql_num_rows($result) > 0) {
    echo “login success !!!!! testeeooo”;
    else {
    echo “login not success”;

  7. Hi, thanks for the great tutorial,

    Hopefully this may help you all. I had the same issue with the Login dialog. Here is what worked for me. In this line below, I did not notice the semi colon between the single quotation mark and the last double quotation marks in the video. I added the semi colon and now it is giving the successful message and working fine.

    $mysql_qry = “select * from employee_data where username like ‘$user_name’ and password like ‘$user_pass’;”;

    Hope this can be of help.

  8. Hi! 1st of all thanks a lot for your, all very very useful tutorials… i just got a problem here is… whenever i am clicking on login button it’s just showing “Login Status” title but not showing any message like login success or not success.

    • For progressbar follow following 3 steps.
      —>//Declare object of ProgressDialog in BackgroundWorker.Do not forget to import class.

      ProgressDialog pd1 ;
      —>//Add this code in onPreExecute method.

      pd1 = new ProgressDialog(context);
      pd1.setTitle(“Retrieving data”);
      pd1.setMessage(“Please wait.”);
      —> //Add this code in onPostExecute method.

      if(pd1!=null) pd1.dismiss();

      • when login button is clicked alertDialog says LOGIN STATUS…
        when register button is pressed from register activity alertDialog again says LOGIN STATUS… to change it to display as “REGISTER STATUS”…?

  9. Hello, Can you please tell me how to open new activity if login is successed! I tried startActivity method it is giving error that can n’t resolve the constructor Intent in current class is less than new activity. Please help me.

  10. when i run the application on the AVD, it asks for the username and password , but when i click on the login, the application closes down. any idea?

    i am using online database not a local

        • the problem in this line > String login_url = “”;
          edit it to >> String log_url = “”;
          ATTENTION : edit this webapp to your folder name where login.php exist
          if the probelm still , then ensure your folder name is right

        • SOLVED
          the problem in this line > String login_url = “”;
          edit it to >> String login_url = “”;
          ATTENTION : edit this webapp to your folder name where login.php exist
          if the probelm still , then ensure your folder name is right !
          if you use XAMPP like me , then it will be >> String login_url = “”;
          ATTENTION : instead of 81 use your port number

          • one thing i have to ask if i want to connect with jdbc then how i can host in and which hosting site is prefered

          • guys help me my connection is successful but when I login in it it shows my data it shows only html code please help me guys how html embeeded and it shows data. plz help me

          • guys help me my connection is successful but when I login in it it shows my data it shows only html code please help me guys how html embeeded and it shows data

          • @Pearl Adams hey I m using xamp too and i have same problem but in your solution u said use port no but i want to run on real device in my own mobile so wht should I do please help me

          • you have to edit like :
            String login_url = “”;

            you have add question mark after php file.

          • In xampp there will be a htdocs folder
            Place your php in htdocs folder(php will basically fetch and set data in database….server)
            Open command prompt and type ipconfig.
            There infront of ipv4 you will find an address like 192.xx.xx.xx
            Copy that address and save it somewhere. Remember ip will change whenever you’ll change wifi or reset it or restart your system so you’ll have to build app again if you restart sytem, etc.

  11. I really thank you bro for your helpful tutorials. I’ve been studying programming from you since four years. Many thanks and best wishes for you brother.

  12. so the code works perfectly on an emulator. but when i try on my phone it only shows login status and the if it was success or not. please help. i even put my ip address and i get the same results on both devices.

  13. guys help me my connection is successful but when I login in it it shows my data it shows only html code please help me guys how html embeeded and it shows data.

  14. i am using a webhosting server and when i run the app on my phone i get the box login status ..
    But no more, is there anyone who has any suggestions?
    I have changed String login_url to the right one

  15. Hello , I am new:

    I want; whenever user gets ‘login success’ the user will get alert with Ok …and when this Ok is clicked then user should go to Activity2 Page.

    I am unable to do this please help; below is the code:

    protected void onPostExecute(String result) {

    if(result.equals(“login success”)) {
    alertDialog.setButton(“OK”, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {

    else {


  16. Hello guys…. I’m new in android programming but I’m conversant with php…. the above code is working very fine with me, now plz how do I handle my session and navigate to profile page showing the users his/her name in inside the button…. Thanks Admin,Friends and all programmers in this forum…

  17. hello i have an issues where the variables username and password are showing undefined when using post method index when i launch the login.php file on the browser so unable to proceed further so could you please help me!!!!.

Leave a Reply

Your email address will not be published.