This is an easy step by step tutorial of how to make an Android PHP MySQL app to create login and registration form, where in the login form, data is cached when you already logged in. In this tutorial, you will learn one important topic, how to connect Android with PHP and MySQL by using an AsyncTask-based library called “generic asynctask v2“, which I created for later use. It is easier to use than the original AsyncTask itself because the code is almost just two lines straight. Another thing is that when after you create an account for an app, says Facebook, you will be asked to login for the first time. After you did login, you won’t get any login form again. You simply go straight to the Newsfeed. So how could you do that? Well, in this tutorial you will learn actually this. We will use SharedPreferences to save/cache the login data to test later on when another login. I also have a great video tutorial about caching data with SharedPreferences with a great details, in case you wanna learn it.

Android PHP MySQL Login Registration Form 2Android PHP MySQL Login Registration Form

Android PHP MySQL Login and Registration (Cache Data with SharedPreferences)

Background

As you know your phone cannot store any large data like you do on your computer. In your computer if you think when you were learning Java or C#, you could store data on your database server right inside the same computer. Your computer just needed a connector such as ODBC, JDBC, or ADO.NET to connect from your software to your database server without using any middleman, the web server. This practice can work well for a small school registration system where you use one machine to enroll new students, store data on SQL Server or MySQL, and print out to a printer next to the computer.

kosalgeek asynctask diagramHowever, your smart phone can no longer do that even for testing. In order to connect from your phone to a database server, says MySQL, you must need a web server to act as a web service. You can use a standard Restful API or use simple plain PHP. It is not limited to PHP, you can use JSP or ASP.NET or even other popular open source like Ruby on Rails or Python. As long as your server side code can let you pass the POST, GET, PUT, DELETE request, it is good to go.

For me, I find PHP is very simple to use while you can write a few lines of code and you can use WAMP as your Web Server out of the gate.

Motivation

Why another tutorial about Android PHP MySQL login and registration form, you may ask? Because there are plenty of good tutorials outside on the webs including the one from androidhive, journaldev, and inducesmile, right? Actually, it is wrong with those, but those have something in common. They use plant old AsyncTask which is very difficult to modify, and they don’t use caching which is the most point of making login page.

Video Demo of The Final Output

Below is the presentation the final output of our project. I suggest you to watch until the end to really understand what are the points we are trying to accomplish:

Did you watch the video until the end? If yes, I gotta ask you one question: how many Activities that I did in my project? One, two, three, four, five, six?

If you say four, that is correct. For the simplicity, I created four Activities:
1st for Splashscreen
2nd for Login Form
3rd for Registration Form
4th for Main Page

LET’S BUILD ANDROID MySQL PHP APP

I. Install Necessary Software

1. Android Studio

Up to this point, I hope you already downloaded and installed Android Studio. If you don’t have it yet, maybe it is a good time to download it. Click here to download Android Studio. The installation is very straight forward, just click next ok most of the time.

2. Geny Motion

Geny Motion is a great alternative of a slow built-in Android emulator. It is paid product but it has a free version. It is very deceiving to go the page to download it because you will usually some dollars signs every where. You will need to sign up for an account first before you can download it. You would see something like the screenshot below:download genymotion

The user account is very important because you will need it to download your testing virtual devices later on. Here are my virtual devices for testing:

genymotion

3. XAMPP or WAMP

In order to run Apache server, PHP and MySQL, you can use XAMPP for Mac and Windows. But for Windows, people prefer WAMP. Because I will use Windows for this tutorial, I will stick with WAMP, but you are free to use any. Click here to download the latest WAMP.

If you are using your another database server, says MS SQL Server, in your computer, you are likely you have problem with your default 80 port. If you have such a problem, you can change it to other port number, says 8089. If you are sure, you can follow the steps down below:

Step 1: Open httpd.conf

Step 2: Change from 80 to 8089

Step 3: change to ServerName localhost:8090

4. Text Editor

Again, it is according to your preference. I am not gonna argue with this but I will use Notepad++ where you can download it from here. I used Brackets in my Mac and it was very good too.

II. Work with Database

1. Create a database

Let’s call our database “todolistonline” and create it with the collation of UTF8.

2. Create a table

In this example, we will create only a table first. Let me call it table_user. Below is the code that you can paste it in the SQL tab:

If you don’t know how to run the code, see the screenshot below:

II. PHP as a Web Service

Here I created 3 PHP files: connection.php, login.php, and register.php.

connection.php

This code is reusable even thought it is not in a fancy class. But you copy and paste to your new file and name it as connection.php. What you can do is that you can change your database name in the $dbname. And if you have a different username and password, you can them too. However, you should never touch the $servername because it most of the time is “localhost” even in the real hosting.

1. login.php

Let me explain a bit the code above. First I test whether you really send the data via POST request with the key email and password or not, as well as test them if they are not empty. Then, I test the provided email and password against the database. If the result returns num_rows is greater than zero, it means that the record with the email and password exists. So I echo “LoginSuccess”. The LoginSuccess is very important here because we will use it later to test with the Android. So please don’t change this echo text. For the else part, it is just for debugging.

2. register.php

For the register, it is quite similar to login, except we use INSERT INTO instead of SELECT. Here the code in else part, the echo “ErrorInsert” is very important for our Android code later so don’t change this echo text. Another echo below it, it is debugging. And in the true condition, the $last_id is for displaying the record id.

