Kemudian kita juga memanfaatkan JSON.Net untuk mengambil data JSONnya. Hal yang perlu disiapkan adalah kita memiliki sebuah tabel database dengan format sebagai berikut :
Tabel cardview
CREATE TABLE `cardview` ( `id` int(11) NOT NULL, `foto` varchar(100) NOT NULL, `judul` varchar(40) NOT NULL, `keterangan` varchar(100) NOT NULL, `detail_artikel` text NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
Kemudian masukan data ke dalam tabel tersebut
INSERT INTO `cardview` (`id`, `foto`, `judul`, `keterangan`, `detail_artikel`) VALUES (1, 'https://websiteanda.com/demo/webservices/image/foto1.jpg', 'Terlahir Kembali', 'Film inspiratif sesion 2017 abad ini', 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.'), (2, 'https://websiteanda.com/demo/webservices/image/foto2.jpg', 'Sang Pencerah', 'Sejarah perjuangan KH. Ahmad Dahlan membangun generasi pencerah', 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.'), (3, 'https://websiteanda.com/demo/webservices/image/foto3.jpg', 'Kisah Inspiratif', 'Kisah-kisah inspiratif kehidupan pada abad ini ', 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.'), (4, 'https://websiteanda.com/demo/webservices/image/foto4.jpg', 'Catatan Hati Seorang Pengusaha', 'Dunia wirausaha yang berkembang pesat pada tahun 2017 ', 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.'), (5, 'https://websiteanda.com/demo/webservices/image/foto5.jpg', 'Motivasi Iman', 'Adakalanya hidup ini perlu asupan rohani kehidupan ', 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.');
Kemudian Buatlah sebuah file php dengan nama koneksi.php seperti berikut
<?php $server = "localhost"; // sesuaikan alamat server anda $user = "nama_user"; // sesuaikan user web server anda $password = "password_db"; // sesuaikan password web server anda $database = "nama_database"; // sesuaikan database web server anda $connect = mysql_connect($server, $user, $password) or die ("Koneksi gagal!"); mysql_select_db($database) or die ("Database belum siap!"); ?>
Kita juga membuat sebuah file .php dengan nama json.php untuk menghasilkan data JSON dengan kode seperti ini
<?php header('content-type: application/json'); include "koneksi.php"; $query = "SELECT * from cardview "; $result = mysql_query($query) or die(mysql_error()); $arr = array(); while ($row = mysql_fetch_assoc($result)) { $temp = array( "id" => $row["id"], "foto" => $row["foto"], "judul" => $row["judul"], "keterangan" => $row["keterangan"], "detail_artikel" => $row["detail_artikel"] ); array_push($arr, $temp); } $data = json_encode($arr); echo $data; ?>
Data JSON sudah siap, sekarang kita membuat sebuah project Xamarin Androidnya, kita buat project dengan nama ListViewImageJSON
Langkah 1
Kita buka file Main.axml lalu kita tambahkan sebuah tool ListView kedalamnya sehingga code Main.axml menjadi seperti ini.
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> <ProgressBar android:id="@+id/progressBar" style="@android:style/Widget.DeviceDefault.ProgressBar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:visibility="gone" /> <ListView android:id="@+id/dataList" android:layout_width="fill_parent" android:layout_height="wrap_content" android:cacheColorHint="#00000000" android:dividerHeight="1dp" /> </FrameLayout>
Langkah 2
Untuk mengisi data pada ListView kita buat sebuah tempat yang akan menampung data dari JSON tersebut , kita membuat dengan cara pada folder layout -> klik kanan add new file buat sebuah layout baru dengan nama ContentParse.axml dengan code sebagai berikut
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:minHeight="50dp" android:orientation="horizontal"> <ImageView android:id="@+id/Foto" android:layout_width="70dp" android:layout_height="70dp" android:paddingLeft="10dp" android:layout_alignParentLeft="true" android:layout_centerVertical="true" android:src="@drawable/Placeholder" /> <TextView android:id="@+id/Judul" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@id/Foto" android:lineSpacingExtra="3dp" android:paddingLeft="10dp" android:paddingTop="5dp" android:textColor="#ffffff" android:text="Judul" android:textStyle="bold" android:typeface="sans" /> <TextView android:id="@+id/Keterangan" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/Title" android:layout_toRightOf="@id/Foto" android:paddingLeft="10dp" android:paddingTop="5dp" android:text="Keterangan" android:textColor="#fff" android:textSize="12sp" android:layout_marginTop="21.5dp" /> <TextView android:id="@+id/Detail" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/Title" android:layout_toRightOf="@id/Foto" android:paddingLeft="10dp" android:paddingTop="5dp" android:text="Detail" android:textColor="#fff" android:textSize="10sp" android:layout_marginTop="55.5dp" android:maxLength="100" /> </RelativeLayout>
Pada kode diatas kita menambahkan 1 buah imageview dan 3 buah textview untuk menampung data sql yaitu foto, judul, keterangan dan detail_artikel.
Langkah 3
Kita buat sebuah layout kembali dengan nama DetailsAcitivity.axml dengan code sebagai berikut
android:layout_height="match_parent"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <ImageView android:id="@+id/FeaturedFoto" android:layout_width="match_parent" android:layout_height="200dp" android:src="@drawable/Placeholder" android:scaleType="centerCrop" /> <TextView android:id="@+id/Judul" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ellipsize="end" android:lineSpacingExtra="3dp" android:maxLines="2" android:padding="5dp" android:text="Title" android:textAppearance="@android:style/TextAppearance.DeviceDefault.Large" android:textColor="#fff" android:textStyle="bold" /> <TextView android:id="@+id/Keterangan" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="5dp" android:text="desc" android:textAppearance="@android:style/TextAppearance.DeviceDefault" android:textColor="#fff" /> <TextView android:text="detail" android:textAppearance="?android:attr/textAppearanceSmall" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/Detail" android:padding="5dp" /> </LinearLayout> </ScrollView>
Layout ini berfungsi sebagai tempat tampilnya data detail ketika listview di Klik.
Langkah 4
Buatlah sebuah Class baru dengan nama Galeri.cs masukan code sebagai berikut
using System; using System.Collections.Generic; namespace ListViewImageJSON { public class Galeri { public Galeri() { } public int id { get; set; } public string judul { get; set; } public string keterangan { get; set; } public string detail_artikel { get; set; } public string foto { get; set; } } }
Kita buat variable-variable yang akan menampung data json yaitu id,foto,judul,keterangan dan detail_artikel
Langkah 5
Jangan lupa untuk menginstal Komponen UrlImageViewerHelper dan Json.NET pada Component project ini, dapat dilakukan dengan cara pada folder Component -> Klik Kanan -> Get More Components -> Cari JSON.Net lalu install, instal juga UrlImageViewrHelper nya.
Langkah 6
Buatlah sebuah class Adapter dengan nama CustomListAdapter.cs dengan code sebagai berikut
using System; using Android.Widget; using Android.App; using System.Collections.Generic; using Android.Views; using Android.Media; using System.Net; using System.Threading.Tasks; using System.IO; using Android.Graphics; namespace ListViewImageJSON { public class CustomListAdapter : BaseAdapter<Galeri> { public CustomListAdapter() { } Activity context; List<Galeri> list; public CustomListAdapter(Activity _context, List<Galeri> _list):base() { this.context = _context; this.list = _list; } public override int Count { get { return list.Count; } } public override long GetItemId(int position) { return position; } public override Galeri this[int index] { get { return list[index]; } } public override View GetView(int position, View convertView, ViewGroup parent) { View view = convertView; // re-use an existing view, if one is available // otherwise create a new one if (view == null) view = context.LayoutInflater.Inflate(Resource.Layout.ContentParse, parent, false); Galeri item = this[position]; view.FindViewById<TextView>(Resource.Id.Judul).Text = item.judul; view.FindViewById<TextView>(Resource.Id.Keterangan).Text = item.keterangan; view.FindViewById<TextView>(Resource.Id.Detail).Text = item.detail_artikel; using (var imageView = view.FindViewById<ImageView>(Resource.Id.Foto)) { string url = Android.Text.Html.FromHtml(item.foto).ToString(); //Download and display image Koush.UrlImageViewHelper.SetUrlDrawable(imageView, url, Resource.Drawable.Placeholder); } return view; } } }
Adapter ini berguna sebagai tempat bank data JSON yang dapat kita tampilkan ke dalam layout yang sudah di atur pada Activity.
Langkah 7
Buka file MainActivity.cs dan modifikasi codenya menjadi seperti ini
using System; using Android.App; using Android.Content; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; using System.Net; using System.IO; using Newtonsoft.Json; using System.Threading.Tasks; using System.Linq; using System.Collections.Generic; namespace ListViewImageJSON { [Activity(Label = "ListViewImageJSON", MainLauncher = true)] public class MainActivity : Activity { ListView DaftarGaleri; ProgressBar progress; private List<Galeri> itemGaleri; private Uri BaseUri = new Uri("https://namawebanda.com/demo/webservices/json.php?"); protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); DaftarGaleri = FindViewById<ListView>(Resource.Id.dataList); itemGaleri = new List<Galeri>(); var webClient = new WebClient(); webClient.DownloadStringAsync(BaseUri); progress = FindViewById<ProgressBar>(Resource.Id.progressBar); //Showing loading progressbar progress.Visibility = ViewStates.Visible; webClient.DownloadStringCompleted += WebClient_DownloadStringCompleted; } private void WebClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { RunOnUiThread(() => { itemGaleri = JsonConvert.DeserializeObject<List<Galeri>>(e.Result); CustomListAdapter adapter = new CustomListAdapter(this, itemGaleri); DaftarGaleri.Adapter = adapter; progress.Visibility = ViewStates.Gone; DaftarGaleri.ItemClick += DaftarGaleri_ItemClick; } ); } void DaftarGaleri_ItemClick(object sender, AdapterView.ItemClickEventArgs e) { Galeri select = itemGaleri.ElementAt(e.Position); //Toast.MakeText(this, select, ToastLength.Long).Show(); //Passing object form one activity to other Intent i = new Intent(Application.Context, typeof(DetailGaleriActivity)); i.PutExtra("item", JsonConvert.SerializeObject(select)); StartActivity(i); } } }
Sesuaikan url alamat pemanggilan JSONnya sesuai website anda
private Uri BaseUri = new Uri("https://namawebanda.com/demo/webservices/json.php?");
Kemudian kita buat fungsi jika listview di Klik
void DaftarGaleri_ItemClick(object sender, AdapterView.ItemClickEventArgs e) { Galeri select = itemGaleri.ElementAt(e.Position); //Toast.MakeText(this, select, ToastLength.Long).Show(); //Passing object form one activity to other Intent i = new Intent(Application.Context, typeof(DetailGaleriActivity)); i.PutExtra("item", JsonConvert.SerializeObject(select)); StartActivity(i); }
Kita menggunakan PutExtra untuk mengambil data pada MainActivity.cs agar dapat ditampilkan pada DetailGaleryActiviy.cs
Langkah 8
Buatlah sebuah activity baru dengan nama DetailGaleryActivity.cs kemudian kita masukan code seperti ini
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Newtonsoft.Json; using Android.Text; namespace ListViewImageJSON { [Activity(Label = "DetailGaleriActivity")] public class DetailGaleriActivity : Activity { protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Create your application here SetContentView(Resource.Layout.DetailsActivity); ActionBar.SetDisplayHomeAsUpEnabled(true); Galeri items = JsonConvert.DeserializeObject<Galeri>(Intent.GetStringExtra("item")); FindViewById<TextView>(Resource.Id.Judul).Text = Html.FromHtml(items.judul).ToString(); FindViewById<TextView>(Resource.Id.Keterangan).Text = Html.FromHtml(items.keterangan).ToString(); FindViewById<TextView>(Resource.Id.Detail).Text = Html.FromHtml(items.detail_artikel).ToString(); ImageView imageView = FindViewById<ImageView>(Resource.Id.FeaturedFoto); //Download and display image Koush.UrlImageViewHelper.SetUrlDrawable(imageView, Html.FromHtml(items.foto).ToString(), Resource.Drawable.Placeholder); } public override bool OnOptionsItemSelected(IMenuItem item) { switch (item.ItemId) { case Android.Resource.Id.Home: Finish(); break; } return true; } } }
Activity ini adalah activity yang akan menampilkan data detail jika setiap listview diklik.
Demikianlah tutorial singkat ini saya buat.
Terimakasih
Salam,
Ipung Purwono
No comments:
Post a Comment
Mohon melakukan komentar dengan bahasa yang mudah dipahami, santun dan dengan bahasa yang baik.