
Pertama buatlah database dengan nama test, dengan nama tabel motor

Untuk mengambil data dari MySQL diperlukan sebuah file PHP yan nantinya akan mengubah data tersebut dalam bentuk JSON. Dengan demikian anda harus membuat file dengan nama test.php kemudian simpan file ke htdoc didalam folder test pada XAMPP anda.
test.php
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 | <? php $ response = array (); // include db connect class mysql_connect("localhost","root",""); mysql_select_db("test"); // get by pendaftaran $ result = mysql_query ("SELECT * FROM motor") or die(mysql_error()); // cek if (mysql_num_rows($result) > 0) { // looping hasil // pendaftaran node $response["data"] = array(); while ($row = mysql_fetch_array($result)) { $pendaftaran = array(); $pendaftaran["motor"] = $row[1]; $pendaftaran["harga"] = $row[2]; // masukan pendaftaran pada $response array_push($response["data"], $pendaftaran); } // sukses $response["success"] = 1; // echo JSON response echo json_encode($response); } else { $response["success"] = 0; $response["message"] = "Tidak ada data yang ditemukan"; echo json_encode($response); } ?> |
Buka Eclipse anda, pada res/layout ubah activity_main.xml seperti berikut. activity_main.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 | <? xml version = "1.0" encoding = "utf-8" ?> android:layout_width = "fill_parent" android:layout_height = "fill_parent" android:orientation = "vertical" > < ListView android:id = "@android:id/list" android:layout_width = "fill_parent" android:layout_height = "wrap_content" android:dividerHeight = "1dp" /> </ LinearLayout > |
list.xml
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 | <? xml version = "1.0" encoding = "utf-8" ?> android:layout_width = "match_parent" android:layout_height = "match_parent" android:orientation = "horizontal" > < LinearLayout android:layout_width = "match_parent" android:layout_height = "wrap_content" android:gravity = "center_vertical" android:orientation = "vertical" > < TextView android:id = "@+id/mb" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_marginTop = "5dp" android:paddingLeft = "5dp" android:paddingTop = "2dp" android:textSize = "16sp" android:textStyle = "bold" /> < TextView android:id = "@+id/hg" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:paddingLeft = "5dp" android:paddingTop = "2dp" android:textSize = "14sp" android:textStyle = "bold" /> </ LinearLayout > </ LinearLayout > |
MainActivity.java
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 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 | package com.codingers; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.http.NameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.ListActivity; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; public class MainActivity extends ListActivity { // Progress Dialog private ProgressDialog pDialog; // buat json object JSONParser jParser = new JSONParser(); ArrayList< HashMap <String, String>> semuaList; String url_semua = ""; // JSON Node private static final String TAG_SUCCESS = "success"; private static final String TAG_DATA = "data"; private static final String TAG_MBL = "motor"; private static final String TAG_HRG = "harga"; // pendaftaran JSONArray JSONArray jmobil = null; String isi; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); url_semua = "http://10.0.2.2/test/test.php"; // Hashmap untuk ListView semuaList = new ArrayList< HashMap <String, String>>(); // Loading products in Background Thread new LoadSemua().execute(); // Get listview ListView lv = getListView(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // jika kode hasil sama dengan 100 if (resultCode == 100) { Intent intent = getIntent(); finish(); startActivity(intent); } } class LoadSemua extends AsyncTask< String , String, String> { /** * sebelum melakukan thread di background maka jalankan progres dialog * */ @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(MainActivity.this); pDialog.setMessage("Mohon tunggu, Loading Data..."); pDialog.setIndeterminate(false); pDialog.setCancelable(false); pDialog.show(); } /** * dapetkan semua produk dari get url di background * */ protected String doInBackground(String... args) { // Buat Parameter List< NameValuePair > params = new ArrayList< NameValuePair >(); // ambil json dari url JSONObject json = jParser.makeHttpRequest(url_semua, "GET", params); // cek logcat untuk response dari json Log.d("Semua : ", json.toString()); try { // cek jika tag success int success = json.getInt(TAG_SUCCESS); if (success == 1) { // data ditemukan jmobil = json.getJSONArray(TAG_DATA); // tampilkan perulangan semua produk for (int i = 0; i < jmobil.length (); i++) { JSONObject c = jmobil .getJSONObject(i); // simpan pada variabel String mb = c .getString(TAG_MBL); String hg = c .getString(TAG_HRG); // buat new hashmap HashMap<String, String> map = new HashMap< String , String>(); // key => value map.put(TAG_MBL, mb); map.put(TAG_HRG, hg); // masukan HashList ke ArrayList semuaList.add(map); } } else { // jika tidak ada data // tutup semua proses sebelumnya } } catch (JSONException e) { e.printStackTrace(); } return null; } protected void onPostExecute(String file_url) { // hentikan progress ketika semua data didapat pDialog.dismiss(); // perbarui screen runOnUiThread(new Runnable() { public void run() { ListAdapter adapter = new SimpleAdapter(MainActivity.this, semuaList, R.layout.list, new String[] { TAG_MBL, TAG_HRG }, new int[] { R.id.mb, R.id.hg }); setListAdapter(adapter); } }); } } } |
JSONParser.java
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 | package com.codingers; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; public class JSONParser { static InputStream is = null; static JSONObject jObj = null; static String json = ""; // constructor public JSONParser() { } // function get json from url // by making HTTP POST or GET mehtod public JSONObject makeHttpRequest(String url, String method, List< NameValuePair > params) { try { if (method == "POST") { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } else if (method == "GET") { // request method is GET DefaultHttpClient httpClient = new DefaultHttpClient(); String paramString = URLEncodedUtils.format(params, "utf-8"); url += "?" + paramString; HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // try parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } // return JSON String return jObj; } } |
1 | < uses-permission android:name = "android.permission.INTERNET" /> |

Setelah dijalankan hasilnya sebagai berikut. selamat mencoba .....
download source code
mau tanya kalau listview menggunakan Imageview gimana ya?
ReplyDeletesiang,mau tanya ko saya kan sudah membuat jsonparser tapi knp defaulthttp nya itu merah semua ya yg berbau http,knp ya ?hannya mas
ReplyDeletemohon arahanny
bantu jawab :
DeleteAyas Fildzah "siang,mau tanya ko saya kan sudah membuat jsonparser tapi knp defaulthttp nya itu merah semua ya yg berbau http,knp ya ?hannya mas
mohon arahanny"
tambahin di gradle app
android {
useLibrary 'org.apache.http.legacy'
}