Tutorial

Android Login and Registration With PHP MySQL

Published on August 3, 2022
author

By Anupam Chugh

Android Login and Registration With PHP MySQL

Android Login and Registration are very common scenarios. You will find registration and login operation in all the apps where we want user information. In this tutorial, we’ll set up a local web server and MySQL database. We will develop android login and registration application. We will use PHP script to connect to the MySQL database.

Android Login Registration

The first step is to create the backend web server. I am working on Mac OS X and XAMPP can be used to set up a local Apache web server and MySQL database quickly.

Setting Up XAMPP Server

XAMPP(or WAMP) is a one-click installer software that creates an environment for developing a PHP, MySQL web application (that we’ll be connecting with our android application). Download and install XAMPP from here. Launch the XAMPP app after installation and you will be greeted with below screen. xampp application You can test your server by opening https://localhost. The following screen should appear. android xampp dashboard Also, you can check phpMyAdmin by opening https://localhost/phpmyadmin. Let’s see what it shows! android phpmyadmin error OOPS! You might end up with a screen like this. Seems like the MySQL server isn’t properly running. Go To the Manage Servers tab in the XAMPP application and click restart all. The servers should be running properly as seen in the image below. android xampp manage servers Now test phpMyAdmin in the localhost and you’ll end up with a screen similar to this. android phpmyadmin Now let’s test a sample php script. Create a new test.php file and add the following lines into it.

<?php
echo "Hello, World";
?>

In the above code:

  • ?php starts opening tag for any PHP script.
  • ?> means closing tag like closing bracket in Java.

Note: Knowing PHP is not mandatory for this tutorial. if you’re using a MAC then goto Applications->Xampp->htdocs. Create a new folder here lets say test_android and copy paste the test.php that was created before. Now open the url https://localhost/test_android/test.php You’ll end up with a screen like this: android php hello world

Setting Up MySQL Database

Open the phpMyAdmin by visiting https://localhost/phpmyadmin. Now select the Databases Tab that’s present in the top left of the headers row. Give a random name and create it. The newly created empty database would be visible in the left sidebar. android phpmyadmin database create Let’s create a users table in the newly created Database. Run the following query in the console

