Thursday, January 26, 2017

Displaying Data On Android (Retrofit 2.0 GET) From Server PHP + MySQL

Continuing the previous post about how to input data from android to server that made using PHP + MySQL, then today i going to create an article that still related with database (PHP and MySQL).

This article will talking about how to displaying data on android from server that made using PHP and MySQL. The server hostinged in localhost.

 
In android I using retrofit 2.0 as the tool that help me to do communicate data between android and server. Because this process just do displaying data, then the method that will used is method GET (Retrofit)

By following this tutorial until the end, you will learn 2 thing. First, you will learn how to create your own server using PHP and MySQL, and the second you will learn how to use retrofit (Method GET).

Also see : How to GET using retrofit 2.0 by paramter (using dummy server from apiary)

Creating Database


Database that uses still same as the previous article that talking about how to insert data from Android to Server (PHP+MySQL). There is no changes or replaced. You can follow the steps how to create the database from this article.

Code In PHP Project


In the php project, there are several php class that uses :
  • Connection.php
  • DisplayJsonFood.php

1. Connection.php

This file used to connecting database that we have created to out php project. Below is the full code of Connection.php :

<?php
/**
* Created by PhpStorm.
* User: putuguna
* Date: 1/24/2017
* Time: 10:13 AM
*/
class Connection{
function getConnection(){
$host = "localhost";
$username = "root";
$password = "";
$dbname = "loginphpandroid";
try{
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $conn;
}catch (PDOException $e){
echo "ERROR CONNECTIONF : " . $e->getMessage();
}
}
}
view raw Connection.php hosted with ❤ by GitHub
2. DisplayJsonFood.php

This file used to displaying datas from database be a json format. Why json format? Becase Android cannot straight access the database, so between php and android communicate by using JSON. Below is the full code of this file :

<?php
/**
* Created by PhpStorm.
* User: putuguna
* Date: 1/25/2017
* Time: 10:33 AM
*/
require_once("../db/Connection.php");
class DisplayJsonFood{
function getAllJsonFood(){
$connection = new Connection();
$conn = $connection->getConnection();
$jsonFood = array();
$status="status";
$message = "message";
try{
$sqlQuery = "SELECT * FROM food";
$getJson = $conn->prepare($sqlQuery);
$getJson->execute();
$result = $getJson->fetchAll(PDO::FETCH_ASSOC);
foreach($result as $data){
array_push($jsonFood,
array('idfood'=>$data['idfood'],
'foodname'=>$data['foodname'],
'foodqty'=>$data['foodqty']));
}
}catch (PDOException $e){
echo "Error while displaying json : " . $e->getMessage();
}
if($sqlQuery){
echo json_encode(array("food"=>$jsonFood,$status=>1,$message=>"Success"));
}else{
echo json_encode(array("food"=>null,$status=>0, $message=>"Failed while displaying data food"));
}
}
}
$json = new DisplayJsonFood();
$json->getAllJsonFood();
the above code will displaying json look like the follows  :

{
"food":[
{
"idfood":"35",
"foodname":"Nasi Goreng",
"foodqty":"3"
},
{
"idfood":"36",
"foodname":"Ayam Bakar",
"foodqty":"2"
},
{
"idfood":"37",
"foodname":"Ayam Bumbu Rica",
"foodqty":"5"
},
{
"idfood":"38",
"foodname":"ramen",
"foodqty":"1"
}
],
"status":1,
"message":"Success"
}
view raw jsonFood.json hosted with ❤ by GitHub
Because the data food is possibility more that one, then on json above, data saved inside array tagline. The array tagline that i meant is []. Inside the [] there is tagline {}. Tagline {} called as object.

Example : If there are four datas in database, then the object inside tagline [] also became four,  so the form look like : [{},{},{},{}]. Please take a look at the following image :



On above image, beside the tagline [] and {}, also there are two attributes, there are status and message.

If the process successful, the the value of attribute status became "1", and the massage became "success". And in the process is failed, the value of attribute status became "0", and the message became "Failed while displaying data".

Code In Android Project


There are several java classes on project android required. These classes look like the follows :
  • FoodModel.java
  • ListFoodModel.java
  • LoggingInterceptor.java
  • ApiService.java
  • ApiClient.java
  • FoodAdapter.java
  • MainActivity.java

1. FoodModel.java

This file created as an object. Inside this file contains method getter and setter. Below is the full code of FoodModel.java :

