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 🙂