Hey guys, in this post we are going to learn how to Retrieve Data from MySQL Database in Android. And for this we will be using Volley Library. I have already posted a number of tutorials about Volley, PHP and MySQL. This post is specifically about retrieving data from MySQL Database in Android. So lets begin.
Table of Contents
MySQL Database
So guys this is my database table and I will fetch the data from here.
We already have some rows inserted in the above table. And our task here is to fetch those records in our Android Application. If you want you can get my database from below.
Retrieving Data as JSON from Table
- Here I am using (XAMPP) so for the PHP side create a folder inside htdocs (C:/xampp/htdocs). I created MyApi.
- Inside this folder create a file named Api.php and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | <?php /* * Created by Belal Khan * website: www.simplifiedcoding.net * Retrieve Data From MySQL Database in Android */ //database constants define('DB_HOST', 'localhost'); define('DB_USER', 'root'); define('DB_PASS', 'password'); define('DB_NAME', 'simplifiedcoding'); //connecting to database and getting the connection object $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME); //Checking if any error occured while connecting if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); die(); } //creating a query $stmt = $conn->prepare("SELECT id, title, shortdesc, rating, price, image FROM products;"); //executing the query $stmt->execute(); //binding results to the query $stmt->bind_result($id, $title, $shortdesc, $rating, $price, $image); $products = array(); //traversing through all the result while($stmt->fetch()){ $temp = array(); $temp['id'] = $id; $temp['title'] = $title; $temp['shortdesc'] = $shortdesc; $temp['rating'] = $rating; $temp['price'] = $price; $temp['image'] = $image; array_push($products, $temp); } //displaying the result in json format echo json_encode($products); |
- Now trying opening this PHP file in your browser. You will see the following output.

