Posting kali ini, saya akan membagikan tutorial cara membuat pencarian data di listview dengan menggunakan searchview. Pada postingan sebelumnya kita telah membahas tutorial Menampilkan Gambar dari Server Localhost dengan Library Picasso pada Eclipse Android, caranya sama hanya pada postingan ini kita akan melakukan pencarian yang datanya berisi gambar dari server.
Penasaran kan? Untuk memulai membuat aplikasi ini, terlebih dahulu anda harus mengikuti tutorial Menampilkan Gambar dari Server Locahost Database MySQL pada Listview Android yang akan kita jadikan kelanjutan dari tutorial ini. Baiklah, jika projectnya sudah ada, maka ikut aja langkah-langkah di bawah ini.
Pada folder src/namapackage di file CustomAdapter.java ubah koding seperti di bawah ini.Penasaran kan? Untuk memulai membuat aplikasi ini, terlebih dahulu anda harus mengikuti tutorial Menampilkan Gambar dari Server Locahost Database MySQL pada Listview Android yang akan kita jadikan kelanjutan dari tutorial ini. Baiklah, jika projectnya sudah ada, maka ikut aja langkah-langkah di bawah ini.
CustomAdapter.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 | package com.codingers; import java.util.ArrayList; import com.squareup.picasso.Picasso; import android.app.Activity; import android.content.Context; import android.content.res.Resources; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Filter; import android.widget.Filterable; import android.widget.ImageView; import android.widget.TextView; public class CustomAdapter extends BaseAdapter implements Filterable { Context context; ArrayList< Industry > industrlist; ArrayList< Industry > mStringFilterList; ValueFilter valueFilter; CustomAdapter(Context context, ArrayList< Industry > industrlist) { this.context = context; this.industrlist = industrlist; mStringFilterList = industrlist; } @Override public int getCount() { return industrlist.size(); } @Override public Object getItem(int position) { return industrlist.get(position); } @Override public long getItemId(int position) { return industrlist.indexOf(getItem(position)); } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater mInflater = (LayoutInflater) context .getSystemService(Activity.LAYOUT_INFLATER_SERVICE); View vi = convertView; if (convertView == null) // convertView = mInflater.inflate(R.layout.list_item, null); vi = mInflater.inflate(R.layout.list_item, null); TextView id = (TextView) vi.findViewById(R.id.id); TextView nama = (TextView) vi.findViewById(R.id.name); TextView harga = (TextView) vi.findViewById(R.id.harga); ImageView gambar = (ImageView) vi.findViewById(R.id.gambar); Industry industr = industrlist.get(position); id.setText(industr.getPID()); nama.setText(industr.getName()); harga.setText(industr.getHrg()); Picasso.with(context).load(industr.getImg()).into(gambar); return vi; } @Override public Filter getFilter() { if (valueFilter == null) { valueFilter = new ValueFilter(); } return valueFilter; } private class ValueFilter extends Filter { @Override protected FilterResults performFiltering(CharSequence constraint) { FilterResults results = new FilterResults(); if (constraint != null && constraint.length() > 0) { ArrayList< Industry > filterList = new ArrayList< Industry >(); for (int i = 0; i < mStringFilterList.size (); i++) { if ((mStringFilterList.get(i).getName().toUpperCase()) .contains(constraint.toString().toUpperCase())) { Industry industr = new Industry(mStringFilterList .get(i).getPID(), mStringFilterList.get(i) .getName(), mStringFilterList.get(i).getHrg(), mStringFilterList.get(i).getImg()); filterList.add(industr); } } results.count = filterList .size(); results.values = filterList ; } else { results.count = mStringFilterList .size(); results.values = mStringFilterList ; } return results; } @Override protected void publishResults(CharSequence constraint, FilterResults results) { industrlist = (ArrayList<Industry>) results.values; notifyDataSetChanged(); } } } |
Industry.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 | package com.codingers; public class Industry { String pid, name, harga, img; Industry(String pid, String name, String harga, String img) { this.pid = pid; this.name = name; this.harga = harga; this.img = img; } public String getImg() { return img; } public void setImg(String img) { this.img = img; } public String getHrg() { return harga; } public void setHrg(String harga) { this.harga = harga; } public String getPID() { return pid; } public void setPID(String pid) { this.pid = pid; } public String getName() { return name; } public void setName(String name) { this.name = name; } } |
JSONParserGambar.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 | package com.codingers; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; public class JSONParserGambar { static InputStream is = null; static JSONObject jObj = null; static String json = ""; // constructor public JSONParserGambar() { } public JSONObject AmbilJson(String url) { // Making HTTP request try { // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); HttpResponse httpResponse = httpClient.execute(httpPost); 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; } } |
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 | package com.codingers; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.annotation.SuppressLint; import android.app.ActionBar; import android.app.Activity; import android.app.SearchManager; import android.content.Context; import android.content.res.TypedArray; import android.os.Bundle; import android.os.StrictMode; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.ListView; import android.widget.SearchView; public class MainActivity extends Activity implements SearchView.OnQueryTextListener { private static final String TAG_SUCCESS = "success"; private static final String TAG_USER = "produk"; private static final String TAG_ID = "pid"; private static final String TAG_NAME = "nama"; private static final String TAG_HRG = "hrg"; private static final String TAG_IMG = "gambar"; ListView lv; String[] country_names, iso_codes; TypedArray country_flags; ArrayList< Industry > induslist; CustomAdapter adapter; SearchView searchView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder() .permitAll().build(); StrictMode.setThreadPolicy(policy); lv = (ListView) findViewById(R.id.list_view); induslist = new ArrayList< Industry >(); String url_load = "http://10.0.2.2/test/semua.php"; JSONParserGambar jParser = new JSONParserGambar(); JSONObject json = jParser.AmbilJson(url_load); // 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) { JSONArray industri = json.getJSONArray(TAG_USER); Log.d("WMWMWMWMWMWMWMWMW : ", industri.length() + ""); for (int i = 0; i < industri.length(); i++) { JSONObject ar = industri.getJSONObject(i); Industry indust = new Industry(ar.getString(TAG_ID), ar.getString(TAG_NAME), ar.getString(TAG_HRG), "http://10.0.2.2/test/img/" + ar.getString(TAG_IMG)); induslist.add(indust); } } else { // jika tidak ada data // maka jalankan tambahkan buku tamu // Intent i = new Intent(getApplicationContext(), // Maps.class); // tutup semua proses sebelumnya // i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // startActivity(i); } } catch (JSONException e) { e.printStackTrace(); } adapter = new CustomAdapter(getApplicationContext(), induslist); lv.setAdapter(adapter); // searchView.setOnQueryTextListener(this); } @Override public boolean onQueryTextChange(String newText) { adapter.getFilter().filter(newText); return false; } @Override public boolean onQueryTextSubmit(String query) { return false; } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.activity_main_actions, menu); // Associate searchable configuration with the SearchView SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); searchView = (SearchView) menu.findItem(R.id.action_search) .getActionView(); searchView.setSearchableInfo(searchManager .getSearchableInfo(getComponentName())); searchView.setOnQueryTextListener(this); return super.onCreateOptionsMenu(menu); } /** * On selecting action bar icons * */ @Override public boolean onOptionsItemSelected(MenuItem item) { // Take appropriate action for each action item click switch (item.getItemId()) { case R.id.action_search: // search action return true; case android.R.id.home: onBackPressed(); finish(); break; default: break; } return true; } } |
Cara click listviewnya gimana gan??? Mohon bantuannya gan kirim balasan di email saya...
ReplyDelete