CREATE TABLE  `firstDB`.`users` (
    `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    `username` VARCHAR( 20 ) NOT NULL ,
    `password` VARCHAR( 20 ) NOT NULL
)

If the table is successfully created, you’ll end up with a screen similar to this: android phpmyadmin create table

Connecting PHP to MySQL Database

To connect a PHP script to MySQL database three input values are required. Following are the inputs and there default values for a XAMPP server

  • Host name: localhost
  • MySQL user name : root
  • MySQL password : It is blank. “”

Let’s create a test-connect.php script and add it in the htdocs->test-android folder.

<?php
$host="localhost";
$user="root";
$password="";
$con=mysql_connect($host,$user,$password);
if($con) {
    echo '<h1>Connected to MySQL</h1>';
} else {
    echo '<h1>MySQL Server is not connected</h1>';
}
?>

mysql_connect() is a PHP’s inbuilt function to connect to MySQL database with the parameters listed above. Try running https://localhost/test_android/test-connect.php and see the output. If it’s not connected, then try restarting the XAMPP servers.

Android Login Registration App

Now that we’ve discussed the basic setup of PHP and MySQL, let’s get into the android login application part. We’ll be developing a sign-in/register application. To keep it short and simple we’ll be checking if the username and email are unique during registration. Before we jump onto the app logic let’s work on the PHP scripts and MySQL Database. First, let’s DROP the Table users and create a fresh one in the context of the above application.

CREATE TABLE IF NOT EXISTS `firstDB`.`users` (
`id` int(20) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`username` varchar(70) NOT NULL,
`password` varchar(40) NOT NULL,
`email` varchar(50) NOT NULL,
`created_at` datetime NOT NULL,
`updated_at` datetime DEFAULT NULL

)

Following are the PHP scripts that you can copy paste in the htdocs->test_android folder. config.php

<?php
    define("DB_HOST", "localhost");
    define("DB_USER", "root");
    define("DB_PASSWORD", "");
    define("DB_NAME", "firstDB");
    ?>

The script for Database connection is given below. db-connect.php

<?php
    
    include_once 'config.php';
    
    class DbConnect{
        
        private $connect;
        
        public function __construct(){
            
            $this->connect = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
            
            if (mysqli_connect_errno($this->connect)){
                echo "Unable to connect to MySQL Database: " . mysqli_connect_error();
            }
        }
        
        public function getDb(){
            return $this->connect;
        }
    }
    ?>

The following script contains all the core functions of the application. user.php

<?php
    
    include_once 'db-connect.php';
    
    class User{
        
        private $db;
        
        private $db_table = "users";
        
        public function __construct(){
            $this->db = new DbConnect();
        }
        
        public function isLoginExist($username, $password){
            
            $query = "select * from ".$this->db_table." where username = '$username' AND password = '$password' Limit 1";
            
            $result = mysqli_query($this->db->getDb(), $query);
            
            if(mysqli_num_rows($result) > 0){
                
                mysqli_close($this->db->getDb());
                
                
                return true;
                
            }
            
            mysqli_close($this->db->getDb());
            
            return false;
            
        }
        
        public function isEmailUsernameExist($username, $email){
            
            $query = "select * from ".$this->db_table." where username = '$username' AND email = '$email'";
            
            $result = mysqli_query($this->db->getDb(), $query);
            
            if(mysqli_num_rows($result) > 0){
                
                mysqli_close($this->db->getDb());
                
                return true;
                
            }
               
            return false;
            
        }
        
        public function isValidEmail($email){
            return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
        }
        
        public function createNewRegisterUser($username, $password, $email){
              
            $isExisting = $this->isEmailUsernameExist($username, $email);
            
            if($isExisting){
                
                $json['success'] = 0;
                $json['message'] = "Error in registering. Probably the username/email already exists";
            }
            
            else{
                
            $isValid = $this->isValidEmail($email);
                
                if($isValid)
                {
                $query = "insert into ".$this->db_table." (username, password, email, created_at, updated_at) values ('$username', '$password', '$email', NOW(), NOW())";
                
                $inserted = mysqli_query($this->db->getDb(), $query);
                
                if($inserted == 1){
                    
                    $json['success'] = 1;
                    $json['message'] = "Successfully registered the user";
                    
                }else{
                    
                    $json['success'] = 0;
                    $json['message'] = "Error in registering. Probably the username/email already exists";
                    
                }
                
                mysqli_close($this->db->getDb());
                }
                else{
                    $json['success'] = 0;
                    $json['message'] = "Error in registering. Email Address is not valid";
                }
                
            }
            
            return $json;
            
        }
        
        public function loginUsers($username, $password){
            
            $json = array();
            
            $canUserLogin = $this->isLoginExist($username, $password);
            
            if($canUserLogin){
                
                $json['success'] = 1;
                $json['message'] = "Successfully logged in";
                
            }else{
                $json['success'] = 0;
                $json['message'] = "Incorrect details";
            }
            return $json;
        }
    }
    ?>

In the above code, the $json contains the JSONObjects returned. The following PHP script is the one that is called upon first from the application. index.php

<?php
    
    require_once 'user.php';
    
    $username = "";
    
    $password = "";
    
    $email = "";
    
    if(isset($_POST['username'])){
        
        $username = $_POST['username'];
        
    }
    
    if(isset($_POST['password'])){
        
        $password = $_POST['password'];
        
    }
    
    if(isset($_POST['email'])){
        
        $email = $_POST['email'];
        
    }
    
    $userObject = new User();
    
    // Registration
    
    if(!empty($username) && !empty($password) && !empty($email)){
        
        $hashed_password = md5($password);
        
        $json_registration = $userObject->createNewRegisterUser($username, $hashed_password, $email);
        
        echo json_encode($json_registration);
        
    }
    
    // Login
    
    if(!empty($username) && !empty($password) && empty($email)){
        
        $hashed_password = md5($password);
        
        $json_array = $userObject->loginUsers($username, $hashed_password);
        
        echo json_encode($json_array);
    }
    ?>

In the above code, we check whether the email field is empty or not. If it is, we’ll call the login function in the PHP script, else we’ll go to the registration function. The JSON response returns two params : success(0 or 1) and the message.

  • The md5() function uses the RSA Data Security, Inc. MD5 Message-Digest Algorithm to create a hash string of the password.
  • To check if the email address is a valid we’ve implemented a isValidEmail() method. FILTER_VALIDATE_EMAIL works on PHP versions 5.2.0+

Android Login Registration Project Structure

android login, android registration In this project, we’ve used three libs for implementing the HTTP Calls in our application. The JSONParser class is used for doing the POST and GET HTTP Calls to the localhost and returning the response in the form of a JSONObject.

Android Login Registration Code

The activity_main.xml layout is defined below.

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:fillViewport="true">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:paddingLeft="24dp"
            android:paddingRight="24dp"
            android:id="@+id/linearLayout">

                <EditText android:id="@+id/editName"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="Username"
                    android:textColor="#FF192133"
                    android:textColorHint="#A0192133"
                    android:fontFamily="sans-serif-light"
                    android:focusable="true"
                    android:focusableInTouchMode="true" />

                <EditText android:id="@+id/editPassword"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="textPassword"
                    android:textColor="#FF192133"
                    android:textColorHint="#A0192133"
                    android:fontFamily="sans-serif-light"
                    android:hint="Password"
                    android:focusable="true"
                    android:focusableInTouchMode="true" />

                <EditText android:id="@+id/editEmail"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="textEmailAddress"
                    android:textColor="#FF192133"
                    android:visibility="gone"
                    android:textColorHint="#A0192133"
                    android:fontFamily="sans-serif-light"
                    android:hint="Email"
                    android:focusable="true"
                    android:focusableInTouchMode="true" />

            <Button
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/btnSignIn"
                android:text="SIGN IN"
                android:textStyle="bold"
                />

            <Button
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/btnRegister"
                android:text="REGISTER"
                android:textStyle="bold"
                />

        </LinearLayout>

    </RelativeLayout>

</ScrollView>

The MainActivity.java is given below.

package com.journaldev.loginphpmysql;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {


    EditText editEmail, editPassword, editName;
    Button btnSignIn, btnRegister;

    String URL= "https://10.0.3.2/test_android/index.php";

    JSONParser jsonParser=new JSONParser();

    int i=0;

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

        editEmail=(EditText)findViewById(R.id.editEmail);
        editName=(EditText)findViewById(R.id.editName);
        editPassword=(EditText)findViewById(R.id.editPassword);

        btnSignIn=(Button)findViewById(R.id.btnSignIn);
        btnRegister=(Button)findViewById(R.id.btnRegister);

        btnSignIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AttemptLogin attemptLogin= new AttemptLogin();
                attemptLogin.execute(editName.getText().toString(),editPassword.getText().toString(),"");
            }
        });

        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if(i==0)
                {
                    i=1;
                    editEmail.setVisibility(View.VISIBLE);
                    btnSignIn.setVisibility(View.GONE);
                    btnRegister.setText("CREATE ACCOUNT");
                }
                else{

                    btnRegister.setText("REGISTER");
                    editEmail.setVisibility(View.GONE);
                    btnSignIn.setVisibility(View.VISIBLE);
                    i=0;

                    AttemptLogin attemptLogin= new AttemptLogin();
                    attemptLogin.execute(editName.getText().toString(),editPassword.getText().toString(),editEmail.getText().toString());

                }

            }
        });


    }

    private class AttemptLogin extends AsyncTask<String, String, JSONObject> {

        @Override

        protected void onPreExecute() {

            super.onPreExecute();

        }

        @Override

        protected JSONObject doInBackground(String... args) {



            String email = args[2];
            String password = args[1];
            String name= args[0];

            ArrayList params = new ArrayList();
            params.add(new BasicNameValuePair("username", name));
            params.add(new BasicNameValuePair("password", password));
            if(email.length()>0)
            params.add(new BasicNameValuePair("email",email));

            JSONObject json = jsonParser.makeHttpRequest(URL, "POST", params);


            return json;

        }

        protected void onPostExecute(JSONObject result) {

            // dismiss the dialog once product deleted
            //Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show();

            try {
                if (result != null) {
                    Toast.makeText(getApplicationContext(),result.getString("message"),Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getApplicationContext(), "Unable to retrieve any data from server", Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }


        }

    }
}

That’s a pretty big code! Let’s draw the important inferences from the above code.

  1. https://10.0.3.2 is the localhost rerouting address. This address works exclusively if you’re using the Genymotion emulator. Use https://10.0.2.2 for the AVD Emulator which is much improved now. If you’re running the application on your own device using your computer’s WIFI address instead. Example: https://192.168.0.143.
  2. When the REGISTER Button is clicked we programmatically hide the SIGN IN Button and display the Email Address input text field instead.
  3. The AttemptLogin class executes the network HTTP requests to our localhost in the background. The username password and email parameters are added to an ArrayList that are passed in the method makeHttpRequest(URL, “POST”, params); of the JSONParser class.
  4. In the onPostExecute Method we display the message string returned from the server in a Toast message.

The JSONParser.java class is given below.

package com.journaldev.loginphpmysql;

import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

/**
 * Created by anupamchugh on 29/08/16.
 */
public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static JSONArray jArr = null;
    static String json = "";
    static String error = "";

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
                                      ArrayList params) {

        // Making HTTP request
        try {

            // check for request method
            if(method.equals("POST")){
                // request method is POST
                // defaultHttpClient
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));
                try {
                    Log.e("API123", " " +convertStreamToString(httpPost.getEntity().getContent()));
                    Log.e("API123",httpPost.getURI().toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }

                HttpResponse httpResponse = httpClient.execute(httpPost);
                Log.e("API123",""+httpResponse.getStatusLine().getStatusCode());
                error= String.valueOf(httpResponse.getStatusLine().getStatusCode());
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method.equals("GET")){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
            Log.d("API123",json);
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try to parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
            jObj.put("error_code",error);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }

    private String convertStreamToString(InputStream is) throws Exception {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        is.close();
        return sb.toString();
    }
}

In the above code, we’re calling the respective classes HTTPPost or HTTPGet depending on the the second parameter that’s passed in the makeHttpRequest function.

jObj.put("error_code",error);

Above, we are appending the response status code returned from the server in the final JSONObject that’s returned to the MainActivity class. Note: Don’t forget to add the following permission in your AndroidManifest.xml file.

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

Many Users have posted their comments at the bottom of this tutorial, stating they’re getting “Unable to retrieve data” Toast. Please note that since Android 6.0 and above you need to add the following attribute in your application tag in the Manifest.xml file: android:usesCleartextTraffic="true" Why so? In order to allow the network security of the emulator/device to do http calls. Please check the output with the latest screengrabs from Android Q emulator below. Latest source code with the changes in the AndroidManifest.xml file is updated in the link and our Github Repository.

The output of the application in action is given below.

Android Registration User

In the below screengrab we register a new user and it gets added in the Database. We then login using the credentials we entered during registration.

Android Login With Php Mysql Final Output
Android Login With Php Mysql Final Output

This brings an end to the Android Login with PHP MySQL Tutorial. You can download the project from the link below. It contains the test_android folder too that holds the PHP files. Copy it into the xampp->htdocs folder! Good Luck.

Download Android Login Registration PHP MySQL Project

You can also access the full source code from our Github Repository below:

Github Project Link

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author(s)

Category:
Tutorial
Tags:

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
October 14, 2016

Thank u sir…its 100% correct…i got it…awesome codes

- Bibhuti

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
February 11, 2017

Hi Bibhuti, Happy to know that Thanks

- Anupam Chugh

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
June 15, 2017

Though Intent Condition has Entered it is not working!!!

- raghu

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    June 15, 2017

    Hi Bibhuti, It’s not working for me… once post u’r code

    - raghu

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      October 17, 2016

      Where do i put the New Intent code to start a new activity after successful Login and Register??? PLZ HELP?

      - Bibhuti

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      October 20, 2016

      Hi Bibhuti, if (result != null) { Toast.makeText(getApplicationContext(),result.getString(“message”),Toast.LENGTH_LONG).show(); //INTENT statement goes in here. }

      - Anupam Chugh

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        October 18, 2016

        When I press Sign In or create account button it says" unable to retrieve data from server". Please help me to resolve it.

        - Rose

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        October 20, 2016

        Hi Rose, “unable to retrieve data from server” indicates that the result retrieved from the web server is NULL. You should cross check the following things in your code: Is your network connection stable? Is your xampp sever running correctly? Is your localhost url https://10.0.3.2 ? It depends on whether you’re using genymotion or the standard emulator.

        - Anupam Chugh

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        October 21, 2016

        I’m having the same problem… Is your network connection stable? -Yes Is your xampp sever running correctly? -Yes The only thing is that I’m using the standard emulator. Please help.

        - Fisch

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        December 20, 2017

        bro did you got the solution?

        - Praful Dhabekar

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        March 21, 2018

        Did any of you get a solution to this? I’m stuck here too!

        - Akshit

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          March 22, 2018

          I wasn’t connecting my phone and laptop on a common network. I shared my phone’s hotspot with my laptop and it worked! Hope this helps.

          - Akshit

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          March 23, 2018

          Great Observation Akshit. This should help quite a few people. Nicely figured it out!

          - Anupam Chugh

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            October 25, 2016

            Hey, thanks for you perfect tutorial … this was the most clear tutorial in the internet for me concerning login and registration in android! But one question: What is the best way to achieve that the new acitivty is only started after a successful login? If i am not mistaken, the new intent code should be inserted here: if (result != null) { Toast.makeText(getApplicationContext(),result.getString(“message”),Toast.LENGTH_LONG).show(); // Open startBildschirm Intent intent = new Intent(getApplicationContext(), XXXACTIVTYXXX.class); startActivity(intent); The problem is that the new activity is started in any case… Should I check if result.getString(‘message’) == “Sucessfull Login” -> start Intent or is there a better way? Thank you so much!

            - Maper

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            October 28, 2016

            Hi Maper, Yes you’re right. This is the ideal way indeed. if result.getString(‘message’).equals(“Successful Login”)) { //Intent statement }

            - Anupam Chugh

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            June 2, 2017

            sir help me to solve this error - AttempLogin gives an error of it must be declared as abstract or implement abstract method ‘doInBackground(Params…)’ in ‘AsyncTask’

            - Devesh Soni

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            January 10, 2018

            Hi Devesh, The AsyncTask declaration is like this: private class AttemptLogin extends AsyncTask<String, String, JSONObject> { //the methods are overridden here. } The code gives you an error because this wasn’t defined: <String, String, JSONObject> Apparently, it wasn’t visible in the post before. Though it’s present in the full source code when you download. I’ve updated the post. So it should be visible in the post too. Thanks

            - Anupam Chugh

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              April 17, 2019

              a lot of concern about “unable to retrieve data from the server” has been mentioned in the comments . why does the dev doesnt addressing this concern??

              - abdul sibak

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              April 17, 2019

              Hi Adbul, The latest code and the reason for it not working for many users has been updated in the post. Thanks

              - Anupam Chugh

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                November 14, 2016

                How can I log out?

                - Bruno

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                May 12, 2018

                Try creating a PHP function for that, just the same way as the login. Probably use an auth_token and clear it.

                - Anupam Chugh

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  December 3, 2016

                  how i add verification code like whatsapp and other app verifies number how i add that source code in this code project please reply as soon as possible and help me for this coding.thanku

                  - aamrin

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    December 8, 2016

                    Sir First of all thank you very much … and secondly sir plz teach ma that… when i click sign in button then how to open a new activity form…

                    - Munawar

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    February 11, 2017

                    Hi Munawar, Use Intents Thanks

                    - Anupam Chugh

                      JournalDev
                      DigitalOcean Employee
                      DigitalOcean Employee badge
                      December 12, 2016

                      Hi Sir can i know what is the problem if the method of AttempLogin gives an error of it must be declared as abstract or implement abstract method ‘doInBackground(Params…)’ in ‘AsyncTask’ ?

                      - Cli

                      JournalDev
                      DigitalOcean Employee
                      DigitalOcean Employee badge
                      August 1, 2017

                      Finanally solved it, here’s the solution private class AddAsyncTask extends AsyncTask

                      - Mamman

                      JournalDev
                      DigitalOcean Employee
                      DigitalOcean Employee badge
                      August 16, 2017

                      private class AttemptLogin extends AsyncTask

                      - Massolihen Dasuki

                      JournalDev
                      DigitalOcean Employee
                      DigitalOcean Employee badge
                      May 12, 2018

                      Glad it helped you Mamman :)

                      - Anupam Chugh

                        JournalDev
                        DigitalOcean Employee
                        DigitalOcean Employee badge
                        August 29, 2017

                        ??? where to add this

                        - JUSTIN JOHN

                        JournalDev
                        DigitalOcean Employee
                        DigitalOcean Employee badge
                        January 10, 2018

                        The AsyncTask declaration is like this: private class AttemptLogin extends AsyncTask<String, String, JSONObject> { //the methods are overridden here. } The code gives you an error because this wasn’t defined: <String, String, JSONObject> Apparently, it wasn’t visible in the post before. Though it’s present in the full source code when you download. I’ve updated the post. So it should be visible in the post too.

                        - Anupam Chugh

                          JournalDev
                          DigitalOcean Employee
                          DigitalOcean Employee badge
                          January 10, 2018

                          Hi Cli, The AsyncTask declaration is like this: private class AttemptLogin extends AsyncTask<String, String, JSONObject> { //the methods are overridden here. } The code gives you an error because this wasn’t defined: <String, String, JSONObject> Apparently, it wasn’t visible in the post before. Though it’s present in the full source code when you download. I’ve updated the post. So it should be visible in the post too. Thanks

                          - Anupam Chugh

                            JournalDev
                            DigitalOcean Employee
                            DigitalOcean Employee badge
                            December 21, 2016

                            perfect!! thxxxxx best tutorial .

                            - yas

                            JournalDev
                            DigitalOcean Employee
                            DigitalOcean Employee badge
                            February 11, 2017

                            Hi yas, Happy to hear that Thanks

                            - Anupam Chugh

                            JournalDev
                            DigitalOcean Employee
                            DigitalOcean Employee badge
                            January 8, 2018

                            @Override protected JSONObject doInBackground(String… args) { String email = args[2]; String password = args[1]; String name= args[0]; why this code gives erorr"method does not override" please tell the solution

                            - ansa

                            JournalDev
                            DigitalOcean Employee
                            DigitalOcean Employee badge
                            January 10, 2018

                            Hi Ansa, The AsyncTask declaration is like this: private class AttemptLogin extends AsyncTask<String, String, JSONObject> { //the methods are overridden here. } The code gives you an error because this wasn’t defined: <String, String, JSONObject> Apparently, it wasn’t visible in the post before. Though it’s present in the full source code when you download. I’ve updated the post. So it should be visible in the post too. Thanks

                            - Anupam Chugh

                              JournalDev
                              DigitalOcean Employee
                              DigitalOcean Employee badge
                              December 30, 2016

                              thank you, i am still facing challenges to an apple running on my phone to login on the mysql database, i have followed all the steps, i tried when i setup hostednetwork on my laptop failed, also i tried when am using home wireless where both my phone and laptop are connected to also failed. when i click on login button it shows no change.

                              - LUSAATA DENIS

                                JournalDev
                                DigitalOcean Employee
                                DigitalOcean Employee badge
                                January 4, 2017

                                When I press Sign In or create account button it says” unable to retrieve data from server”…i am running on my phone

                                - Andy

                                  JournalDev
                                  DigitalOcean Employee
                                  DigitalOcean Employee badge
                                  January 26, 2017

                                  I’m facing some problem… Its not adding content to I he db neither buttons are working.pls help me

                                  - Dev

                                    JournalDev
                                    DigitalOcean Employee
                                    DigitalOcean Employee badge
                                    January 26, 2017

                                    I’m facing some problem… Its not adding content to the db neither buttons are working.pls help me pls.

                                    - Dev

                                      JournalDev
                                      DigitalOcean Employee
                                      DigitalOcean Employee badge
                                      February 10, 2017

                                      i cant get login it will registered me but when i press login its says invalid details …

                                      - shabih

                                      JournalDev
                                      DigitalOcean Employee
                                      DigitalOcean Employee badge
                                      February 11, 2017

                                      Hi shabih, Apparently the there must be some whitespace after the email/password text. To ensure that whitespace isn’t taken into consideration, use editText.getText().toString().trim(); Thanks

                                      - Anupam Chugh

                                        JournalDev
                                        DigitalOcean Employee
                                        DigitalOcean Employee badge
                                        February 28, 2017

                                        “unable to retrieve data from server” - I get E/JSON Parser: Error parsing data org.json.JSONException: Value <script of type java.lang.String cannot be converted to JSONObject. Seems like I’m getting HTML respnsone instead of JSON.

                                        - lol

                                          JournalDev
                                          DigitalOcean Employee
                                          DigitalOcean Employee badge
                                          March 26, 2017

                                          Hello is there a way to use web server such as 000webhost instead of xampp?

                                          - Sarah Lee

                                            JournalDev
                                            DigitalOcean Employee
                                            DigitalOcean Employee badge
                                            April 12, 2017

                                            hi , I m doing my final year MCA project on Canteen Automation System it will include two system i.e desktop application and android . i have developed android application in android studio and desktop in asp.net with C# and my database should be the common so that i can access same data from both mobile and desktop . can you please suggest which database i should use ?? i m very much confused between mysql and sql . your suggestion will help for me.

                                            - Urvashi Sondagar

                                              JournalDev
                                              DigitalOcean Employee
                                              DigitalOcean Employee badge
                                              April 22, 2017

                                              public class AttemptLogin extends AsyncTask { /// i have an error in this portion can you please help @Override protected void onPreExecute() { super.onPreExecute();

                                              - Akhil ps

                                              JournalDev
                                              DigitalOcean Employee
                                              DigitalOcean Employee badge
                                              May 12, 2018

                                              Do refer to the Async Task tutorial: https://www.journaldev.com/9708/android-asynctask-example-tutorial

                                              - Anupam Chugh

                                                JournalDev
                                                DigitalOcean Employee
                                                DigitalOcean Employee badge
                                                May 18, 2017

                                                It is very useful tutorial…you have done great job with sharing knowledge with us…So i hope you will continue this…

                                                - Dushantha

                                                JournalDev
                                                DigitalOcean Employee
                                                DigitalOcean Employee badge
                                                May 19, 2017

                                                In each case it arises “Incorrect Details” toast message??

                                                - arjun

                                                  JournalDev
                                                  DigitalOcean Employee
                                                  DigitalOcean Employee badge
                                                  May 12, 2018

                                                  Dushantha, glad it helped you!

                                                  - Anupam Chugh

                                                    JournalDev
                                                    DigitalOcean Employee
                                                    DigitalOcean Employee badge
                                                    May 19, 2017

                                                    I am not able to anything. Neither Sign In nor Register. Whatever I am trying to do it says Incorrect details. However there is no any whitespace between data. email is in correct format, still i am unable to register.

                                                    - arjun

                                                      JournalDev
                                                      DigitalOcean Employee
                                                      DigitalOcean Employee badge
                                                      May 20, 2017

                                                      public class AttemptLogin extends AsyncTask { /// i have an error in this portion can you please help @Override protected void onPreExecute() { super.onPreExecute();

                                                      - Dushantha

                                                      JournalDev
                                                      DigitalOcean Employee
                                                      DigitalOcean Employee badge
                                                      May 21, 2017

                                                      i’m having the same error actually the problem is in dobackground method …kindly help if you have debug this error…

                                                      - Aqsa Ayub

                                                      JournalDev
                                                      DigitalOcean Employee
                                                      DigitalOcean Employee badge
                                                      August 29, 2017

                                                      anyone got solution to this Async task?

                                                      - JUSTIN JOHN

                                                        JournalDev
                                                        DigitalOcean Employee
                                                        DigitalOcean Employee badge
                                                        June 2, 2017

                                                        hi sir, is it possible to connect it with a server

                                                        - fawaz

                                                          JournalDev
                                                          DigitalOcean Employee
                                                          DigitalOcean Employee badge
                                                          June 27, 2017

                                                          package com.login; import android.app.Activity; import android.content.ContentValues; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import static android.R.attr.name; public class SignActivity extends Activity { TextView snam,pass,loc,con,uname; EditText enam,epass,email,econ,eunam; Button subtn; sqlite sq; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sign); enam = (EditText) findViewById(R.id.sena); epass = (EditText) findViewById(R.id.sepas); email = (EditText) findViewById(R.id.semail); econ = (EditText) findViewById(R.id.secpas); eunam = (EditText) findViewById(R.id.seuna); subtn = (Button) findViewById(R.id.subtn); subtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (enam.getText().toString().equals(“”)|| email.getText().toString().equals(“”)) { enam.setError(“field is empty”); } else { ContentValues conValue = new ContentValues(); conValue.put(“name”, enam.getText().toString()); conValue.put(“loc”, email.getText().toString()); conValue.put(“unam”, eunam.getText().toString()); conValue.put(“pass”, epass.getText().toString()); sqlite sqli = new sqlite(SignActivity.this); long i = sqli.insertAction(conValue, “login”); Toast.makeText(SignActivity.this, “successfully entered”+i, Toast.LENGTH_LONG).show(); enam.setText(“”); email.setText(“”); epass.setText(“”); econ.setText(“”); eunam.setText(“”); } } }); } }

                                                          - sam

                                                            JournalDev
                                                            DigitalOcean Employee
                                                            DigitalOcean Employee badge
                                                            July 11, 2017

                                                            Thanks a lot for the nice tutorial. Now how to put an intent to login to direct it to a new activity?

                                                            - Cédric

                                                            JournalDev
                                                            DigitalOcean Employee
                                                            DigitalOcean Employee badge
                                                            July 12, 2017

                                                            startActivity(new Intent(LoginActivity.java, NewActivity.java));

                                                            - Anupam Chugh

                                                            JournalDev
                                                            DigitalOcean Employee
                                                            DigitalOcean Employee badge
                                                            December 10, 2017

                                                            “startActivity(new Intent(LoginActivity.java, NewActivity.java));” sir where should i put this code? thanks

                                                            - beginner

                                                              JournalDev
                                                              DigitalOcean Employee
                                                              DigitalOcean Employee badge
                                                              July 20, 2017

                                                              100% working but can u please give us logout activity also

                                                              - venkatesh

                                                              JournalDev
                                                              DigitalOcean Employee
                                                              DigitalOcean Employee badge
                                                              September 19, 2017

                                                              Just create a new Activity Venkatesh. And add the intent to the new Activity in the current one.

                                                              - Anupam Chugh

                                                                JournalDev
                                                                DigitalOcean Employee
                                                                DigitalOcean Employee badge
                                                                August 29, 2017

                                                                hello do i have to make any changes in code in php files? for eg dbconnect.php? mine is showing unable to retrive data from server! hope ull help?

                                                                - JUSTIN JOHN

                                                                JournalDev
                                                                DigitalOcean Employee
                                                                DigitalOcean Employee badge
                                                                December 20, 2017

                                                                Maybe you have to change password in config.php file.

                                                                - Praful Dhabekar

                                                                  JournalDev
                                                                  DigitalOcean Employee
                                                                  DigitalOcean Employee badge
                                                                  September 20, 2017

                                                                  The code works, but whenever I register a user, different password saves on the database. If I try to login, it says incorrect details though it is correct. What should I do?

                                                                  - Grae

                                                                    JournalDev
                                                                    DigitalOcean Employee
                                                                    DigitalOcean Employee badge
                                                                    October 5, 2017

                                                                    sir how can i get values from database to my activity???

                                                                    - shahid Ali

                                                                      JournalDev
                                                                      DigitalOcean Employee
                                                                      DigitalOcean Employee badge
                                                                      November 24, 2017

                                                                      great post so thanks because this post is so amazing.

                                                                      - firefox mozilla not responding

                                                                      JournalDev
                                                                      DigitalOcean Employee
                                                                      DigitalOcean Employee badge
                                                                      May 12, 2018

                                                                      Appreciate that!

                                                                      - Anupam Chugh

                                                                        JournalDev
                                                                        DigitalOcean Employee
                                                                        DigitalOcean Employee badge
                                                                        January 4, 2018

                                                                        loginphpmysql.iml thus it is required to put into the android project what is the use of that

                                                                        - VJ

                                                                          JournalDev
                                                                          DigitalOcean Employee
                                                                          DigitalOcean Employee badge
                                                                          February 23, 2018

                                                                          Hi, i am facing depreciation for defaultHttpClient which is being triked off in my code how can i resolve that issue.

                                                                          - Akash

                                                                          JournalDev
                                                                          DigitalOcean Employee
                                                                          DigitalOcean Employee badge
                                                                          February 25, 2018

                                                                          Hi Akash, Add the following to your build.gradle. useLibrary 'org.apache.http.legacy'

                                                                          - Anupam Chugh

                                                                            JournalDev
                                                                            DigitalOcean Employee
                                                                            DigitalOcean Employee badge
                                                                            February 24, 2018

                                                                            you forgot to see add library in android code and thats why main xml file is not created properly and in mani activity occur so many errors

                                                                            - Akshay

                                                                              JournalDev
                                                                              DigitalOcean Employee
                                                                              DigitalOcean Employee badge
                                                                              March 16, 2018

                                                                              Thank you for the amazing tutorial! Is it still recommended to use HttpClient ? if i wanted to use the URLConnecton what should i replace in the code? Thanks

                                                                              - ghost

                                                                                JournalDev
                                                                                DigitalOcean Employee
                                                                                DigitalOcean Employee badge
                                                                                April 4, 2018

                                                                                Hi sir…if i want to redirect after successful login then where should i put intent code means at which position…i tried but in that if user is not registered then also it will redirect activity…so please help to solve this problem.

                                                                                - janki

                                                                                JournalDev
                                                                                DigitalOcean Employee
                                                                                DigitalOcean Employee badge
                                                                                April 5, 2018

                                                                                Check in the postExecute method if the “success” param is true. if(result.getBoolean(“success”) { //Create intent. }

                                                                                - Anupam Chugh

                                                                                  JournalDev
                                                                                  DigitalOcean Employee
                                                                                  DigitalOcean Employee badge
                                                                                  April 25, 2018

                                                                                  Thanku for the post. But my users who are registered are not shown in mysql. Can u pls help me.

                                                                                  - Joe Paul

                                                                                    JournalDev
                                                                                    DigitalOcean Employee
                                                                                    DigitalOcean Employee badge
                                                                                    April 26, 2018

                                                                                    When i am click on the create account button i am getting message as “unable to retrieve the server” please help me to solve this problem

                                                                                    - Ashok

                                                                                    JournalDev
                                                                                    DigitalOcean Employee
                                                                                    DigitalOcean Employee badge
                                                                                    July 25, 2018

                                                                                    i get this notif too

                                                                                    - admin

                                                                                      JournalDev
                                                                                      DigitalOcean Employee
                                                                                      DigitalOcean Employee badge
                                                                                      May 2, 2018

                                                                                      I want to set a role_id for admin and users how should I use them in both php and android. I planning to use with SharedPreferences but I don’t have much idea how it will fulfill please help

                                                                                      - Swanand Joshi

                                                                                        JournalDev
                                                                                        DigitalOcean Employee
                                                                                        DigitalOcean Employee badge
                                                                                        May 16, 2018

                                                                                        I want to read this article offline, how can i do that? Cause i’am not always connected to the internet. . .

                                                                                        - Joe Joe Oej

                                                                                        JournalDev
                                                                                        DigitalOcean Employee
                                                                                        DigitalOcean Employee badge
                                                                                        May 17, 2018

                                                                                        Hi Joe Joe, Luckily we have the Android Application ready just in time for you. We do provide an option to bookmark tutorials there. You can download it from the below link. https://play.google.com/store/apps/details?id=com.journaldev.app&hl=en\_IN

                                                                                        - Anupam Chugh

                                                                                          JournalDev
                                                                                          DigitalOcean Employee
                                                                                          DigitalOcean Employee badge
                                                                                          July 26, 2018

                                                                                          how to add registration by otp

                                                                                          - amit

                                                                                          JournalDev
                                                                                          DigitalOcean Employee
                                                                                          DigitalOcean Employee badge
                                                                                          July 30, 2018

                                                                                          You need to write a php code for it.

                                                                                          - Anupam Chugh

                                                                                            JournalDev
                                                                                            DigitalOcean Employee
                                                                                            DigitalOcean Employee badge
                                                                                            August 6, 2018

                                                                                            Hi…I’m getting the “unable to retrieve any data from the server”… please help

                                                                                            - Mbulelo

                                                                                            JournalDev
                                                                                            DigitalOcean Employee
                                                                                            DigitalOcean Employee badge
                                                                                            August 16, 2018

                                                                                            same error i get it what to do?

                                                                                            - bhagyashri

                                                                                              JournalDev
                                                                                              DigitalOcean Employee
                                                                                              DigitalOcean Employee badge
                                                                                              September 19, 2018

                                                                                              check your db connect php script … because the example given contains error … it should be mysqli_connect , not like in the example mysql_connect

                                                                                              - Syirasky

                                                                                                JournalDev
                                                                                                DigitalOcean Employee
                                                                                                DigitalOcean Employee badge
                                                                                                August 8, 2018

                                                                                                HI. I Have done everything. I am able to login as well but I want one more function I would be glad if you help. After successful login I want to switch activity as well. ( From MainActivity to other activity.)

                                                                                                - Nirav

                                                                                                  JournalDev
                                                                                                  DigitalOcean Employee
                                                                                                  DigitalOcean Employee badge
                                                                                                  August 8, 2018

                                                                                                  HI. I am using above mention codes. My application works fine only over my wifi but I am not able to use to from mobile network and other wifi networks. Please guide.

                                                                                                  - Nirav

                                                                                                    JournalDev
                                                                                                    DigitalOcean Employee
                                                                                                    DigitalOcean Employee badge
                                                                                                    August 16, 2018

                                                                                                    When I press Sign In or create account button it says” unable to retrieve data from server”…i am running on my phone

                                                                                                    - bhagyashri

                                                                                                      JournalDev
                                                                                                      DigitalOcean Employee
                                                                                                      DigitalOcean Employee badge
                                                                                                      September 10, 2018

                                                                                                      Hello there! Everything works perfectly. I have a question. How to check if the user is logged in already and then automatically redirected to the home page activity. Instead of logging every time I open the app. Thanks!

                                                                                                      - johnlopev

                                                                                                        JournalDev
                                                                                                        DigitalOcean Employee
                                                                                                        DigitalOcean Employee badge
                                                                                                        September 20, 2018

                                                                                                        i got this kind of error, help me please FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ‘:app:transformResourcesWithMergeJavaResForDebug’. > More than one file was found with OS independent path ‘META-INF/DEPENDENCIES’ * Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

                                                                                                        - Nur

                                                                                                          JournalDev
                                                                                                          DigitalOcean Employee
                                                                                                          DigitalOcean Employee badge
                                                                                                          September 20, 2018

                                                                                                          Sir, Can i get the same procedure for fetching the database from mysql & php?

                                                                                                          - Saqueeb Shariff

                                                                                                            JournalDev
                                                                                                            DigitalOcean Employee
                                                                                                            DigitalOcean Employee badge
                                                                                                            September 21, 2018

                                                                                                            My application stops when i run it. It shows “com. Example. Login has stopped”. Checked for logcat and it shows error in onCreate method

                                                                                                            - Saba

                                                                                                              JournalDev
                                                                                                              DigitalOcean Employee
                                                                                                              DigitalOcean Employee badge
                                                                                                              September 22, 2018

                                                                                                              Why I can’t sign in? It says “Error in registering. Probably the username/email already exists.” The username and email is not the same from db. Help me please…

                                                                                                              - Mim

                                                                                                                JournalDev
                                                                                                                DigitalOcean Employee
                                                                                                                DigitalOcean Employee badge
                                                                                                                September 23, 2018

                                                                                                                In the onPostExecute() funtion. The “result” is unable save the data. Due to which it is executing “else” toast. I donot understand where i went wrong. Plz help

                                                                                                                - Hamza Naeem

                                                                                                                  JournalDev
                                                                                                                  DigitalOcean Employee
                                                                                                                  DigitalOcean Employee badge
                                                                                                                  October 1, 2018

                                                                                                                  hello, i am new to this how do i create 2 types of user?

                                                                                                                  - ryan

                                                                                                                    Join the Tech Talk
                                                                                                                    Success! Thank you! Please check your email for further details.

                                                                                                                    Please complete your information!

                                                                                                                    Become a contributor for community

                                                                                                                    Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                                                                                                                    DigitalOcean Documentation

                                                                                                                    Full documentation for every DigitalOcean product.

                                                                                                                    Resources for startups and SMBs

                                                                                                                    The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                                                                                                                    Get our newsletter

                                                                                                                    Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                                                                                                                    New accounts only. By submitting your email you agree to our Privacy Policy

                                                                                                                    The developer cloud

                                                                                                                    Scale up as you grow — whether you're running one virtual machine or ten thousand.

                                                                                                                    Get started for free

                                                                                                                    Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                                                                                                                    *This promotional offer applies to new accounts only.