- Now we will use this URL in our android side to get the above JSON data.
- But remember you cannot use localhost in your URL. You need to find your IP and you can find it using ipconfig command in windows and ifconfig command in linux or mac.
- In my case the URL is: http://192.168.101.1/MyApi/Api.php
Retrieve Data From MySQL Database in Android
Creating a new Android Project
- So lets create a new Android Studio project where we will display the data fetched from MySQL.
- Once your project is created you need to add the dependencies.
Dependencies Required
- We will use
- RecyclerView for creating the Product List that we are getting as JSON.
- Glide to load image from URL.
- Volley to get the JSON data from URL.
Adding Required Dependencies
- Add the following lines inside your app level build.gradle file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) compile 'com.android.support:appcompat-v7:26.+' compile 'com.android.support.constraint:constraint-layout:1.0.2' testCompile 'junit:junit:4.12' //add these for lines compile 'com.android.volley:volley:1.1.0-rc1' compile 'com.android.support:recyclerview-v7:26.0.0-alpha1' compile 'com.github.bumptech.glide:glide:4.2.0' annotationProcessor 'com.github.bumptech.glide:compiler:4.2.0' } |
- Now modify the project level gradle file as shown below.
1 2 3 4 5 6 7 8 9 10 11 | allprojects { repositories { jcenter() //add these two lines here mavenCentral() maven { url 'https://maven.google.com' } } } |
- Now sync your project and you are done.
Creating Interfaces
- First we will create a RecyclerView inside our activity_main.xml.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="net.simplifiedlearning.volleymysqlexample.MainActivity"> <android.support.v7.widget.RecyclerView android:id="@+id/recylcerView" android:layout_width="match_parent" android:layout_height="match_parent" tools:layout_editor_absoluteX="745dp" tools:layout_editor_absoluteY="-51dp" /> </RelativeLayout> |
- Now we will create a new layout resource file named product_list.xml inside the layout folder. This is for our list item.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="8dp"> <ImageView android:id="@+id/imageView" android:layout_width="120dp" android:layout_height="90dp" android:padding="4dp" /> <TextView android:id="@+id/textViewTitle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="5dp" android:layout_toRightOf="@id/imageView" android:text="Apple MacBook Air Core i5 5th Gen - (8 GB/128 GB SSD/Mac OS Sierra)" android:textAppearance="@style/Base.TextAppearance.AppCompat.Small" android:textColor="#000000" /> <TextView android:id="@+id/textViewShortDesc" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/textViewTitle" android:layout_marginLeft="5dp" android:layout_marginTop="5dp" android:layout_toRightOf="@id/imageView" android:text="13.3 Inch, 256 GB" android:textAppearance="@style/Base.TextAppearance.AppCompat.Small" /> <TextView android:id="@+id/textViewRating" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/textViewShortDesc" android:layout_marginLeft="5dp" android:layout_marginTop="5dp" android:layout_toRightOf="@id/imageView" android:background="@color/colorPrimary" android:paddingLeft="15dp" android:paddingRight="15dp" android:text="4.7" android:textAppearance="@style/Base.TextAppearance.AppCompat.Small.Inverse" android:textStyle="bold" /> <TextView android:id="@+id/textViewPrice" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/textViewRating" android:layout_marginLeft="5dp" android:layout_marginTop="5dp" android:layout_toRightOf="@id/imageView" android:text="INR 56990" android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" android:textStyle="bold" /> </RelativeLayout> </LinearLayout> |
- It will create the following output.
Creating Model
- To keep the product we will create a class that will contain all the product attributes. So create a class named Product and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | package net.simplifiedlearning.volleymysqlexample; /** * Created by Belal on 10/18/2017. */ public class Product { private int id; private String title; private String shortdesc; private double rating; private double price; private String image; public Product(int id, String title, String shortdesc, double rating, double price, String image) { this.id = id; this.title = title; this.shortdesc = shortdesc; this.rating = rating; this.price = price; this.image = image; } public int getId() { return id; } public String getTitle() { return title; } public String getShortdesc() { return shortdesc; } public double getRating() { return rating; } public double getPrice() { return price; } public String getImage() { return image; } } |
Creating Product Adapter
- Now for RecyclerView we will create a ProductAdapter.java. I already posted about RecyclerView so you can learn about it in detail from this RecyclerView Tutorial.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | package net.simplifiedlearning.volleymysqlexample; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import java.util.List; /** * Created by Belal on 10/18/2017. */ public class ProductsAdapter extends RecyclerView.Adapter<ProductsAdapter.ProductViewHolder> { private Context mCtx; private List<Product> productList; public ProductsAdapter(Context mCtx, List<Product> productList) { this.mCtx = mCtx; this.productList = productList; } @Override public ProductViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(mCtx); View view = inflater.inflate(R.layout.product_list, null); return new ProductViewHolder(view); } @Override public void onBindViewHolder(ProductViewHolder holder, int position) { Product product = productList.get(position); //loading the image Glide.with(mCtx) .load(product.getImage()) .into(holder.imageView); holder.textViewTitle.setText(product.getTitle()); holder.textViewShortDesc.setText(product.getShortdesc()); holder.textViewRating.setText(String.valueOf(product.getRating())); holder.textViewPrice.setText(String.valueOf(product.getPrice())); } @Override public int getItemCount() { return productList.size(); } class ProductViewHolder extends RecyclerView.ViewHolder { TextView textViewTitle, textViewShortDesc, textViewRating, textViewPrice; ImageView imageView; public ProductViewHolder(View itemView) { super(itemView); textViewTitle = itemView.findViewById(R.id.textViewTitle); textViewShortDesc = itemView.findViewById(R.id.textViewShortDesc); textViewRating = itemView.findViewById(R.id.textViewRating); textViewPrice = itemView.findViewById(R.id.textViewPrice); imageView = itemView.findViewById(R.id.imageView); } } } |
Fetching JSON and Displaying it in RecyclerView
- Now the last step is fetching the JSON response from URL and display it to RecyclerView.
- So come inside MainActivity.java and write the following code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 | package net.simplifiedlearning.volleymysqlexample; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { //this is the JSON Data URL //make sure you are using the correct ip else it will not work private static final String URL_PRODUCTS = "http://192.168.101.1/MyApi/Api.php"; //a list to store all the products List<Product> productList; //the recyclerview RecyclerView recyclerView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //getting the recyclerview from xml recyclerView = findViewById(R.id.recylcerView); recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(new LinearLayoutManager(this)); //initializing the productlist productList = new ArrayList<>(); //this method will fetch and parse json //to display it in recyclerview loadProducts(); } private void loadProducts() { /* * Creating a String Request * The request type is GET defined by first parameter * The URL is defined in the second parameter * Then we have a Response Listener and a Error Listener * In response listener we will get the JSON response as a String * */ StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_PRODUCTS, new Response.Listener<String>() { @Override public void onResponse(String response) { try { //converting the string to json array object JSONArray array = new JSONArray(response); //traversing through all the object for (int i = 0; i < array.length(); i++) { //getting product object from json array JSONObject product = array.getJSONObject(i); //adding the product to product list productList.add(new Product( product.getInt("id"), product.getString("title"), product.getString("shortdesc"), product.getDouble("rating"), product.getDouble("price"), product.getString("image") )); } //creating adapter object and setting it to recyclerview ProductsAdapter adapter = new ProductsAdapter(MainActivity.this, productList); recyclerView.setAdapter(adapter); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }); //adding our stringrequest to queue Volley.newRequestQueue(this).add(stringRequest); } } |
Adding Internet Permission
- Lastly add internet permission in your AndroidManifest.xml file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="net.simplifiedlearning.volleymysqlexample"> <!-- the internet permission --> <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> |
- Now you can run your application.

- Bingo! It is working absolutely fine.
- Now if you want you can download my source code from the below given link.
Retrieve Data from MySQL Database in Android Source Code
So thats all for this tutorial friends. Hope you got the point how to retrieve data from mysql database in android. If you are having any confusions or queries you can leave your comments below. Thank You 🙂

Hi, my name is Belal Khan and I am a Google Developers Expert (GDE) for Android. The passion of teaching made me create this blog. If you are an Android Developer, or you are learning about Android Development, then I can help you a lot with Simplified Coding.
Thank You for your code instruction.It really helps me.
Thanks a lot I’m getting the Result
Error:(1, 0) Cause: com/android/build/gradle/AppPlugin : Unsupported major.minor version 52.0
Open File
this my error please help i open the project to android studio
When I rotate the screen, the data gets reloaded. How to solve that ? Is there any way to implement Loaders as is done in AsyncTask to avoid reloading of data.
you need to save data before goes to “On Create” when you use a save data in OnSavedInstanceState.
///onSaveInstanceState
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(“TagDataToSave”,DataToSave);
}
////OnCreate Code
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState!=null)
{
TagDataToSave=savedInstanceState.getInt(“DataToSave”);
}
else
{
TagDataToSave=10;//To OnCreate on a first time
}
}
can i get a php code for its retreival ???
in this list if i want to perform filter with user data like user will click on a option then that data will goes to server and give a response on this list.plz help me
I will try to make a new video for your query, ASAP.
hi. can you help me to make my ip not static or the users will input the ip of their server ? thank you
Also I want to save all listview data to mysql in one click as like e-commerce cart data plz help
am not getting any error but not displaying the values from the database to the recyclerview but the php file is displaying the data on the browser
Hi man thanks a lot for the tutorial u are awesome.
Would u help me with this one.
I want to write an application that fetches data from database using either Volley or Okhttp.
So what i want to achieve is a multi list view.
1.first list view is for fetching albums with images and text
2.second list view Fetches songs under a particular album–they also contain images and text
3.third screen gives full information of a song –they also contain images and text
Can u do a tutorial on this one. Thanks your help.
Sir Will It is possible to retrieve, update or delete data using Java/Kotlin in Android Studio directly from MSSQl server ?.
No you cannot do it directly.. to do it direcly mysql server should be available in your android device
can i have button along with the each list of listview???
Yes obviously you can put whatever you want
I want to retrieve only the image that too by email as a login profile so, should i use array in php to fetch the image?
Every Thing is ok but data not displaying on Activity please reply
check the ip address in the main activity page
to know whats your ip
type ipconfig in command prompt
Hi,
Thanks for your tutorial. I am getting below error :
org.json.JSONException: Value >>>”+jsonObject.toString(), Toast.LENGTH_LONG).show();
// Log.i(TAG,”Status >>”+jsonObject.getBoolean(“status”));
if (jsonObject.getBoolean(“status”)) {
Toast.makeText(MainActivity.this, “Success occurred..\n” + jsonObject.toString(), Toast.LENGTH_LONG).show();
}else{
Toast.makeText(MainActivity.this, “Else occurred..\n” + jsonObject.toString(), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Please help.
Thanks for the code Sir …
But what if i want to use spinner and select one category and fetch data for specific column according to the selected category?? please answer me sir
Thanks in Advance
Hi sir, i wan ask, how to limit data from mysql in display in AS. for example i wont display data only 5.
thanks
E/dalvikvm: Could not find class ‘android.graphics.drawable.RippleDrawable’, referenced from method android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering
error aa raha he
can ‘t fetch any data but i have all data to retrieve but no error! please help
My image doesn’t seem to load.. I need some help…
Hey, can i get data from online MySQL server(means from my online website database)?
if yes, what link i will give in the code??
you have given ip address of computer, what will be the link i will add in code to access data from database??
Waiting for your reply.
Hey bro, can i know how to fetch specific data from the table? For example, fetch only the current user data.
Hi,
I have this error:
error: class ProductsAdapter is public, should be declared in a file named ProductsAdapter.java
Make sure you rename your Java class from ProductAdapter to ProductsAdapter.
Hi,
Thank’s for your tutorial but I have a problem by fetching the datas.
The products array seems to be created and the temp one also. The php scripts walks through the “while”, but the either the array_push or the last echo don’t show me any result.
Another problem is that I’m in France and the accents like “é” don’t appear in the fields.
May you help me ?
am not getting any error but not displaying the values from the database to the recyclerview but the php file is displaying the data on the browser why is it so
sir i got no error but not display data from the server? can help me
did you solve? i get same error
did you solved this?
Omg same. Could anyone solve it?
Was anyone able to solve this issue?
still not display 🙁
Hi, thank you for the tutorial. Really appreciate it. Can you help me please? I’ve gone through the tutorial and it works fine, but I’d like filter the recyclerview based on store_id, for example: a list of products but only view products by selected store…
Hello Sir,I m new to MySQL actually I want to ask that should my PC be on all the time if I fetch data or upload that to my database.
please I have really learnt a lot from your post and must say its great. now i need some help am developing an app
1. user enter – let say : location and region in different edit text views and submits query
2. result should display all hospitals in that location and region in a list view but a radio button form and check box.
3. from here the user has to select one and press a button to send it.
4. before the activity is sent, it is sending to the select hospitals email address
5. so the app so be able to select to email of the selected hospital and by pressing the submit button an email is sent to the hospital.
can you please guide me to achieve this task thanks
Hi, when I change the phone language to Arabic nothing display just the image, return to the English language show all data.
I can’t find where the error is. Mysql database is utf8_unicode_ci , how can I Retrieve Data and display it in Arabic.
Hai sir,i got no error but not display data from the server?help me
can i get code for update and delete ?
No error but I’m getting no display only black white screen when i run, I’ve also tried it on emulator, pls help.
hi my app doesn’t show anything but I don’t have any mistake, Could you help me?
Had same challenge, Make sure you are on internet and IP address of your API is correct.
Hai, How can i store image as url?
Thanks for the Videos, i have learnt a lot in a short time.
Thank You your all instructions helped me a lot in learning new things.
Hey there it’s a great tutorial thanks for that, but here I stucked an error occurs that is, “E/RecyclerView: No adapter attached; skipping layout” whenever I run my code in an physical device, but when I run my code in emulator it’ s work fine so what is the reason behind that and what is the solution?, Please help!
The Data is being displayed but it says in the logcat that “No Adapter Attached; Skiiping Layout” . I am stuck for days on this one please help me! Thank you…
To start with, I want to say thank you for these amazing Tuts, but my question is:
Suppose I want to view the data from MYSQL (The One I have displayed on my Android Device) offline, how can I modify the code above.
I would also appreciate if you can point me to the actual tut that has this information.
My Main goal is to create an app that synchronises both ways (maintaining a perfectly synched and updated database in MYSQL & SQLite and either of the changed on these database should be seemlessly appended to them both)
I will try to post a tutorial that will teach you how you can manage data persistence.
hi thanks,
If a deceiving person decompile the apk, it will access this get json data URL , which means accessing all json data inside the database. what’s the solution?
Error:Execution failed for task ‘:app:packageAllDebugClassesForMultiDex’.
> java.util.zip.ZipException: duplicate entry: android/support/v4/hardware/display/DisplayManagerCompat.class
when i build the project it is fine but when i run it, it shows this error, please any solution for this
Thanks Belal for help.
It Worked for me after removing some Exception.. ?.
But I Am Facing One Issue With My API.php It’s Running Well On LocalHost But When I Upload It To My Online Server Its Just Run For First Time And Returning The Same Result Again And Again .. PLEASE HELP ME .
Thank You.
Hello, I am having a problem with the function execute on the Api.
Its giving me this message>
Fatal error: Uncaught Error: Call to a member function execute() on bool in C:\xampp\htdocs\MyApi\api.php:23 Stack trace: #0 {main} thrown in C:\xampp\htdocs\MyApi\api.php on line 23
How I can fix this?
hi plz check ur table name. may be it is wrong
E/RecyclerView: No adapter attached; skipping layout
Sir,I m getting this error although I have set the adapter.
Make sure your list contains some values, try checking the size of the list after fetching the data from api.
its still not working , E/RecyclerView: No adapter attached; skipping layout
You should check the video tutorial for detailed explanation. So try this: https://www.youtube.com/playlist?list=PLk7v1Z2rk4hhYrhtRtAX2zVm-FHV38-TQ
how can you select specific item from database and load them in the recyclerview
like select from * tablename where phone number = the user specify in the android app
Me too I want to know how it’s done.
If anyone here can advise us or give us where we can find help
This is awesome Sir , thanks a lot .IT WORKED
sir can i download your project because it does not work for me no data is shown in my app
Good Tutorial.
What if we use CodeIgniter in place of core PHP?
You can use it, its your choice. The android side do not cares about what you are using in the server.
u are a Hero.
thanks a lot
how to display it in a fragment?
incompatible types: int cannot be converted to String
StringRequest stringRequest = new StringRequest(Request.Method.GET, BASE_URL,
the method GET is Int. can solve my error?