Membuat RecyclerView di Android Dan Menampilkan Data dari MySQL - Hai sobat blogcahti, sudah sekian lama saya baru update post lagi dikarenakan kesibukan kuliah membuat saya malas buka blog untuk membuat artikel baru. Tutorial yang saya bagikan kali ini cukup berbeda yaitu mengenai pemrogaman android yang berhubungan dengan tugas akhir kuliah. Tujuan tutorial ini yaitu mengambil data JSON yang telah diparsing dari database MYSQL dengan memanfaatkan library Retrofit. Kemudian dataset akan ditampilkan pada RecyclerView dalam bentuk list items.
Apa itu RecyclerView Android
Saya akan berikan sedikit penjelasan mengenai RecyclerView sebelum kita memulai membuat program. Singkatnya RecylerView adalah sebuah widget yang berfungsi untuk menampilkan dataset. Sebelum adanya widget RecyclerView, kita menggunakan ListView untuk menampilkan dataset. Kekurangan yang ada pada ListView dalam menghandle data yang besar dan dirasa kurang efisien menjadi alasan lahirnya RecyclerView, dimana dapat menampung dataset dalam jumlah besar.Oke, itu sedikit penjelasan singkat RecylerView langsung saja kita praktekan dengan membuat program.
Langkah Membuat RecyclerView
Sebelum membuat project android, terlebih dahulu membuat database dan file .php untuk koneksi ke database.Membuat Database Mysql
Pertama, buat database dengan nama "location".Kemudian buat table dengan nama "location".
Buat struktur tabel dengan query :
CREATE TABLE `location` (
`id` int(11) NOT NULL,
`name` varchar(30) NOT NULL,
`lat` varchar(30) NOT NULL,
`lng` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
Insert value ke tabel dengan query :
INSERT INTO `location` (`id`, `name`, `lat`, `lng`) VALUES
(1, 'Universitas Amikom Yogyakarta', '-7.760508', '110.408542'),
(2, 'Universitas Negeri Yogyakarta', '-7.774721', '110.386242'),
(3, 'Universitas Gajah Mada', '-7.771374', '110.377472');
Jika tidak ada error lanjut ke tahap berikutnya.
Membuat File .php Koneksi Database
Buat direktori baru pada folder htdocs dengan nama "location" untuk menyimpan file php. Disini kita akan membuat dua file php yakni untuk koneksi ke database dan menampilkan field dari tabel.Buat file connect.php dan getlocation.php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
define('hostname','localhost'); | |
define('username', 'root'); | |
define('password', ''); | |
define('database', 'location'); | |
$conn = mysqli_connect(hostname, username, password, database) or die('Unable to connect'); | |
?> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require_once 'connect.php'; | |
$type = $_GET['item_type']; | |
if ($type == 'location') { | |
$query = "SELECT * FROM location"; | |
$result = mysqli_query($conn, $query); | |
$response = array(); | |
while( $row = mysqli_fetch_assoc($result) ){ | |
array_push($response, | |
array( | |
'id'=>$row['id'], | |
'name'=>$row['name'], | |
'lat'=>$row['lat'], | |
'lng'=>$row['lng']) | |
); | |
} | |
echo json_encode($response); // enchoding kedalam JSON dari array | |
} | |
mysqli_close($conn); // menutup koneksi mysql | |
?> |
Setelah itu coba cek apakah json sudah bisa tampil dengan cara memasukan url localhost/recyclerview/getcontact.php?item_type=tb_recylerview
Maka hasilnya akan seperti ini :
[{"id":"1","name":"Universitas Amikom Yogyakarta","lat":"-7.760508","lng":"110.408542"},{"id":"2","name":"Universitas Negeri Yogyakrta","lat":"-7.774721","lng":"110.386242"},{"id":"3","name":"Universitas Gajah Mada","lat":"-7.771374","lng":"110.377472"}]
Tahap pembuatan project android.
Buka Android Studio, New > Project > Empty Activity dan beri nama RecylerView.Tambahkan depedencies pada build.gradle (Module:app) seperti berikut :
//add these for lines
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.2.0'
implementation "androidx.recyclerview:recyclerview:1.1.0"
// For control over item selection of both touch and mouse driven selection
implementation "androidx.recyclerview:recyclerview-selection:1.1.0-beta01"
Kemudian Sync project. Ingat! Saya menggunakan versi androidx, kalian bisa menyesuaikannya.
Ubah activity_main.xml seperti berikut :
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="utf-8"?> | |
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout | |
xmlns:android="http://schemas.android.com/apk/res/android" | |
xmlns:tools="http://schemas.android.com/tools" | |
tools:context="com.blogcahti.recyclerview.MainActivity" | |
android:id="@+id/simpleSwipeRefreshLayout" | |
android:layout_width="match_parent" | |
android:layout_height="match_parent"> | |
<RelativeLayout | |
android:layout_width="match_parent" | |
android:layout_height="match_parent"> | |
<ProgressBar | |
android:id="@+id/prograss" | |
android:layout_centerInParent="true" | |
android:layout_width="wrap_content" | |
android:layout_height="wrap_content" /> | |
<androidx.recyclerview.widget.RecyclerView | |
android:id="@+id/recyclerView" | |
android:layout_width="match_parent" | |
android:layout_height="match_parent"/> | |
<!--<Button | |
android:id="@+id/btnMap" | |
android:layout_width="match_parent" | |
android:layout_height="wrap_content" | |
android:layout_alignParentBottom="true" | |
android:background="#2196F3" | |
android:text="Maps" | |
android:onClick="openMap" | |
android:textAppearance="@style/TextAppearance.AppCompat.Body2" | |
android:textColor="#FFFFFF" | |
android:textSize="18sp" />--> | |
</RelativeLayout> | |
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="utf-8"?> | |
<RelativeLayout | |
xmlns:android="http://schemas.android.com/apk/res/android" | |
android:layout_width="match_parent" | |
android:orientation="vertical" | |
android:layout_height="wrap_content"> | |
<LinearLayout | |
android:layout_width="match_parent" | |
android:orientation="vertical" | |
android:layout_height="wrap_content"> | |
<TextView | |
android:paddingTop="10dp" | |
android:paddingLeft="15dp" | |
android:paddingRight="15dp" | |
android:textSize="20sp" | |
android:textColor="#111" | |
android:id="@+id/name" | |
android:text="Name" | |
android:layout_width="match_parent" | |
android:layout_height="wrap_content" /> | |
<TextView | |
android:paddingTop="5dp" | |
android:paddingBottom="10dp" | |
android:paddingLeft="15dp" | |
android:paddingRight="15dp" | |
android:id="@+id/lat" | |
android:text="Jarak" | |
android:layout_width="match_parent" | |
android:layout_height="wrap_content" /> | |
<TextView | |
android:paddingTop="5dp" | |
android:paddingBottom="10dp" | |
android:paddingLeft="15dp" | |
android:paddingRight="15dp" | |
android:id="@+id/lng" | |
android:text="Jarak" | |
android:layout_width="match_parent" | |
android:layout_height="wrap_content" /> | |
<View | |
android:background="#bfbfbf" | |
android:layout_width="match_parent" | |
android:layout_height="0.1dp"/> | |
</LinearLayout> | |
</RelativeLayout> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.blogcahti.recyclerview; | |
import android.content.Context; | |
import android.view.LayoutInflater; | |
import android.view.View; | |
import android.view.ViewGroup; | |
import android.widget.TextView; | |
import androidx.recyclerview.widget.RecyclerView; | |
import java.util.List; | |
public class Adapter extends RecyclerView.Adapter<Adapter.MyViewHolder> { | |
private List<Location> location; | |
private Context context; | |
public Adapter(List<Location> location, Context context) { | |
this.location = location; | |
this.context = context; | |
} | |
@Override | |
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { | |
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false); | |
return new MyViewHolder(view); | |
} | |
@Override | |
public void onBindViewHolder(final MyViewHolder holder, final int position) { | |
// Get position of MyViewHolder class | |
holder.name.setText(location.get(position).getName()); | |
holder.lat.setText(location.get(position).getLat()); | |
holder.lng.setText(location.get(position).getLng()); | |
// Set onclick to specific ID ViewHolder on detail_activity.xml | |
// Onclick recycle view | |
/*holder.name.setOnClickListener(new View.OnClickListener() { | |
@Override | |
public void onClick(View view) { | |
Intent intent = new Intent(view.getContext(), DetailBengkel.class); | |
// Initialize to bind data for detail_activity | |
intent.putExtra("name", bengkel.get(position).getName()); | |
intent.putExtra("lat", bengkel.get(position).getLat()); | |
intent.putExtra("lng", bengkel.get(position).getLng()); | |
context.startActivity(intent); | |
} | |
});*/ | |
} | |
@Override | |
public int getItemCount() { | |
return location.size(); | |
} | |
// This ViewHolder of RecycleView | |
public static class MyViewHolder extends RecyclerView.ViewHolder{ | |
TextView name,lat,lng; | |
public MyViewHolder(View itemView) { | |
super(itemView); | |
// Find ID of layout | |
name = itemView.findViewById(R.id.name); | |
lat = itemView.findViewById(R.id.lat); | |
lng = itemView.findViewById(R.id.lng); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.blogcahti.recyclerview; | |
import java.util.List; | |
import retrofit2.Call; | |
import retrofit2.http.GET; | |
import retrofit2.http.Query; | |
public interface ApiInterface { | |
@GET("getlocation.php") | |
Call<List<Location>> getLocation( | |
@Query("item_type") String item_type, | |
@Query("key") String keyword | |
); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.blogcahti.recyclerview; | |
import android.os.Bundle; | |
import android.view.View; | |
import android.widget.ProgressBar; | |
import android.widget.Toast; | |
import androidx.appcompat.app.AppCompatActivity; | |
import androidx.recyclerview.widget.LinearLayoutManager; | |
import androidx.recyclerview.widget.RecyclerView; | |
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; | |
import java.util.List; | |
import retrofit2.Call; | |
import retrofit2.Callback; | |
import retrofit2.Response; | |
public class MainActivity extends AppCompatActivity { | |
private RecyclerView recyclerView; | |
private RecyclerView.LayoutManager layoutManager; | |
public static List<Location> location; | |
private Adapter adapter; | |
private ApiInterface apiInterface; | |
ProgressBar progressBar; | |
public static String lat, lng, name; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
// get the reference of RecyclerView | |
progressBar = findViewById(R.id.prograss); | |
recyclerView = findViewById(R.id.recyclerView); | |
layoutManager = new LinearLayoutManager(this); | |
recyclerView.setLayoutManager(layoutManager); | |
recyclerView.setHasFixedSize(true); | |
// Call table on database | |
getJson("location", ""); | |
/*menambah warna pada SwipeRefreshLayout*/ | |
final SwipeRefreshLayout dorefresh = (SwipeRefreshLayout)findViewById(R.id.simpleSwipeRefreshLayout); | |
dorefresh.setColorSchemeResources(android.R.color.holo_blue_bright, | |
android.R.color.holo_green_light, | |
android.R.color.holo_orange_light, | |
android.R.color.holo_red_light); | |
/*event ketika widget dijalankan*/ | |
dorefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener(){ | |
@Override | |
public void onRefresh() { | |
refreshItem(); | |
} | |
void refreshItem() { | |
getJson("location", ""); | |
onItemLoad(); | |
} | |
void onItemLoad() { | |
dorefresh.setRefreshing(false); | |
} | |
}); | |
// btnMap = findViewById(R.id.btnMap); | |
// btnMap.setOnClickListener(MainActivity.this); | |
} | |
/*private void openMap() { | |
Intent intent = new Intent(MainActivity.this, maps.class); | |
startActivity(intent); | |
}*/ | |
public void getJson(String type, String key){ | |
apiInterface = ApiClient.getApiClient().create(ApiInterface.class); | |
Call<List<Location>> call = apiInterface.getLocation(type, key); | |
call.enqueue(new Callback<List<Location>>() { | |
@Override | |
public void onResponse(Call<List<Location>> call, Response<List<Location>> response) { | |
progressBar.setVisibility(View.GONE); | |
location = response.body(); | |
adapter = new Adapter(location, MainActivity.this); | |
recyclerView.setAdapter(adapter); | |
adapter.notifyDataSetChanged(); | |
/*for(Bengkel data : bengkel) { | |
Log.d("Nama", Double.parseDouble(data.getLat()) +","+ data.getLng()); | |
}*/ | |
} | |
@Override | |
public void onFailure(Call<List<Location>> call, Throwable t) { | |
progressBar.setVisibility(View.GONE); | |
Toast.makeText(MainActivity.this, "Error\n"+t.toString(), Toast.LENGTH_LONG).show(); | |
} | |
}); | |
} | |
/*@Override | |
public void onClick(View v) { | |
openMap(); | |
}*/ | |
} |
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Terakhir, Run App menggunakan emulator atau device yang tersambung USB. Terlebih dahulu aktifkan USB debugging di device android. Note : Ganti IP address di ApiClient.java dengan IP local komputer
Apabila terjadi masalah pada saat menjalankan aplikasi dengan error "java.io.IOException: Cleartext HTTP traffic to * not permitted" buka AndroidManifest.xml lalu tambahkan :
<application android:usescleartexttraffic="true" application=""></application>
Project source : GITHUB
Sekian tutorial tentang Cara Membuat RecyclerView di Android dengan Mysql. Jika ada yang ingin ditanyakan, silahkan berkomentar.
Terimakasih telah mengunjungi blogcahti, semoga bermanfaat.
Cara Membuat RecyclerView di Android Dan Menampilkan Data dari MySQL
4/
5
Oleh
Blogcahti