Here, you can ask why I don’t use JSON. Well, JSON is good but it does not have to be. If I use JSON, then it needs Json Parser which makes the code more complex than it should be. The plain old echo works fine too.

III. Create an Android Project

We have 4 Activities in our Android project: StartupActivity, LoginActivity, RegisterActivity, and MainPageActivity.

First, We start from StartupActivity. In the Splash Screen, you will check the saved cache data for the login. If it returns null, then we send users to LoginActivity. If it returns some data, then we test the data against the one in the remote database server, if it returns true again, then we send users to the MainPageActivity.

Second, in your LoginActivity, you have two fields, email and password, and one button. Below the button, you can have a nice link to go to Register.

Next, in the RegisterActivity, you have three textboxes – email, password and confirm password, and of course a button.

Lastly, The MainPageActivityis menu activity where users can use your service. It is a good idea to use Navigation Drawer for your MainPageActivity. Once again, if you wanna learn more about Navigation Drawer, you watch this tutorial which consists of three parts.

1. Startup Activity

startup screen

Here is XML code for activity_startup.xml:

The startup activity is the splash screen actually. The whole point is show users your app logo. In this case, I put an ImageView that takes the whole screen. I imported startup.jpg into the drawable folder and use it as the source of the ImageView.

And for Java code at StartupActivity.java:

In StartupActivity.java, the most important code is when I use:

SharedPreferences pref = getSharedPreferences(“loginData”, MODE_PRIVATE); SharedPreferences.Editor editor = pref.edit();
//editor.clear(); //for bebugging
//editor.commit(); //for bebugging
emailStored = pref.getString(“email”, null);
passwordStored = pref.getString(“password”, null);

First you declare a variable pref in order to store and get cache from your internal app data. And I named it loginData. the MODE_PRIVATE is very important to protect from hacking. You can use MODE_PUBLIC but you should not.

And then, you declare another variable editor in order to edit. If you wanna clear, you need to call clear() and commit() together.

When you wanna get data, you can call pref.getString(“key”, null). You can however use another data type behind string. The first parameter is key and second one is your default data, usually null. After that, you can use if statement to test it. I said earlier that you can test the cache data against the database data, but for simplicity, I don’t test it. If true, then you send users to a Main Page, or false, then send to a Login Page.

And the code around that started from new Handler() is for waiting for 3000 milliseconds (3 seconds). It makes your app look like it is retrieve some data. Just for cool reason.

2. Login Activity

login screen

Here is XML code for activity_login.xml:

The UI here is not complex to explain, just two EditTexts, one Button, and one TextView.

And for Java code at LoginActivity.java:

The java file above is where you connect login.php page. As you can see the last line:
loginTask.execute(“http://10.0.3.2:8089/todolistonline/login.php”);

The 10.0.3.2 is the alias for GenyMotion’s localhost. If you use a built-in emulator, you will use 10.0.2.2. Note that, you cannot use localhost here because your emulator also has a localhost. That’s why you have to use alias. In case, you test your real Android device, e.g. Samsung Galaxy S8, then you need to change the number to your computer IP address, for example, 192.168.10.14. This IP address 192.168.10.14 is just example. You must check it in your real computer. You check it in your command prompt and type ipconfig command. The reason that you use your computer IP address here is because your computer has WAMP and MySQL which acts just like a real server. If you use a real hosting domain, e.g. http://kosalgeek.com, then you need to use it.

Where is the main code to connect to the web server? It is when you call PostResponseAsyncTask. You will need to import my library from my Github kosalgeek generic asynctask v2. You can learn it in great detail of how to use the Generic AsyncTask library here.

You may take note that I use SharePreferences here too. It is for add data into the cache.

Another point to make is the LoginSuccess. Remember the PHP, you need to use the same text because you wanna test it here.

3. Register Activity

register screen

Here is XML code for activity_register.xml:

For registration, it is very simple. You have some EditTexts and Button again.

And for Java code at RegisterActivity.java:

The code here in RegisterActivity is quite similar to the login. Except here, you test ErrorInsert to see if you insert data successfully or not.

4. Main Page Activity

main page screen

Here is XML code for content_main_page.xml:

Actually, you have generated xml files more than one for the Navigation Drawer. But because here I don’t write any code yet so I post only one xml file. Below is the screenshot of the files:

And for Java code at MainPageActivity.java:

again the MainPageActivity is just the generated code. I did not change any.

5. Android Manifest

Here is XML code for activity_startup.xml:

The necessary code here is:

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

It is for asking a permission to connect your app to the Internet.

6. Gradle

And for code at Gradle:

The two lines below are the change. These are my library lines of code.

compile files(‘libs/GenAsync.1.2.jar’)
compile files(‘libs/MD5Simply.jar’)

DOWNLOAD SOURCE CODE

DOWNLOAD

OK, now we reach the end of this tutorial. I hope you like it. Feel free to ask any question to the comment section down below.

And if you wanna connect me and discuss with me in the future, you can join my Facebook Page for free. Our members in the group will be able to help you too. You can follow me as well at KosalGeek Facebook Page.

I will post a full video tutorial in my YouTube Channel Oum Saokosal. Be sure to subscribe to my channel.

Comments

comments