public class kuliner extends ListActivity {
private static String url = "http://kulinermalang.zz.mu/kuliner/daftar_kuliner.php";
private static final String no_id = "id";
private static final String gambar = "gambar";
private static final String nama = "nama_toko";
JSONArray menu = null;
ListView list;
ArrayList<HashMap<String, String>> daftar_kuliner = new ArrayList<HashMap<String, String>>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main_listview);
EditText search = (EditText) findViewById(R.id.tfCari);
//ambil();
search.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
loadingData loading = new loadingData();
loading.execute();
}
//this method for call data to listView
private class loadingData extends AsyncTask<String, Void, String> {
private ProgressDialog Dialog;
String response;
#Override
protected void onPreExecute() {
Dialog = new ProgressDialog(kuliner.this);
Dialog.setMessage("Loading Data...");
Dialog.show();
}
#Override
protected String doInBackground(String... urls) {
response = "Success";
return response;
}
#Override
protected void onPostExecute(String result) {
if (response.equalsIgnoreCase("Success")) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.AmbilJson(url);
String id_nama;
String gambar_toko = null;
String nama_toko;
String image_url;
try {
menu = json.getJSONArray("daftar");
for (int i = 0; i < menu.length(); i++) {
JSONObject ar = menu.getJSONObject(i);
id_nama = ar.getString(no_id);
gambar_toko = ar.getString(gambar);
nama_toko = ar.getString(nama);
HashMap<String, String> map = new HashMap<String, String>();
map.put(no_id, id_nama);
map.put(gambar, gambar_toko);
map.put(nama, nama_toko);
daftar_kuliner.add(map);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
Dialog.dismiss();
}
}
}
You could probably do something like this
//get your ListView with attached SimpleAdapter
ListAdapter adapter = listView.getAdapter();
for(int i = 0; i < adapter.getCount(); i++) {
String value = ((HashMap<String, String>)adapter.getItem(i)).get("Your_key");
}
But i'm not sure i understand the question correctly, what is it that you want to accomplish exactly? I'm sorry for asking a question here but i'm not allowed to comment yet :/
in the onTextChangedMethod of TextWatcher, write an if condition that - the edittext values is in the list you are inflating in your listview, if yes them add that edittext value to another list and set that list to your adapter. For Example Here is my Code :- ( Just focus on ListView, ArrayList and TextWatcher. Dont mind other code)
package com.example.alaramsms;
import java.util.ArrayList;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ContactActivity extends Activity implements OnItemClickListener{
String textlength;
ArrayList<String> filtered_name;
ArrayList<String> filtered_phone;
ArrayList<String> name1 = new ArrayList<String>();
ArrayList<String> phno1 = new ArrayList<String>();
ArrayList<String> phno0 = new ArrayList<String>();
ArrayList<String> list = new ArrayList<String>();
ArrayList<String> mOriginalValues;
MyAdapter mAdapter ;
Button send,btnselect;
ListView lv;
EditText myFilter;
boolean flag = false;
ArrayList<Integer> checkedPositions = new ArrayList<Integer>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get);
lv =(ListView)findViewById(R.id.lv);
getAllCallLogs(this.getContentResolver());
mAdapter = new MyAdapter(this,name1,phno1);
lv.setAdapter(mAdapter);
lv.setOnItemClickListener(this);
lv.setItemsCanFocus(false);
lv.setTextFilterEnabled(true);
send = (Button) findViewById(R.id.button1);
CheckBox chkAll = ( CheckBox ) findViewById(R.id.chkAll);
chkAll.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
flag = !flag;
mAdapter.notifyDataSetChanged();
}
});
myFilter = (EditText) findViewById(R.id.myFilter);
myFilter.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count,int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
#SuppressLint("DefaultLocale")
public void onTextChanged(CharSequence s,
int start, int before, int count)
{
textlength = myFilter.getText().toString();
filtered_name = new ArrayList<String>();
filtered_phone = new ArrayList<String>();
for (int i = 0; i < name1.size(); i++)
{
if(name1.get(i).toString().toUpperCase().contains(myFilter.getText().toString().toUpperCase()))
{
System.err.println("Selection: " + textlength);
filtered_name.add(name1.get(i));
filtered_phone.add(phno1.get(i));
}
}
mAdapter = new MyAdapter(ContactActivity.this,filtered_name,filtered_phone);
lv.setAdapter(mAdapter); // Here inflating two other lists containing he searched items
}
});
send.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
StringBuilder checkedcontacts= new StringBuilder();
System.out.println(".............."+mAdapter.mCheckStates.size());
for(int i = 0; i < name1.size(); i++)
{
if(mAdapter.mCheckStates.get(i)==true)
{
phno0.add(phno1.get(i).toString()) ;
checkedcontacts.append(name1.get(i).toString());
checkedcontacts.append("\n");
}
else
{
System.out.println("..Not Checked......"+name1.get(i).toString());
}
}
Toast.makeText(ContactActivity.this, checkedcontacts,1000).show();
Intent returnIntent = new Intent();
returnIntent.putStringArrayListExtra("name",phno0);
setResult(RESULT_OK,returnIntent);
finish();
}
});
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
mAdapter.toggle(arg2);
}
public void getAllCallLogs(ContentResolver cr) {
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println(".................."+phoneNumber);
name1.add(name);
phno1.add(phoneNumber);
}
phones.close();
}
class MyAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener
{
private SparseBooleanArray mCheckStates;
ArrayList<String> name1;
ArrayList<String> phno1;
LayoutInflater mInflater;
TextView tv1,tv;
CheckBox cb;
MyAdapter(ContactActivity contactActivity, ArrayList<String> name1, ArrayList<String> phno1)
{
mCheckStates = new SparseBooleanArray(name1.size());
mInflater = (LayoutInflater)ContactActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.name1 = name1;
this.phno1 = phno1;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return name1.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
vi = mInflater.inflate(R.layout.row, null);
tv= (TextView) vi.findViewById(R.id.textView1);
tv1= (TextView) vi.findViewById(R.id.textView2);
cb = (CheckBox) vi.findViewById(R.id.checkBox1);
tv.setText("Name :"+ name1.get(position));
tv1.setText("Phone No :"+ phno1.get(position));
cb.setTag(position);
cb.setChecked(flag); // You just have to add this line
cb.setOnCheckedChangeListener(this);
return vi;
}
/*
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,FilterResults results) {
//ArrayList<String> name1 = new ArrayList<String>();
arrayList = (ArrayList<String>) results.values; // has the filtered values
notifyDataSetChanged(); // notifies the data with new filtered values
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults(); // Holds the results of a filtering operation in values
ArrayList<String> FilteredArrList = new ArrayList<String>();
if (mOriginalValues == null) {
mOriginalValues = new ArrayList<String>(name1); // saves the original data in mOriginalValues
}
/********
*
* If constraint(CharSequence that is received) is null returns the mOriginalValues(Original) values
* else does the Filtering and returns FilteredArrList(Filtered)
*
********/
/* if (constraint == null || constraint.length() == 0) {
// set the Original result to return
results.count = mOriginalValues.size();
results.values = mOriginalValues;
} else {
constraint = constraint.toString().toLowerCase();
for (int i = 0; i < mOriginalValues.size(); i++) {
String name1 = mOriginalValues.get(i).toString();
if (name1.toLowerCase().startsWith(constraint.toString())) {
FilteredArrList.add(name1);
}
}
// set the Filtered result to return
results.count = FilteredArrList.size();
results.values = FilteredArrList;
}
return results;
}
};
return filter;
}*/
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
}
Related
I am trying since last some days but I didn't achieve my goal. The problem I am facing in my code is when I type in EditText for search in list view as the searching criteria depend on 'Policy No'. It works perfect for single value (Policy No) and it changes as I type. But the remaining other values doesn't changes it remains on their own places. Kindly Help me for this. Thanks In Advance . and sorry for my bad English.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Interpolator.Result;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
public class ListViewAdapter_claimlist extends BaseAdapter implements Filterable{
Activity context;
String claimid[];
String ref[];
String policy[];
String natureofloss[];
String status[];
private ItemFilter mFilter = new ItemFilter();
private List<String>originalData = null;
private List<String>filteredData = null;
private List<String>claimidFilter = null;
private List<String>refFilter = null;
private List<String>nautreoflossfilter = null;
private List<String>statusFilter = null;
ArrayList<abc> alldata = new ArrayList<abc>();
public ListViewAdapter_claimlist(Activity context, String[] claimid, String[] ref,String[] policy, String[] natureofloss, String[] status) {
super();
this.context = context;
this.claimid = claimid;
this.ref = ref;
this.policy = policy;
this.natureofloss = natureofloss;
this.status = status;
this.filteredData = new ArrayList<String>(Arrays.asList(this.policy));
this.originalData = new ArrayList<String>(Arrays.asList(this.policy));
this.claimidFilter = new ArrayList<String>(Arrays.asList(this.claimid));
this.refFilter = new ArrayList<String>(Arrays.asList(this.ref));
this.nautreoflossfilter = new ArrayList<String>(Arrays.asList(this.natureofloss));
this.statusFilter = new ArrayList<String>(Arrays.asList(this.status));
for(int i = 0; i<this.claimid.length; i++)
{
abc a = new abc();
a.setClaimid(claimid[i]);
a.setRef(ref[i]);
a.setPolicy(policy[i]);
a.setNatureofLoss(natureofloss[i]);
a.setStatus(status[i]);
alldata.add(a);
}
}
public int getCount() {
return filteredData.size();
}
public Object getItem(int position) {
return filteredData.get(position);
}
public long getItemId(int position) {
return 0;
}
private class ViewHolder {
TextView cliamid;
TextView ref;
TextView policy;
TextView natureofloss;
TextView status;
}
public View getView(int position, View convertView, final ViewGroup parent)
{
final ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
if (convertView == null)
{
convertView = inflater.inflate(R.layout.rowitem_cliamlist, null);
holder = new ViewHolder();
holder.cliamid = (TextView) convertView.findViewById(R.id.tv_claims);
holder.ref = (TextView) convertView.findViewById(R.id.tv_referencepolicy);
holder.policy = (TextView) convertView.findViewById(R.id.tv_policyNo);
holder.natureofloss = (TextView) convertView.findViewById(R.id.tv_natureoflos);
holder.status = (TextView) convertView.findViewById(R.id.tv_claimstatus);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
Button b = (Button) convertView.findViewById(R.id.btn_quotaions_claims);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(parent.getContext(), QuotationList.class);
intent.putExtra("quot_id", holder.cliamid.getText().toString());
Constants.claim_id = holder.cliamid.getText().toString();
context.startActivity(intent);
}
});
Button c = (Button) convertView.findViewById(R.id.btn_claimdetail_claims);
c.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
StringTokenizer tokens = new StringTokenizer(holder.ref.getText().toString(), "/");
String first = tokens.nextToken();
String two = tokens.nextToken();
Intent intent = new Intent(parent.getContext(), Claimform.class);
intent.putExtra("ref_id", first);
intent.putExtra("typeofintimation", holder.natureofloss.getText().toString());
Constants.key_id = first;
context.startActivity(intent);
}
});
abc aa = alldata.get(position);
holder.cliamid.setText(aa.getClaimid());
holder.ref.setText(aa.getRef());
holder.policy.setText(filteredData.get(position));
holder.natureofloss.setText(aa.getNatureofloss());
holder.status.setText(aa.getStatus());
return convertView;
}
//--------------------------------------------------------------------------------
public Filter getFilter() {
return mFilter;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
final List<String> list = originalData;
int count = list.size();
final ArrayList<String> nlist = new ArrayList<String>(count);
String filterableString ;
for (int i = 0; i < count; i++) {
filterableString = list.get(i);
if (filterableString.toLowerCase().contains(filterString)) {
nlist.add(filterableString);
}
}
results.values = nlist;
results.count = nlist.size();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredData = (ArrayList<String>) results.values;
notifyDataSetChanged();
}
}
public class abc
{
String claimid;
String ref;
String policy;
String natureofloss;
String status;
public void setClaimid(String claimid)
{
this.claimid = claimid;
}
public void setRef(String ref)
{
this.ref = ref;
}
public void setPolicy(String policy)
{
this.policy = policy;
}
public void setNatureofLoss(String natureofloss)
{
this.natureofloss = natureofloss;
}
public void setStatus(String status)
{
this.status = status;
}
public String getClaimid()
{
String claimid = this.claimid;
return claimid;
}
public String getRef()
{
String ref = this.ref;
return ref;
}
public String getPolicy()
{
String Policy = this.policy;
return Policy;
}
public String getNatureofloss()
{
String Natureofloss = this.natureofloss;
return Natureofloss;
}
public String getStatus()
{
String Status = this.status;
return Status;
}
}
}
EditText Event
searchText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
ClaimList.this.lviewAdapter.getFilter().filter(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
Use these following lines of code...It can be helpful for you
searchText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
ClaimList.this.lviewAdapter.getFilter().filter(searchText.getText().toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
Kindly help me in my code, It doesn't search perfect all other values remain on their position except the search able string.
Here is the code of filterable class
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Interpolator.Result;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
public class ListViewAdapter_claimlist extends BaseAdapter implements Filterable{
Activity context;
String claimid[];
String ref[];
String policy[];
String natureofloss[];
String registration[];
String status[];
private ItemFilter mFilter = new ItemFilter();
private List<String>originalData = null;
private List<String>filteredData = null;
private List<String>claimidFilter = null;
private List<String>refFilter = null;
private List<String>nautreoflossfilter = null;
private List<String>registrationFilter = null;
private List<String>statusFilter = null;
ArrayList<abc> alldata = new ArrayList<abc>();
public ListViewAdapter_claimlist(Activity context, String[] claimid, String[] ref,String[] policy, String[] natureofloss,String[] registration, String[] status) {
super();
this.context = context;
this.claimid = claimid;
this.ref = ref;
this.policy = policy;
this.natureofloss = natureofloss;
this.registration = registration;
this.status = status;
this.filteredData = new ArrayList<String>(Arrays.asList(this.policy));
this.originalData = new ArrayList<String>(Arrays.asList(this.policy));
this.claimidFilter = new ArrayList<String>(Arrays.asList(this.claimid));
this.refFilter = new ArrayList<String>(Arrays.asList(this.ref));
this.nautreoflossfilter = new ArrayList<String>(Arrays.asList(this.natureofloss));
this.registrationFilter = new ArrayList<String>(Arrays.asList(this.registration));
this.statusFilter = new ArrayList<String>(Arrays.asList(this.status));
for(int i = 0; i<this.claimid.length; i++)
{
abc a = new abc();
a.setClaimid(claimid[i]);
a.setRef(ref[i]);
a.setPolicy(policy[i]);
a.setNatureofLoss(natureofloss[i]);
a.setRegistration(registration[i]);
a.setStatus(status[i]);
alldata.add(a);
}
}
public int getCount() {
return filteredData.size();
}
public Object getItem(int position) {
return filteredData.get(position);
}
public long getItemId(int position) {
return 0;
}
private class ViewHolder {
TextView cliamid;
TextView ref;
TextView policy;
TextView natureofloss;
TextView registration;
TextView status;
}
public View getView(int position, View convertView, final ViewGroup parent)
{
final ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
if (convertView == null)
{
convertView = inflater.inflate(R.layout.rowitem_cliamlist, null);
holder = new ViewHolder();
holder.cliamid = (TextView) convertView.findViewById(R.id.tv_claims);
holder.ref = (TextView) convertView.findViewById(R.id.tv_referencepolicy);
holder.policy = (TextView) convertView.findViewById(R.id.tv_policyNo);
holder.natureofloss = (TextView) convertView.findViewById(R.id.tv_natureoflos);
holder.registration = (TextView) convertView.findViewById(R.id.tv_registration);
holder.status = (TextView) convertView.findViewById(R.id.tv_claimstatus);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
abc aa = alldata.get(position);
holder.cliamid.setText(aa.getClaimid());
holder.ref.setText(aa.getRef());
holder.policy.setText(filteredData.get(position));
holder.natureofloss.setText(aa.getNatureofloss());
holder.registration.setText(aa.getRegistration());
holder.status.setText(aa.getStatus());
return convertView;
}
//--------------------------------------------------------------------------------
public Filter getFilter() {
return mFilter;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
final List<String> list = originalData;
int count = list.size();
final ArrayList<String> nlist = new ArrayList<String>(count);
String filterableString ;
for (int i = 0; i < count; i++) {
filterableString = list.get(i);
if (filterableString.toLowerCase().contains(filterString)) {
nlist.add(filterableString);
}
}
results.values = nlist;
results.count = nlist.size();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredData = (ArrayList<String>) results.values;
notifyDataSetChanged();
}
}
public class abc
{
String claimid;
String ref;
String policy;
String natureofloss;
String registration;
String status;
public void setClaimid(String claimid)
{
this.claimid = claimid;
}
public void setRef(String ref)
{
this.ref = ref;
}
public void setPolicy(String policy)
{
this.policy = policy;
}
public void setNatureofLoss(String natureofloss)
{
this.natureofloss = natureofloss;
}
public void setRegistration(String registration)
{
this.registration = registration;
}
public void setStatus(String status)
{
this.status = status;
}
public String getClaimid()
{
String claimid = this.claimid;
return claimid;
}
public String getRef()
{
String ref = this.ref;
return ref;
}
public String getPolicy()
{
String Policy = this.policy;
return Policy;
}
public String getNatureofloss()
{
String Natureofloss = this.natureofloss;
return Natureofloss;
}
public String getRegistration()
{
String Registration = this.registration;
return Registration;
}
public String getStatus()
{
String Status = this.status;
return Status;
}
}
}
Edit Text Event Handler
searchText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
ClaimList.this.lviewAdapter.getFilter().filter(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
Before Search
When Search by Police No(policy# in code)
Thank in Advance :)
You can choose another trick for this, set an textWatcher on the edit text where you are entering the search text.
searchText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
String text = searchText.getText().toString()
.toLowerCase(Locale.getDefault());
lviewAdapter.filter(text);
}
});
put a filter method in Adapter class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
temp.clear();
if (charText.length() == 0) {
temp.addAll(list_original);
} else {
for (Abc abc: list_original) {
// if you want to search via policy
if (abc.getPolicy().toLowerCase(Locale.getDefault())
.contains(charText)) {
temp.add(abc);
}
}
}
notifyDataSetChanged();
}
And create two Abc type arraylists one is temp and one is original, always pass data to the listview in getview method from temp list, so that you can make changes in temp, not the original one. In above case the temp list cleared first and run a loop to check that search text in original list if matches then add that object to temp list, and called notifyDataSetChanged.. Voila
Hello i have made a dynamic listview..Now i want to add filter in listview.if i enter text in edittext then item which mathces the search should display..have called addTextChangedListener to my edittext..and called a method filter in my adapter..but m not getting any idea what should i write in my filter method as it is a dynamic listview...
Here is my code:
package com.XXXXX.XXXXX;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.AdapterView.OnItemClickListener;
import com.XXXXX.adapter.UpdateSingleItemViewActivity;
import com.XXXXX.adapter.UpdatesAdapterList;
import com.XXXXX.local.database.DBController;
import com.XXXXX.XXXXX.XXXXX.constant.Constant;
import com.XXXXX.XXXXX.XXXXX.utils.Utility;
public class Cardiology_updates extends Activity implements OnClickListener,
OnRefreshListener {
EditText et ;
private Context appContext;
// ProgressDialog mProgressDialog;
private Dialog dialog;
private boolean isFinish = false;
String result = "";
JSONObject jsonobject;
JSONArray jsonArray;
ArrayList<HashMap<String, String>> UpdatesHmList;
public static ArrayList<HashMap<String, String>> FinalLocalDataList;
ArrayList<HashMap<String, String>> LocalDataList;
DBController controller = new DBController(this);
HashMap<String, String> queryValues;
ListView list;
UpdatesAdapterList adapter;
public static String UpdateID = "UpdateID";
public static String UpdateTitle = "Title";
/*
* public static String UpdateDescription = "Description"; public static
* String POPULATION = "UpdateDate"; public static String UpdateImage =
* "Photo";
*/
public static String UpdateDescription = "Description";
public static String POPULATION = "Title";
public static String UpdateImage = "Complete_imagePath";
public static String Complete_imagePath;
public static String Title;
public static String Description;
SwipeRefreshLayout swipeLayout;
private ProgressBar progressbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cardiology_updates);
// controller.deleteAllJsonData();
appContext = this;
animationView();
initComponent();
}
private void animationView() {
// TODO Auto-generated method stub
progressbar = (ProgressBar) findViewById(R.id.loading);
}
private void initComponent() {
// TODO Auto-generated method stub
swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setColorScheme(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
dialog = new Dialog(appContext);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.alert_dialog);
((Button) findViewById(R.id.Button01)).setOnClickListener(this);
((Button) dialog.findViewById(R.id.btnOk)).setOnClickListener(this);
new GetUpdatesInfo().execute();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.Button01) {
finish();
// finishActivity() ;
} else if (v.getId() == R.id.btnOk) {
dialog.dismiss();
if (isFinish) {
this.finish();
}
}
}
public class GetUpdatesInfo extends AsyncTask<String, Void, String> {
protected void onPreExecute() {
super.onPreExecute();
if (progressbar.getVisibility() != View.VISIBLE) {
progressbar.setVisibility(View.VISIBLE);
}
}
#Override
protected String doInBackground(String... params) {
// Create an array
UpdatesHmList = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
String url = null;
url = Constant.serverUrl + "/GetUpdateList";
result = Utility.postParamsAndfindJSON(url);
Log.e("result doInBackground", "" + result);
if (!(result == null)) {
try {
controller.deleteAllJsonData();
// Locate the array name in JSON
jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonArray.getJSONObject(i);
// Retrive JSON Objects
map.put("UpdateID", jsonobject.getString("UpdateID"));
map.put("Title", jsonobject.getString("Title"));
String Upadates_Photo = jsonobject.optString("Photo")
.toString();
String Complete_imagePath = Constant.prifixserverUrl
+ Upadates_Photo;
String Title = jsonobject.getString("Title").toString();
String Description = jsonobject
.getString("Description").toString();
String noHtml = Description.replaceAll("<[^>]*>", "");
String parseResponse = noHtml.replaceAll(" ", "");
map.put("Photo", Complete_imagePath);
map.put("Description", Description);
map.put("UpdateDate",
jsonobject.getString("UpdateDate"));
Log.e("UpdateID ",
" "
+ jsonobject.getString("UpdateID")
.toString());
Log.e("Title ", " "
+ jsonobject.getString("Title").toString());
Log.e("Complete_imagePath ",
" " + Complete_imagePath.toString());
Log.e("Description ", " " + parseResponse);
Log.e("UpdateDate ",
" "
+ jsonobject.getString("UpdateDate")
.toString());
queryValues = new HashMap<String, String>();
queryValues.put("Complete_imagePath",
Complete_imagePath);
queryValues.put("Title", Title);
queryValues.put("Description", Description);
controller.insertAllJsonData(queryValues);
// Set the JSON Objects into the array
UpdatesHmList.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
return result;
}
#Override
protected void onPostExecute(String result) {
// Locate the listview in listview_main.xml
if (progressbar.getVisibility() == View.VISIBLE) {
progressbar.setVisibility(View.GONE);
}
/*
* if (result == null) { //mProgressDialog.dismiss();
* localalldata();
*
* }
*/
localalldata();
/*
* list = (ListView) findViewById(R.id.list_Upadates); // Pass the
* results into ListViewAdapter.java adapter = new
* UpdatesAdapterList(Cardiology_updates.this, FinalLocalDataList);
* // Set the adapter to the ListView list.setAdapter(adapter);
*/
// Close the progressdialog
// mProgressDialog.dismiss();
}
}
#Override
public void onRefresh() {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
getSomeData();
// localalldata();
swipeLayout.setRefreshing(false);
}
}, 5000);
}
protected void getSomeData() {
// TODO Auto-generated method stub
// localalldata();
new GetUpdatesInfo().execute();
adapter.notifyDataSetChanged();
/*
* if (LocalDataList == null) { Log.e("LocalDataList inside if ",
* "LocalDataList inside if "); new GetUpdatesInfo().execute();
*
* } else { // adapter.imageLoader.clearCache();
* Log.e("LocalDataList else ", "LocalDataList else ");
*
* adapter.notifyDataSetChanged(); }
*/
}
private void localalldata() {
// TODO Auto-generated method stub
LocalDataList = controller.getAllJsonData();
FinalLocalDataList = new ArrayList<HashMap<String, String>>();
for (HashMap<String, String> hashMap : LocalDataList) {
System.out.println(hashMap.keySet());
HashMap<String, String> map = new HashMap<String, String>();
for (String key : hashMap.keySet()) {
System.out.println(hashMap.get(key));
Complete_imagePath = hashMap.get("Complete_imagePath");
Title = hashMap.get("Title");
Description = hashMap.get("Description");
map.put("Complete_imagePath", Complete_imagePath);
map.put("Title", Title);
map.put("Description", Description);
Log.v("All Json CodiateUpdate Title", "" + Complete_imagePath);
Log.v("All Json CodiateUpdate Title", "" + Title);
}
FinalLocalDataList.add(map);
}
list = (ListView) findViewById(R.id.list_Upadates);
// Pass the results into ListViewAdapter.java
adapter = new UpdatesAdapterList(Cardiology_updates.this,
FinalLocalDataList);
// Set the adapter to the ListView
list.setAdapter(adapter);
// adapter.notifyDataSetChanged();
et = (EditText) findViewById(R.id.search);
// Capture Text in EditText
et.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
//String text = et.getText().toString().toLowerCase(Locale.getDefault());
adapter.getFilter().filter(arg0);
}
});
}
}
Here is my adapter class includes filter:
package com.XXXXX.adapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import com.XXXXX.XXXXX.Cardiology_updates;
import com.XXXXX.XXXXX.R;
import com.XXXXX.imageloader.ImageLoader;
public class UpdatesAdapterList extends BaseAdapter implements Filterable {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
public ImageLoader imageLoader;
private Activity activity;
HashMap<String, String> resultp = new HashMap<String, String>();
public UpdatesAdapterList(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context.getApplicationContext());
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView UpdateTitle;
TextView country;
TextView population;
ImageView UpdateImage;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.listview_updateitem, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
UpdateTitle = (TextView) itemView.findViewById(R.id.txtUpdatetitle);
//country = (TextView) itemView.findViewById(R.id.country);
// population = (TextView) itemView.findViewById(R.id.population);
// Locate the ImageView in listview_item.xml
UpdateImage = (ImageView) itemView.findViewById(R.id.list_UpdateImage);
// Capture position and set results to the TextViews
UpdateTitle.setText(resultp.get(Cardiology_updates.UpdateTitle));
// country.setText(resultp.get(UpdatesActivity.COUNTRY));
// population.setText());
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(Cardiology_updates.UpdateImage), UpdateImage);
// Capture ListView item click
itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, UpdateSingleItemViewActivity.class);
// Pass all data rank
intent.putExtra("UpdateTile", resultp.get(Cardiology_updates.UpdateTitle));
// Pass all data country
intent.putExtra("UpdateDescription", resultp.get(Cardiology_updates.UpdateDescription));
// Pass all data population
intent.putExtra("population",resultp.get(Cardiology_updates.POPULATION));
// Pass all data flag
intent.putExtra("UpdateImage", resultp.get(Cardiology_updates.UpdateImage));
// Start SingleItemView Class
intent.putExtra("position", position);
context.startActivity(intent);
}
});
return itemView;
}
public Filter getFilter() {
Filter filter = new Filter() {
FilterResults results;
ArrayList<HashMap<String, String>> filteredList;
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
// Has the filtered values
data = (ArrayList<HashMap<String, String>>) results.values;
notifyDataSetChanged();
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
// Holds the results of a filtering operation in values
results = new FilterResults();
filteredList= new ArrayList<HashMap<String, String>>();
//This is the search string user typed in EditText.
String searchString = constraint.toString().toUpperCase(Locale.getDefault());
/*
* Code to update the filteredList based on Search String.
*
* I'm just writing pseudo code for search, based on
* Cardiology_updates.UpdateTitle
*/
int mCount=data.size();
for (int i = 0; i < mCount; i++) {
HashMap<String, String> obj= data.get(i);
String updateTitle=obj.get(Cardiology_updates.UpdateTitle);
if(updateTitle.contains(searchString)){
filteredList.add(obj);
}
}
synchronized (this) {
// set the Filtered result to return
results.count = filteredList.size();
results.values = filteredList;
}
return results;
}
};
return filter;
}
}
You need to implement Filterable interface in your UpdatesAdapterList class.
For detailed explanation visit How to implement getfilter() with custom adapter that extends baseadapter?.
public class UpdatesAdapterList extends BaseAdapter implements Filterable {
...
#Override
public Filter getFilter(){
// Your Search logic goes here..
Filter filter = new Filter() {
FilterResults results;
ArrayList<HashMap<String, String>> filteredList;
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
// Has the filtered values
data = (ArrayList<HashMap<String, String>>) results.values;
notifyDataSetChanged();
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
// Holds the results of a filtering operation in values
results = new FilterResults();
filteredList= new ArrayList<HashMap<String, String>>();
//This is the search string user typed in EditText.
String searchString = constraint.toString();
/*
* Code to update the filteredList based on Search String.
*
* I'm just writing pseudo code for search, based on
* Cardiology_updates.UpdateTitle
*/
int mCount=data.size();
for (int i = 0; i < mCount; i++) {
HashMap<String, String> obj= data.get(i);
String updateTitle=obj.get(Cardiology_updates.UpdateTitle);
if(updateTitle.contains(searchString)){
filteredList.add(obj);
}
}
synchronized (this) {
// set the Filtered result to return
results.count = filteredList.size();
results.values = filteredList;
}
}
return results;
}
};
return filter;
}
}
In my application I have search tab which display images with their name in grid view and now I want to implement search functionality. I have been searching in google for past two days but I didn't get any solution. Any idea or tutorial 0r how can I achieve this?
Anyone help me with this.
Thanks in advance.
mainactivity
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import com.example.diceapp.R;
public class SearchActivity extends Activity
{
JSONArray results;
JSONObject jobj;
SearchCustomAdapter adapter1;
ImageButton ib;
ArrayList<String> a1,a2,a3,a4;
ArrayList<String> name=new ArrayList<String>();
ArrayList<String> description=new ArrayList<String>();
ArrayList<String> image=new ArrayList<String>();
ArrayList<String> price=new ArrayList<String>();
Button add;
String pid;
GridView gView;
EditText src;
int textlength = 0;
ArrayList<String> p_name = new ArrayList<String>();
ArrayList<String> p_image = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.search_activity);
a1=new ArrayList<String>();
a2=new ArrayList<String>();
a3=new ArrayList<String>();
a4=new ArrayList<String>();
src=(EditText)findViewById(R.id.srcetxt);
/*src.addTextChangedListener(new TextWatcher()
{
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
SearchActivity.this.adapter1.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});*/
new Searchtask().execute();
gView = (GridView)findViewById(R.id.gridView1);
gView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
System.out.println("outside on click"+position);
}
});
ib=(ImageButton)findViewById(R.id.imageButton1);
}
private class Searchtask extends AsyncTask<String, String, JSONObject>
{
private ProgressDialog pDialog;
#Override
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(SearchActivity.this);
pDialog.setMessage("Loading Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args)
{
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl("http:link.php");
return json;
}
#Override
protected void onPostExecute(JSONObject json)
{
System.out.println("---------------return name list json------------"+json);
pDialog.dismiss();
try
{
jobj=json.getJSONObject("response");
// Getting Array of Contacts
results = jobj.getJSONArray("obejects");
System.out.println("In product Activity after JSON");
// looping through All Contacts
for(int i = 0; i < results.length(); i++)
{
JSONObject c = results.getJSONObject(i);
name.add(c.getString("name"));
image.add(c.getString("image"));
price.add(c.getString("price"));
description.add(c.getString("Description"));
}
}
catch (JSONException e)
{
e.printStackTrace();
}
adapter1 = new SearchCustomAdapter(getApplicationContext(), R.layout.gridlistimg, name, image,description,price);
gView.setAdapter(adapter1);
}
}
}
baseadapter class
package com.example.diceapp.search;
import java.util.ArrayList;
import android.content.Context;
import android.content.Intent;
import android.sax.StartElementListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import com.example.diceapp.AAAMainActivity;
import com.example.diceapp.R;
import com.example.diceapp.category.ImageLoader;
public class SearchCustomAdapter extends BaseAdapter
{
Context context;
LayoutInflater inflater;
ArrayList<String> aaaa1,bbbb1,cccc1;
ArrayList<String> c_pname;
ArrayList<String> c_pimage;
ArrayList<String> c_pprice;
ArrayList<String> c_pdescription;
String[] data_text;
String[] data_image;
ImageLoader iloader;
public SearchCustomAdapter(Context c, int productDescribe,ArrayList<String> pname, ArrayList<String> pimage,
ArrayList<String> productdescription, ArrayList<String> pprice)
{
// TODO Auto-generated constructor stub
this.context=c;
this.c_pname=pname;
this.c_pprice=pprice;
this.c_pdescription=productdescription;
this.c_pimage=pimage;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
iloader= new ImageLoader(context.getApplicationContext());
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return c_pname.size();
//return data_text.length;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int pos) {
// TODO Auto-generated method stub
//return c_pname.indexOf(getItem(pos));//arg0;
return pos;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
// TODO Auto-generated method stub
View row=convertView;
ViewHolder vh;
if(row==null)
{
row=inflater.inflate(R.layout.custom_search_activity, parent, false);
vh=new ViewHolder();
vh.pname=(TextView)row.findViewById(R.id.product_name);
vh.pprice=(TextView)row.findViewById(R.id.textView2);
vh.image1=(ImageView) row.findViewById(R.id.imageView1);
vh.btn=(Button)row.findViewById(R.id.p_custom_tv);
/*row.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
System.out.println("outside on click"+position);
ArrayList<String> sendingary=new ArrayList<String>();
sendingary.add(c_pname.get(position));
sendingary.add(c_pprice.get(position));
sendingary.add(c_pimage.get(position));
sendingary.add(c_pdescription.get(position));
Intent cp=new Intent(context.getApplicationContext(),product_details.class);
cp.putStringArrayListExtra("aryvalue", sendingary);
cp.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(cp);
}
});*/
row.setTag(vh);
}
else
{
vh = (ViewHolder) row.getTag();
row=convertView;
}
vh.pname.setText(c_pname.get(position));
vh.pprice.setText("KD "+c_pprice.get(position));
iloader.DisplayImage(c_pimage.get(position), vh.image1);
return row;
}
public static class ViewHolder
{
TextView pname,pprice;
ImageView image1;
Button btn;
}
public SearchCustomAdapter getFilter() {
// TODO Auto-generated method stub
return null;
}
}
If you use ArrayAdapter as your gridview's adapter, you can override getFilter() method and return your own Filter, which is able to filter items according to entered text. See e.g. this link to learn how to work with Filter. Good luck. :-)
Hi I just edit your code please replace and check it
SearchActivity.java
import java.util.ArrayList;
import java.util.Iterator;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
public class SearchActivity extends Activity {
JSONArray results;
JSONObject jobj;
SearchCustomAdapter adapter1;
ImageButton ib;
ArrayList<String> a1, a2, a3, a4;
ArrayList<String> name = new ArrayList<String>();
ArrayList<String> description = new ArrayList<String>();
ArrayList<String> image = new ArrayList<String>();
ArrayList<String> price = new ArrayList<String>();
Button add;
String pid;
GridView gView;
EditText src;
int textlength = 0;
ArrayList<String> p_name = new ArrayList<String>();
ArrayList<String> p_image = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.search_activity);
a1 = new ArrayList<String>();
a2 = new ArrayList<String>();
a3 = new ArrayList<String>();
a4 = new ArrayList<String>();
src = (EditText) findViewById(R.id.srcetxt);
src.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
#Override
public void afterTextChanged(Editable arg0) {
if (src.getText().toString().trim().length() > 0) {
applySearch(src.getText().toString().trim());
} else {
adapter1.setC_pname(name);
adapter1.setC_pdescription(description);
adapter1.setC_pimage(image);
adapter1.setC_pprice(price);
adapter1.notifyDataSetChanged();
}
}
});
new Searchtask().execute();
gView = (GridView) findViewById(R.id.gridView1);
gView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
// TODO Auto-generated method stub
System.out.println("outside on click" + position);
}
});
ib = (ImageButton) findViewById(R.id.imageButton1);
}
private class Searchtask extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SearchActivity.this);
pDialog.setMessage("Loading Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl("http:link.php");
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
System.out.println("---------------return name list json------------" + json);
pDialog.dismiss();
try {
jobj = json.getJSONObject("response");
// Getting Array of Contacts
results = jobj.getJSONArray("obejects");
System.out.println("In product Activity after JSON");
// looping through All Contacts
for (int i = 0; i < results.length(); i++) {
JSONObject c = results.getJSONObject(i);
name.add(c.getString("name"));
image.add(c.getString("image"));
price.add(c.getString("price"));
description.add(c.getString("Description"));
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter1 = new SearchCustomAdapter(getApplicationContext(), R.layout.gridlistimg, name, image, description, price);
gView.setAdapter(adapter1);
}
}
private void applySearch(String searchStr) {
ArrayList<String> searchname = new ArrayList<String>();
ArrayList<String> searchdescription = new ArrayList<String>();
ArrayList<String> searchimage = new ArrayList<String>();
ArrayList<String> searchprice = new ArrayList<String>();
for (int i = 0; i < name.size(); i++) {
if (name.get(i).contains(searchStr)) {
searchname.add(name.get(i));
searchdescription.add(description.get(i));
searchimage.add(image.get(i));
searchprice.add(price.get(i));
}
}
adapter1.setC_pname(searchname);
adapter1.setC_pdescription(searchdescription);
adapter1.setC_pimage(searchimage);
adapter1.setC_pprice(searchprice);
adapter1.notifyDataSetChanged();
}
}
SearchCustomAdapter.java
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class SearchCustomAdapter extends BaseAdapter {
Context context;
LayoutInflater inflater;
ArrayList<String> aaaa1, bbbb1, cccc1;
ArrayList<String> c_pname;
ArrayList<String> c_pprice;
ArrayList<String> c_pdescription;
ArrayList<String> c_pimage;
public void setC_pname(ArrayList<String> c_pname) {
this.c_pname = c_pname;
}
public void setC_pimage(ArrayList<String> c_pimage) {
this.c_pimage = c_pimage;
}
public void setC_pprice(ArrayList<String> c_pprice) {
this.c_pprice = c_pprice;
}
public void setC_pdescription(ArrayList<String> c_pdescription) {
this.c_pdescription = c_pdescription;
}
String[] data_text;
String[] data_image;
ImageLoader iloader;
public SearchCustomAdapter(Context c, int productDescribe, ArrayList<String> pname, ArrayList<String> pimage, ArrayList<String> productdescription, ArrayList<String> pprice) {
// TODO Auto-generated constructor stub
this.context = c;
this.c_pname = pname;
this.c_pprice = pprice;
this.c_pdescription = productdescription;
this.c_pimage = pimage;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
iloader = new ImageLoader(context.getApplicationContext());
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return c_pname.size();
// return data_text.length;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int pos) {
// TODO Auto-generated method stub
// return c_pname.indexOf(getItem(pos));//arg0;
return pos;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row = convertView;
ViewHolder vh;
if (row == null) {
row = inflater.inflate(R.layout.custom_search_activity, parent, false);
vh = new ViewHolder();
vh.pname = (TextView) row.findViewById(R.id.product_name);
vh.pprice = (TextView) row.findViewById(R.id.textView2);
vh.image1 = (ImageView) row.findViewById(R.id.imageView1);
vh.btn = (Button) row.findViewById(R.id.p_custom_tv);
/*
* row.setOnClickListener(new OnClickListener() {
*
* #Override public void onClick(View arg0) {
*
* System.out.println("outside on click"+position);
*
*
* ArrayList<String> sendingary=new ArrayList<String>();
*
* sendingary.add(c_pname.get(position));
*
* sendingary.add(c_pprice.get(position));
*
* sendingary.add(c_pimage.get(position));
*
* sendingary.add(c_pdescription.get(position));
*
* Intent cp=new
* Intent(context.getApplicationContext(),product_details.class);
*
* cp.putStringArrayListExtra("aryvalue", sendingary);
*
* cp.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
*
* context.startActivity(cp);
*
* } });
*/
row.setTag(vh);
} else {
vh = (ViewHolder) row.getTag();
row = convertView;
}
vh.pname.setText(c_pname.get(position));
vh.pprice.setText("KD " + c_pprice.get(position));
iloader.DisplayImage(c_pimage.get(position), vh.image1);
return row;
}
public static class ViewHolder {
TextView pname, pprice;
ImageView image1;
Button btn;
}
}
I am suffering a weird problem. Actually I have a customize listview in which I am using a filter, everything working fine but when I am typing a text to edittext it disappear the all listitem. I am strange why this going on with me, still I am not a champ of android so need some help. I have seen many similar problems on stackoverflow like this,this,this, and many more, but nothing works in my case. I dont know where i am doing mistake.
My listitem click working fine, So hope it will also work after item search into edittext.
Here is my MainActivity.java :
package com.sunil.listviewmuntilerowdelete;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends Activity {
private String[] myfriendname = null;
EditText edtSearch;
private int[] photo = null;
ListView listView = null;
Context contex = null;
MyListAdapter adapter = null;
private List<MyFriendsSDetails> list = new ArrayList<MyFriendsSDetails>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contex = this;
listView = (ListView) findViewById(R.id.listview);
edtSearch = (EditText) findViewById(R.id.EditText01);
myfriendname = new String[] { "Sunil Gupta", "Abhishek Tripathi",
"Sandeep Pal", "Amit Verma" };
photo = new int[] { R.drawable.sunil, R.drawable.abhi,
R.drawable.sandy, R.drawable.amit };
final String text[] = { "Sunil is a great man",
"Abhishek is hardworking", "Sandeep is same as amit",
"Amit is unique" };
final Integer[] image = { R.drawable.sunil, R.drawable.abhi,
R.drawable.sandy, R.drawable.amit,
};
for (int index = 0; index < myfriendname.length; index++) {
MyFriendsSDetails details = new MyFriendsSDetails(
myfriendname[index], photo[index]);
list.add(details);
}
adapter = new MyListAdapter(contex, list);
listView.setAdapter(adapter);
listView.setTextFilterEnabled(true);
edtSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2,
int arg3) {
// When user changed the Text
MainActivity.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(MainActivity.this,
SecondActivity.class);
intent.putExtra("key1", image[position]);
intent.putExtra("key2", text[position]);
startActivity(intent);
}
});
}
}
MyListAdapter.java
package com.sunil.listviewmuntilerowdelete;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class MyListAdapter extends ArrayAdapter<MyFriendsSDetails> {
Context context;
LayoutInflater inflater;
List<MyFriendsSDetails> list;
public MyListAdapter(Context context, List<MyFriendsSDetails> list) {
super(context, 0, list);
this.context = context;
this.list = list;
inflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.list_item, null);
holder.name = (TextView) convertView.findViewById(R.id.title);
holder.photo = (ImageView) convertView.findViewById(R.id.icon);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.name.setText(list.get(position).getMyfriendname());
holder.photo.setImageResource(list.get(position).getPhoto());
return convertView;
}
private class ViewHolder {
TextView name;
ImageView photo;
}
}
Here is MyFriendsSDetails.java :
package com.sunil.listviewmuntilerowdelete;
public class MyFriendsSDetails {
private String myfriendname = null;
private int photo = 0;
public MyFriendsSDetails(String friendname, int myphoto) {
this.myfriendname = friendname;
this.photo = myphoto;
}
public String getMyfriendname() {
return myfriendname;
}
public void setMyfriendname(String myfriendname) {
this.myfriendname = myfriendname;
}
public int getPhoto() {
return photo;
}
public void setPhoto(int photo) {
this.photo = photo;
}
}
Thanks in advance.
As you are using custom adapter, android cant recognize "MainActivity.this.adapter.getFilter().filter(cs);"
You have to override getFilter() method and do manual changes.
Checkout below code :
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,FilterResults results) {
mDisplayedValues = (ArrayList<HashMap<String, String>>) results.values; // has the filtered values
notifyDataSetChanged(); // notifies the data with new filtered values
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults(); // Holds the results of a filtering operation in values
ArrayList<HashMap<String, String>> FilteredArrList = new ArrayList<HashMap<String, String>>();
if (mOriginalValues == null) {
mOriginalValues = new ArrayList<HashMap<String, String>>(mDisplayedValues); // saves the original data in mOriginalValues
}
/********
*
* If constraint(CharSequence that is received) is null returns the mOriginalValues(Original) values
* else does the Filtering and returns FilteredArrList(Filtered)
*
********/
if (constraint == null || constraint.length() == 0) {
// set the Original result to return
results.count = mOriginalValues.size();
results.values = mOriginalValues;
} else {
constraint = constraint.toString().toLowerCase();
for (int i = 0; i < mOriginalValues.size(); i++) {
String data = mOriginalValues.get(i).get("name");
if (data.toLowerCase().startsWith(constraint.toString())) {
HashMap<String, String> hmap=new HashMap<String, String>();
hmap.put("name", mOriginalValues.get(i).get("name"));
hmap.put("image", mOriginalValues.get(i).get("image"));
FilteredArrList.add(hmap);
Log.e("DEBUG", "name : "+data);
}
}
// set the Filtered result to return
results.count = FilteredArrList.size();
results.values = FilteredArrList;
}
return results;
}
};
return filter;
}
and use it in your adapter getView()
holder.name.setText(mDisplayedValues.get(position).get("name"));