package com.putuguna.androidphpdisplaydata.models;
import com.google.gson.annotations.SerializedName;
/**
* Created by putuguna on 1/25/2017.
*/
public class FoodModel {
@SerializedName("idfood")
private int idFood;
@SerializedName("foodname")
private String foodName;
@SerializedName("foodqty")
private int foodQty;
public FoodModel() {
}
public FoodModel(int idFood, String foodName, int foodQty) {
this.idFood = idFood;
this.foodName = foodName;
this.foodQty = foodQty;
}
public int getIdFood() {
return idFood;
}
public void setIdFood(int idFood) {
this.idFood = idFood;
}
public String getFoodName() {
return foodName;
}
public void setFoodName(String foodName) {
this.foodName = foodName;
}
public int getFoodQty() {
return foodQty;
}
public void setFoodQty(int foodQty) {
this.foodQty = foodQty;
}
}
view raw FoodModel.java hosted with ❤ by GitHub
2. ListFoodModel.java

Perhaps serveral of you have a questions what the different between FoodModel.java and ListFoodModel.java?

Here, as you can see at the json output, the object located inside array tagline, in order to make a similar form between model in android and the json format, then we create list that encapsule the FoodModel.java

In order to easy understand, please take a look at ListFoodModel.java, here :

package com.putuguna.androidphpdisplaydata.models;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* Created by putuguna on 1/25/2017.
*/
public class ListFoodModel {
@SerializedName("food")
private List<FoodModel> listFoodM;
@SerializedName("status")
private int status;
@SerializedName("message")
private String message;
public ListFoodModel(List<FoodModel> listFoodM, int status, String message) {
this.listFoodM = listFoodM;
this.status = status;
this.message = message;
}
public ListFoodModel() {
}
public List<FoodModel> getListFoodM() {
return listFoodM;
}
public void setListFoodM(List<FoodModel> listFoodM) {
this.listFoodM = listFoodM;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
3. LoggingInterceptor.java

This file used to see the output of the process displaying data. If there is an error, this class file know what the causes of the error. The output will appears on logcat. Below is the full code of this file :


package com.putuguna.androidphpdisplaydata.utils;
import android.util.Log;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
/**
* Created by putuguna on 1/24/2017.
*/
public class LoggingInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
long t1 = System.nanoTime();
String requestLog = String.format("Sending request %s on %s%n%s",
request.url(), chain.connection(), request.headers());
//YLog.d(String.format("Sending request %s on %s%n%s",
// request.url(), chain.connection(), request.headers()));
if (request.method().compareToIgnoreCase("post") == 0) {
requestLog = "\n" + requestLog + "\n" + bodyToString(request);
}
Log.d("TAG", "request" + "\n" + requestLog);
Response response = chain.proceed(request);
long t2 = System.nanoTime();
String responseLog = String.format("Received response for %s in %.1fms%n%s",
response.request().url(), (t2 - t1) / 1e6d, response.headers());
String bodyString = response.body().string();
Log.d("TAG", "response" + "\n" + responseLog + "\n" + bodyString);
return response.newBuilder()
.body(ResponseBody.create(response.body().contentType(), bodyString))
.build();
}
public static String bodyToString(final Request request) {
try {
final Request copy = request.newBuilder().build();
final Buffer buffer = new Buffer();
copy.body().writeTo(buffer);
return buffer.readUtf8();
} catch (final IOException e) {
return "did not work";
}
}
}
4. ApiService.java

This file is an interface. Inside this file contains method GET that used to get data from json. The full code of this file is look like the follows :

package com.putuguna.androidphpdisplaydata.apiservices;
import com.putuguna.androidphpdisplaydata.models.ListFoodModel;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
/**
* Created by putuguna on 1/24/2017.
*/
public interface ApiService {
@GET("food/DisplayJsonFood.php")
Call<ListFoodModel> getAllDataFood();
}
view raw ApiService.java hosted with ❤ by GitHub
5. ApiClient.java

This file contains the target URL that will used. And also this class contains the initialized of retrofit. The following is the full code :

