This example show you how to connect and read data from MySQL database directly from Android. The following steps and code snippet will show you how to do it.
Add the MySQL JDBC driver into your project dependencies. Open the app/build.gradle
file and add the dependency.
...
...
dependencies {
...
...
implementation 'mysql:mysql-connector-java:5.1.49'
}
If you want to connect to MariaDB you can change the JDBC driver dependency using 'org.mariadb.jdbc:mariadb-java-client:1.8.0'
, also update the JDBC url in the code snippet by replacing mysql
with mariadb
.
Next, add internet permission to our application in AndroidManifest.xml
file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.kodejava.android">
<uses-permission android:name="android.permission.INTERNET" />
...
...
</manifest>
Let’s connect, read data from the database and display the information on the screen. In the code snippet we create an AsyncTask
to read the information from the database. In the doInBackground()
method we open a connection to the database, create a PreparedStatement
, execute a query, get a ResultSet
and read the information from it. We pack the data into a Map
and return it.
After the doInBackground()
method finish its execution the onPostExecute()
method will be called. In this method we take the result, the Map
returned by the doInBackground()
method, and set the values into the TextView
components for display.
package org.kodejava.android;
import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private static final String URL = "jdbc:mysql://192.168.0.107:3306/kodejava";
private static final String USER = "kodejava";
private static final String PASSWORD = "kodejava";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new InfoAsyncTask().execute();
}
@SuppressLint("StaticFieldLeak")
public class InfoAsyncTask extends AsyncTask<Void, Void, Map<String, String>> {
@Override
protected Map<String, String> doInBackground(Void... voids) {
Map<String, String> info = new HashMap<>();
try (Connection connection = DriverManager.getConnection(URL, USER, PASSWORD)) {
String sql = "SELECT name, address, phone_number FROM school_info LIMIT 1";
PreparedStatement statement = connection.prepareStatement(sql);
ResultSet resultSet = statement.executeQuery();
if (resultSet.next()) {
info.put("name", resultSet.getString("name"));
info.put("address", resultSet.getString("address"));
info.put("phone_number", resultSet.getString("phone_number"));
}
} catch (Exception e) {
Log.e("InfoAsyncTask", "Error reading school information", e);
}
return info;
}
@Override
protected void onPostExecute(Map<String, String> result) {
if (!result.isEmpty()) {
TextView textViewName = findViewById(R.id.textViewName);
TextView textViewAddress = findViewById(R.id.textViewAddress);
TextView textViewPhoneNumber = findViewById(R.id.textViewPhone);
textViewName.setText(result.get("name"));
textViewAddress.setText(result.get("address"));
textViewPhoneNumber.setText(result.get("phone_number"));
}
}
}
}
- Finally, here is the screenshot of our Android application.
The complete source code can be accesses in our GitHub repository here: android-mysql-example.
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
Salam Rahayu mas Wayan,
Saya Maman.
Mas, bisa bantu lihat kode saya, kenapa ya setiap membuat koneksi ke MySQL selalu saja error:
Projectnya bisa sampean clone di: https://github.com/antilaila/mysql-jdbc-demo
Salam Rayahu Mas Maman,
Baik, saya coba liat code-nya ya mas, nanti saya clone repo-nya.
Trim mas Wayan atas waktu dan bantuannya 🙂
Hola, tengo el mismo error, hay alguna solución?
Halo,
Mas Maman, untuk akses (open connection) ke databasenya jangan dilakukan di main thread, gunakan AsyncTask seperti contoh di artikel diatas. Atau gunakan mekanisme yang lebih baru seperti ExecutorService.
Iya mas wayan, saya pelajari dulu topik tentang AsyncTask dan ExecutorService dulu. Terima kasih banyak informasinya. Tetap sehat dan tetap berkarya mas wayan.
Hello Sir,
I tried your code but got the following message:
‘execute(Params…)’ is deprecated as of API 30: Android 11.0 (R)
‘android.os.AsyncTask’ is deprecated as of API 30: Android 11.0 (R)
Overrides deprecated method in ‘android.os.AsyncTask’ as of API 30: Android 11.0 (R)
I tried to use SDK 30 and getting error:
:app is currently compiled against android-30.
Recommended action: Update this project to use a newer compileSdkVersion
of at least 32, for example 33.
Any suggestion on what I can do?
Thank you in advance.
Hello sir,
I tried your code but I got communication link failure. MySQL server is working properly.
Hi Ks, if your MySQL server is running, can you access it from outside of your computer? Do you have any error stack trace that we can see? If I can see your code I might able to test it.
How to do it using a hosted mysql database?
Hi Hatim, just change the IP address to where you host your database. Did you have any difficulties?
Thank you.
how you get this IP 192.168.0.107, is it possible with 000webhost or godaddy hosting, how this work, which hosting or what u use.
Hi Mayur,
The IP should be the IP address or domain address of your database server. If you have the public IP address of your hosting like 000webhost or godaddy then you can use it.