Using MySQL Database in Android Apps

The database is one of the most essential parts of any android app these days. User account details, transaction history, news updates, and statistics are just a few examples of the data one may wish to pull, store and analyse.

Android, by default, has inbuilt SQLite support which stores data on the device itself. But, this method has its own limitation — storage, only local static data can be accessed, etc. But, to access the dynamic data at runtime, online database becomes a major requirement.

As the data is growing many android developers and organizations are moving to cloud databases services like — AWS, Google Firebase, Microsoft Azure, etc. This method removes the memory limitation of the device and one can use these services as pay per go. These cloud databases also use MySQL databases internally.

However, these cloud services are the good option for large scale system, sometimes our own hosted MySQL database server can be a good option for small scale system, where data is in hundreds or thousands of number.

In this article, we shall be discussing how android apps can connect to the our own hosted MySQL database?

STEP 1: Ready the Backend API

The first and foremost requirement is the development of API which shall act as a communication bridge between the android app and MySQL Server. The work of the API is to take the request received from the client (Android app in our case), process it, and respond with the desired result. The output result shall be in JSON Array format.

Below is the code of the API in PHP script which shall make a connection to and fetch User Profile details from the Database.

connection.php : Connect to the MySQL Server

fetchUserProfile.php: Fethcing user details from Email ID.

STEP 2: Android App to display the User profile data fetched from the database

  1. Provide Permission to allow our app to access files on the internet.
    AndroidManifest.xml

2. Design Layout interface
profile_activity.xml

3. Downloading and Parsing JSON Data

The main point to focus AsyncBackground worker class that query the Web API file (fetchUserprofile.php) and process the response received in JSON Array Format.

FetchUserProfile.java :

Conclusion

Many cloud database services are available with advanced features also internally using MySQL databases , sometimes NoSQL databases. It is more cost effective and appropriate to host your own MySQL databases if the applications hosted does not cater much data or in other words, it is a small or medium scale application.

Source Code

I have implemented a library management system (both website and Android App) accessing the same database hosted on MySQL server.

Web API Github link :

https://github.com/sahilkalra29/LibraryManagementSystem/tree/master/app

Android App Github link :

https://github.com/sahilkalra29/LibraryManagementSystemAndroidApp

Following myself