package com.putuguna.androidphpdisplaydata.clients;
import com.putuguna.androidphpdisplaydata.utils.LoggingInterceptor;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by putuguna on 1/24/2017.
*/
public class ApiClient {
public static final String URL = "http://192.168.43.147/AndroidPhpLogin/";
public static Retrofit RETROFIT = null;
public static Retrofit getClient(){
if(RETROFIT==null){
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new LoggingInterceptor())
.build();
RETROFIT = new Retrofit.Builder()
.baseUrl(URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return RETROFIT;
}
}
view raw ApiClient.java hosted with ❤ by GitHub
6. FoodAdapter.java

This file used to set data that got from server to the each textview. The full code is like the follows :

package com.putuguna.androidphpdisplaydata.adapters;
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.putuguna.androidphpdisplaydata.R;
import com.putuguna.androidphpdisplaydata.models.FoodModel;
import java.util.List;
/**
* Created by putuguna on 1/25/2017.
*/
public class FoodAdapter extends RecyclerView.Adapter<FoodAdapter.ViewHolder>{
private List<FoodModel> listFoodModel;
private Context context;
public FoodAdapter(List<FoodModel> listFoodModel, Context context) {
this.listFoodModel = listFoodModel;
this.context = context;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.item_food,parent,false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
FoodModel model = listFoodModel.get(position);
try{
holder.tvFoodName.setText(model.getFoodName());
holder.tvFoodQty.setText(model.getFoodQty()+"");
}catch (Exception e){
e.printStackTrace();
}
}
@Override
public int getItemCount() {
return listFoodModel.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder{
public TextView tvFoodName;
private TextView tvFoodQty;
public ViewHolder(View itemView) {
super(itemView);
tvFoodName = (TextView) itemView.findViewById(R.id.textview_foodname);
tvFoodQty = (TextView) itemView.findViewById(R.id.textview_foodqty);
}
}
}
7. MainActivity.java

MainActivity is the main class that contains all of the process of the above class. The full code of MainActivity is look like the follows :

package com.putuguna.androidphpdisplaydata;
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.putuguna.androidphpdisplaydata.adapters.FoodAdapter;
import com.putuguna.androidphpdisplaydata.apiservices.ApiService;
import com.putuguna.androidphpdisplaydata.clients.ApiClient;
import com.putuguna.androidphpdisplaydata.models.FoodModel;
import com.putuguna.androidphpdisplaydata.models.ListFoodModel;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity {
private Button btnDisplayDatafood;
private RecyclerView recyclerViewFood;
private ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnDisplayDatafood = (Button) findViewById(R.id.button_display_data_food);
recyclerViewFood = (RecyclerView) findViewById(R.id.recyclerview_food);
progressDialog = new ProgressDialog(this);
btnDisplayDatafood.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getAllDataFood();
}
});
}
private void getAllDataFood(){
progressDialog.setTitle("Displaying data");
progressDialog.setMessage("Loading ...");
progressDialog.show();
ApiService apiService = ApiClient.getClient().create(ApiService.class);
Call<ListFoodModel> call = apiService.getAllDataFood();
call.enqueue(new Callback<ListFoodModel>() {
@Override
public void onResponse(Call<ListFoodModel> call, Response<ListFoodModel> response) {
ListFoodModel listFoodModel = response.body();
if(listFoodModel.getStatus()==1){
List<FoodModel> listFood = listFoodModel.getListFoodM();
FoodAdapter foodAdapter = new FoodAdapter(listFood, MainActivity.this);
recyclerViewFood.setLayoutManager(new LinearLayoutManager(MainActivity.this));
recyclerViewFood.setItemAnimator(new DefaultItemAnimator());
recyclerViewFood.setAdapter(foodAdapter);
progressDialog.dismiss();
}else{
Toast.makeText(MainActivity.this, listFoodModel.getMessage(), Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}
@Override
public void onFailure(Call<ListFoodModel> call, Throwable t) {
Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
});
}
}
That's the several steps how to display data on android from database (server made using PHP and MySQL). Hope this article useful. Thank you.

Download the project by clicking the following image


Related Posts

2 komentar

Live dealer casino site review - Lucky Club
Live casino site review. All bonuses and promotions listed. Enjoy free casino games and watch the best live casino slots from the luckyclub top providers.Games: 400+Types of games: Slots, Blackjack, Roulette, Video slotsOther Games: Poker, Ba

Slot Games for Sale by Pragmatic Play
Slot Machines for tenpro Sale by Pragmatic 포커 게임 다운 Play. Game Categories. Slot · 도박사이트 Pragmatic Play · Pragmatic 999betasia Play. Games. 러시안 룰렛 가사 Slot · Provider · Pragmatic Play · Slot


EmoticonEmoticon

:)
:(
hihi
:-)
:D
=D
:-d
;(
;-(
@-)
:o
:>)
(o)
:p
:-?
(p)
:-s
8-)
:-t
:-b
b-(
(y)
x-)
(h)