How to implement autocompletetextview with listview? - android

I am getting response from server and display it using listview and it works fine,now what I am trying is i added autocompletetextview to search items by name,but when i run my app it crashes and showing errors..i already ask this
Tab1Activity.java
public class Tab1Activity extends ListActivity{
private ProgressDialog pDialog;
JSONArray Product=null;
private ListView listview;
ArrayList<HashMap<String,String>> aList;
ArrayList<HashMap<String, String>> arrayTemplist;
private static String PRODUCT_URL = "";
private static final String PRODUCT_DATA="Product";
private static final String PRODUCT_ID="productid";
private static final String PRODUCT_NAME="product_name";
private static final String PRODUCT_CODE="skucode";
private static final String PRODUCT_IMAGE="product_photo";
private static final String PRODUCT_WEIGHT="weight";
private static final String PRODUCT_SALERATE="sale_rate";
//private static final String PRODUCT_LOCATION="weight";
private CustomAdapterTabone adapter;
private TextView noacpt;
private AutoCompleteTextView inputSearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.list_view_tabone);
//noacpt=(TextView)findViewById(R.id.no_acceptedlist);
/*String strtext = getIntent().getStringExtra("id");
System.out.println("<<<<<<<< id : " + strtext);*/
final ListView listview = (ListView)findViewById(android.R.id.list);
//listview.setSelector( R.drawable.list_selector);
//listview.setSelector(R.drawable.listselector);
new LoadAlbums().execute();
aList = new ArrayList<HashMap<String, String>>();
final ListView lv = getListView();
inputSearch = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
arrayTemplist= new ArrayList<HashMap<String,String>>();
String searchString =inputSearch.getText().toString().toLowerCase();
for (int i = 0; i < aList.size(); i++)
{
String currentString =aList.get(i).get(Tab1Activity.PRODUCT_NAME);
if (currentString.toLowerCase().startsWith(searchString ))
{
arrayTemplist.add(aList.get(i));
}
}
for (int i = 0; i < arrayTemplist.size(); i++)
{
String currentstrin = arrayTemplist.get(i).get(Tab1Activity.PRODUCT_NAME);
//Toast.makeText(getApplicationContext(), currentstrin, Toast.LENGTH_LONG).show();
}
adapter=new CustomAdapterTabone(getApplicationContext(), arrayTemplist);
listview.setAdapter(adapter);
/* SimpleAdapter adapters = new SimpleAdapter(Tab1Activity.this, arrayTemplist,R.layout.list_item_tabone, new String[] { PRODUCT_NAME
}, new int[] {
R.id.txtpronameacptedlist});
lv.setAdapter(adapters);
*/
}
#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
}
});
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Intent intent = new Intent(getApplicationContext(), AllProductDetails.class);
intent.putExtra("productid", aList.get(position).get(PRODUCT_ID));
startActivity(intent);
}
class LoadAlbums extends AsyncTask<String, String, ArrayList<HashMap<String,String>>> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Tab1Activity.this);
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(true);
// pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress));
pDialog.setCancelable(false);
pDialog.show();
}
protected ArrayList<HashMap<String,String>> doInBackground(String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
ArrayList<HashMap<String,String>> data = new ArrayList<HashMap<String, String>>();
String jsonStr = sh.makeServiceCall(PRODUCT_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
Product = jsonObj.getJSONArray(PRODUCT_DATA);
for (int i = 0; i < Product.length(); i++) {
JSONObject c = Product.getJSONObject(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(PRODUCT_ID, c.getString(PRODUCT_ID));
map.put(PRODUCT_NAME,c.getString(PRODUCT_NAME));
map.put(PRODUCT_CODE, c.getString(PRODUCT_CODE));
map.put(PRODUCT_IMAGE, c.getString(PRODUCT_IMAGE));
map.put(PRODUCT_WEIGHT, c.getString(PRODUCT_WEIGHT));
map.put(PRODUCT_SALERATE, c.getString(PRODUCT_SALERATE)+getResources().getString(R.string.rupee));
// map.put(INTEREST_ACCEPT_LOCATION, c.getString(INTEREST_ACCEPT_LOCATION));
// adding HashList to ArrayList
data.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return data;
}
protected void onPostExecute(ArrayList<HashMap<String,String>> result) {
super.onPostExecute(result);
// dismiss the dialog after getting all albums
if (pDialog.isShowing())
pDialog.dismiss();
// updating UI from Background Thread
aList = new ArrayList<HashMap<String, String>>();
aList.addAll(result);
adapter = new CustomAdapterTabone(getApplicationContext(),result);
setListAdapter(adapter);
aList.addAll(result);
adapter.notifyDataSetChanged();
}
}
CustomAdapter
public class CustomAdapterTabone extends BaseAdapter{
private Context context;
private ArrayList<HashMap<String,String>> listData;
private AQuery aQuery;
private static final String TAG_NAME="product_name";
private static final String TAG_PROFILE="skucode";
private static final String TAG_IMAGE="product_photo";
private static final String TAG_CAST="weight";
private static final String TAG_AGE="sale_rate";
// private static final String TAG_LOCATION="weight";
public CustomAdapterTabone(Context context,ArrayList<HashMap<String,String>> listData) {
this.context = context;
this.listData=listData;
aQuery = new AQuery(this.context);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.list_item_tabone, null);
holder.propic = (ImageView) convertView.findViewById(R.id.propicaccept);
holder.txtproname = (TextView) convertView.findViewById(R.id.txtpronameacptedlist);
holder.txtproid = (TextView) convertView.findViewById(R.id.txtproidacptedlist);
holder.txtprofilecast = (TextView) convertView.findViewById(R.id.txtprofilecastacptedlist);
holder.txtprofileage = (TextView) convertView.findViewById(R.id.txtprofileageacptedlist);
// holder.txtprofileplace = (TextView) convertView.findViewById(R.id.txtprofileplaceacptedlist);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.txtproname.setText(listData.get(position).get(TAG_NAME));
holder.txtproid.setText(listData.get(position).get(TAG_PROFILE));
holder.txtprofilecast.setText(listData.get(position).get(TAG_CAST));
holder.txtprofileage.setText(listData.get(position).get(TAG_AGE));
//holder.txtprofileplace.setText(listData.get(position).get(TAG_LOCATION));
aQuery.id(holder.propic).image(listData.get(position).get(TAG_IMAGE),true,true,0,R.drawable.ic_launcher);
// image parameter : 1 : memory cache,2:file cache,3:target width,4:fallback image
return convertView;
}
class ViewHolder{
ImageView propic;
TextView txtproname;
TextView txtproid;
TextView txtprofilecast;
TextView txtprofileage;
TextView txtprofileplace;
}
}

First create a custom adapter implements filterable:
public class MyFilterableAdapter extends BaseAdapter implements Filterable {
private Context context;
private List<String> items;
private List<String> filteredItems;
private ItemFilter mFilter = new ItemFilter();
public MyFilterableAdapter(Context context, List<String> items) {
//super(context, R.layout.your_row, items);
this.context = context;
this.items = items;
this.filteredItems = items;
}
#Override
public int getCount() {
return filteredItems.size();
}
#Override
public Object getItem(int position) {
return filteredItems.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.row_search_merchant, parent, false);
viewHolder = new ViewHolder();
viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tv_title);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
String location = filteredItems.get(position);
if (!location.isEmpty() || viewHolder != null) {
viewHolder.tvTitle.setText(location);
}
return convertView;
}
public static class ViewHolder {
TextView tvTitle;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
int count = items.size();
final List<String> tempItems = new ArrayList<>(count);
for (int i = 0; i < count; i++) {
if (items.get(i).toLowerCase().contains(filterString)) {
tempItems.add(items.get(i));
}
}
results.values = tempItems;
results.count = tempItems.size();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredItems = (ArrayList<String>) results.values;
notifyDataSetChanged();
}
}
public Filter getFilter() {
return mFilter;
}
}
And than create a textwatcher
public class MyTextWatcher implements TextWatcher {
private MyCustomAdapter lAdapter;
public MyTextWatcher(MyCustomAdapter lAdapter) {
this.lAdapter = lAdapter;
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
lAdapter.getFilter().filter(s.toString().toLowerCase());
}
}
And finally add your TextWatcher to your Search Edit Text:
final MyCustomAdapter lAdapter = new MyCustomAdapter(context, items);
EditText etSearch = (EditText) view.findViewById(R.id.et_search);
etSearch.addTextChangedListener(new SearchTextWatcher(lAdapter));
I hope this'll help you.

Related

Filter returns empty listview

Hi I am trying a search/filter app where data are coming from mySql database to fill up the listview. The populating of listview is working perfectly fine, except for the filtering part. It doesn't filter the listview, it's empty. Help please.
MAIN Activity:
public class MainActivity extends Activity {
public static final String url = "";
// Declare Variables
ListView list;
ListViewAdapter adapter;
EditText editsearch;
String[] rank;
String[] country;
String[] population;
ArrayList<WorldPopulation> arraylist = new ArrayList<WorldPopulation>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Generate list View from ArrayList
displayListView();
// Locate the ListView in listview_main.xml
list = (ListView) findViewById(R.id.listview);
// Pass results to ListViewAdapter Class
adapter = new ListViewAdapter(this, arraylist);
// Binds the Adapter to the ListView
list.setAdapter(adapter);
// Locate the EditText in listview_main.xml
editsearch = (EditText) findViewById(R.id.search);
// Capture Text in EditText
editsearch.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = editsearch.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
#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) {
// TODO Auto-generated method stub
}
});
}
private void displayListView() {
// Creating volley request obj
StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>(){
#Override
public void onResponse(String response) {
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void parseData(String json) {
JSONArray items = null;
JSONObject jsonObject=null;
try {
jsonObject = new JSONObject(json);
items = jsonObject.getJSONArray("result");
rank = new String[items.length()];
country = new String[items.length()];
population = new String[items.length()];
for (int i = 0; i < items.length(); i++) {
JSONObject jo = items.getJSONObject(i);
rank[i] = jo.getString("rank");
country[i] = jo.getString("country");
population[i] = jo.getString("population");
WorldPopulation wp = new WorldPopulation(rank[i], country[i],
population[i]);
// Binds all strings into an array
arraylist.add(wp);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
BASE Adapter:
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<WorldPopulation> worldpopulationlist = null;
private ArrayList<WorldPopulation> arraylist;
public ListViewAdapter(Context context, List<WorldPopulation> worldpopulationlist) {
mContext = context;
this.worldpopulationlist = worldpopulationlist;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<WorldPopulation>();
this.arraylist.addAll(worldpopulationlist);
}
public class ViewHolder {
TextView rank;
TextView country;
TextView population;
}
#Override
public int getCount() {
return worldpopulationlist.size();
}
#Override
public WorldPopulation getItem(int position) {
return worldpopulationlist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listview_item, null);
// Locate the TextViews in listview_item.xml
holder.rank = (TextView) view.findViewById(R.id.rank);
holder.country = (TextView) view.findViewById(R.id.country);
holder.population = (TextView) view.findViewById(R.id.population);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
holder.rank.setText(worldpopulationlist.get(position).getRank());
holder.country.setText(worldpopulationlist.get(position).getCountry());
holder.population.setText(worldpopulationlist.get(position).getPopulation());
// Listen for ListView Item Click
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Send single item click data to SingleItemView Class
Intent intent = new Intent(mContext, SingleItemView.class);
// Pass all data rank
intent.putExtra("rank",(worldpopulationlist.get(position).getRank()));
// Pass all data country
intent.putExtra("country",(worldpopulationlist.get(position).getCountry()));
// Pass all data population
intent.putExtra("population",(worldpopulationlist.get(position).getPopulation()));
// Pass all data flag
// Start SingleItemView Class
mContext.startActivity(intent);
}
});
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
worldpopulationlist.clear();
if (charText.length() == 0) {
worldpopulationlist.addAll(arraylist);
}
else
{
for (WorldPopulation wp : arraylist)
{
if (wp.getCountry().toLowerCase(Locale.getDefault()).contains(charText))
{
worldpopulationlist.add(wp);
}
}
}
notifyDataSetChanged();
}
And the model:
public class WorldPopulation {
private String rank;
private String country;
private String population;
public WorldPopulation(String rank, String country, String population) {
this.rank = rank;
this.country = country;
this.population = population;
}
public String getRank() {
return this.rank;
}
public String getCountry() {
return this.country;
}
public String getPopulation() {
return this.population;
}
}

Issue with adding addTextChangedListener in adapter

I'm trying to implement a search function in my application. I have used an adapter to because I want to display 2 textviews in listview and listview should be clickable (I don;t think it's possible to do without an adapter).
My problem is I can't use addTextChangedListener in the adapter class. it gives exception (It worked in my activity class).
search activity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_results_activity);
new SearchMenuAsyncTask(getApplicationContext(), this).execute();
listtv = (LinearLayout) findViewById(R.id.product_lv);
lv = (ListView) findViewById(R.id.list_view);
inputSearch = (EditText) findViewById(R.id.inputSearch);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
System.out.println("Text ["+s+"]");
adapter.getFilter().filter(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
#Override
public void onTaskCompleted(JSONArray responseJson) {
try {
final List<String> descriptions = new ArrayList<String>();
final List<String> menudescriptions = new ArrayList<String>();
for (int i = 0; i < responseJson.length(); ++i) {
final JSONObject object = responseJson.getJSONObject(i);
if ((object.getString("MainCategoryID")).equals("5")
&& (object.getString("SubCategoryID")).equals("6")
&& (object.getString("Visible")).equals("true")) {
Log.i("descriptionsBev ", object.getString("Description"));
descriptions.add(object.getString("Description"));
Log.i("MenuDescription ",
object.getString("MenuDescription"));
menudescriptions
.add(object.getString("MenuDescription"));
}
adapter = new CustomListSearch(
getApplicationContext(), descriptions,
menudescriptions);
lv.setAdapter(adapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
CustomListSearch.java
public class CustomListSearch extends BaseAdapter implements Filterable {
private Context context;
private final List<String> descriptions;
private List<String>filteredData = null;
private final List<String> menudescriptions;
private ItemFilter mFilter = new ItemFilter();
private LayoutInflater mInflater;
ArrayAdapter<String> adapter;
public CustomListSearch(Context c, List<String> data,
List<String> menudescriptions) {
this.context = c;
this.filteredData = data ;
this.descriptions = data;
this.menudescriptions = menudescriptions;
mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return filteredData.size();
}
#Override
public Object getItem(int position) {
return filteredData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder {
private TextView tvMenudescriptions;
private TextView tvDescriptions;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(
R.layout.search_list_item, parent, false);
holder.tvDescriptions = (TextView) convertView
.findViewById(R.id.product_name);
holder.tvMenudescriptions = (TextView) convertView
.findViewById(R.id.product_description);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tvDescriptions.setText(descriptions.get(position));
holder.tvMenudescriptions.setText(menudescriptions.get(position));
LinearLayout itemlist = (LinearLayout) convertView
.findViewById(R.id.product_lv);
itemlist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, "Still under constructions...",
Toast.LENGTH_LONG).show();
}
});
return convertView;
}
#Override
public Filter getFilter() {
// TODO Auto-generated method stub
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 = descriptions;
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();
}
}
}
I was following below answer and worked this out
Custom Listview Adapter with filter Android

Loading the filtered items to search output

I have implement search for my application. For that I have used an adapter as well. I have loaded 30 items to the search screen. When I pressed letter z to search, then letter z belongs to 4 items out of 30 items in the list.
According to the below shown code it identifies the number 4 and shows the first 4 items out of the 30 items. When I debug inside getFilter(), it shows the filtered items correctly(I have provided a screen shot).
My problem is how can I load the filtered items. Bit confused here.
search.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_results_activity);
new SearchMenuAsyncTask(getApplicationContext(), this).execute();
listtv = (LinearLayout) findViewById(R.id.product_lv);
lv = (ListView) findViewById(R.id.list_view);
inputSearch = (EditText) findViewById(R.id.inputSearch);
lv.setTextFilterEnabled(true);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
System.out.println("Text ["+s+"]");
adapter.getFilter().filter(s.toString());
TextView headerTV = (TextView) findViewById(R.id.search_header);
headerTV.setText("SEARCH RESULTS");
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
#Override
public void onTaskCompleted(JSONArray responseJson) {
try {
final List<String> menudescriptions = new ArrayList<String>();
for (int i = 0; i < responseJson.length(); ++i) {
final JSONObject object = responseJson.getJSONObject(i);
if ((object.getString("MainCategoryID")).equals("1")
&& (object.getString("SubCategoryID")).equals("1")
&& (object.getString("Visible")).equals("true")) {
Log.i("descriptionsTop ", object.getString("Description"));
descriptions.add(object.getString("Description"));
Log.i("MenuDescription ",
object.getString("MenuDescription"));
menudescriptions
.add(object.getString("MenuDescription"));
}
adapter = new CustomListSearch(
getApplicationContext(), descriptions,
menudescriptions);
lv.setAdapter(adapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
CustomListSearch.java
public class CustomListSearch extends BaseAdapter implements Filterable {
private Context context;
List<String> descriptions;
private List<String>filteredDescriptions;
private final List<String> menudescriptions;
private ItemFilter mFilter = new ItemFilter();
private LayoutInflater mInflater;
ArrayAdapter<String> adapter;
public CustomListSearch(Context c, List<String> data,
List<String> menudescriptions) {
this.context = c;
this.filteredDescriptions = data ;
this.descriptions = data;
this.menudescriptions = menudescriptions;
mInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return filteredDescriptions.size();
}
#Override
public Object getItem(int position) {
return filteredDescriptions.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder {
private TextView tvMenudescriptions;
private TextView tvDescriptions;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(
R.layout.search_list_item, parent, false);
holder.tvDescriptions = (TextView) convertView
.findViewById(R.id.product_name);
holder.tvMenudescriptions = (TextView) convertView
.findViewById(R.id.product_description);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tvDescriptions.setText(descriptions.get(position));
holder.tvMenudescriptions.setText(menudescriptions.get(position));
LinearLayout itemlist = (LinearLayout) convertView
.findViewById(R.id.product_lv);
itemlist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, "Still under constructions...",
Toast.LENGTH_LONG).show();
}
});
return convertView;
}
#Override
public Filter getFilter() {
// TODO Auto-generated method stub
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 = descriptions;
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) {
filteredDescriptions = (ArrayList<String>) results.values;
notifyDataSetChanged();
}
}
}
Screen shot
To filter adapter that contains list of custom object
Create a Object:
public class TvObject {
String name;
String description;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
After:
public class CustomListSearch extends BaseAdapter implements Filterable {
private Context context;
private ItemFilter mFilter = new ItemFilter();
private LayoutInflater mInflater;
private List<TvObject> mListTvObject = new ArrayList<>();
private List<TvObject> mListTvObjectFiltered = new ArrayList<>();
public CustomListSearch(Context c, List<TvObject> mListTvObject) {
this.context = c;
mInflater = LayoutInflater.from(context);
this.mListTvObject = mListTvObject;
this.mListTvObjectFiltered = mListTvObject;
}
#Override
public int getCount() {
return mListTvObjectFiltered.size();
}
#Override
public Object getItem(int position) {
return mListTvObjectFiltered.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder {
private TextView tvMenudescriptions;
private TextView tvDescriptions;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.search_list_item, parent, false);
holder.tvDescriptions = (TextView) convertView.findViewById(R.id.product_name);
holder.tvMenudescriptions = (TextView) convertView.findViewById(R.id.product_description);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tvDescriptions.setText(mListTvObjectFiltered.get(position).getName());
holder.tvMenudescriptions.setText(mListTvObjectFiltered.get(position).getDescription());
LinearLayout itemlist = (LinearLayout) convertView.findViewById(R.id.product_lv);
itemlist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, "Still under constructions...",Toast.LENGTH_LONG).show();
}
});
return convertView;
}
#Override
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();
int count = mListTvObject.size();
final ArrayList<TvObject> mListResult = new ArrayList<>();
String name;
for (int i = 0; i < count; i++) {
TvObject mTvObject = mListTvObject.get(i);
name = mTvObject.getName();
if (name.toLowerCase().contains(filterString)) {
mListResult.add(mTvObject);
}
}
results.values = mListResult;
results.count = mListResult.size();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, Filter.FilterResults results) {
mListTvObjectFiltered = (ArrayList<TvObject>) results.values;
notifyDataSetChanged();
}
}
}
Edited:
In your Activity do something like this!
try {
final List<TvObject > mListObjects = new ArrayList<>();
for (int i = 0; i < responseJson.length(); ++i) {
final JSONObject object = responseJson.getJSONObject(i);
if ((object.getString("MainCategoryID")).equals("1")
&& (object.getString("SubCategoryID")).equals("1")
&& (object.getString("Visible")).equals("true")) {
Log.i("descriptionsTop ", object.getString("Description"));
Log.i("MenuDescription ", object.getString("MenuDescription"));
TvObject mTvObject = new TvObject();
mTvObject.setName(object.getString("Description"));
mTvObject.setDescription(object.getString("MenuDescription"));
mListObjects.add(mTvObject);
}
adapter = new CustomListSearch( getApplicationContext(), mListObjects);
lv.setAdapter(adapter);
}
} catch (JSONException e) {
e.printStackTrace();
}

Android search in Listview using baseadapter

I try to add search list form City list using my base adapter but it doesn't work. I want to search City in cities list. Here's My code.
My CitySerach :
private ProgressDialog pDialog;
EditText inputSearch;
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// Hashmap for ListView
ArrayList<HashMap<String, String>> CitiesLI = new ArrayList<HashMap<String, String>>();
// url to make request
private static String url_cityli = "http://10.0.2.2/Myweb/ecities.php";
// JSON Keys
public static final String TAG_CITEMS_LI = "cities_li";
public static final String TAG_CID_LI = "city_id";
public static final String TAG_CNAME_LI = "city_name";
public static final String TAG_CIMG_LI = "image";
JSONArray cities_li = null;
ListView list;
CitySearchAdapter adapter;
private CitySearch activity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tt);
CitiesLI = new ArrayList<HashMap<String, String>>();
new Activity().execute();
activity = this;
list = (ListView) findViewById(R.id.city_list);
//list click to details view of the place
list.setOnItemClickListener(new OnItemClickListener() {
//#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String cid_li = ((TextView) view.findViewById(R.id.cid_li)).getText().toString();
Intent i = new Intent(getApplicationContext(),
//Tab.class);
CityInfoActivity.class);
// Starting new intent
i.putExtra(TAG_CID_LI, cid_li);
startActivity(i);
//startActivityForResult(i, 100);
}
});
}
public void SetListViewAdapter(ArrayList<HashMap<String, String>> daftar) {
adapter = new CitySearchAdapter(activity, daftar);
list.setAdapter(adapter);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 100) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
class Activity extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CitySearch.this);
pDialog.setMessage("Please Wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONArray json = jParser.makeHttpRequest(url_cityli, "GET",
params);
Log.d("All Products: ", json.toString());
// looping through All data
try {
cities_li = json;
for (int i = 0; i < cities_li.length(); i++) {
JSONObject c = cities_li.getJSONObject(i);
// Storing each json item in variable
String city_id = c.getString(TAG_CID_LI);
String city_name =c.getString(TAG_CNAME_LI);
String image = c.getString(TAG_CIMG_LI);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
//JSON Object
map.put(TAG_CID_LI, city_id);
map.put(TAG_CNAME_LI,city_name);
map.put(TAG_CIMG_LI, image);
// adding HashList to ArrayList
CitiesLI.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
SetListViewAdapter(CitiesLI);
//
// Enabling Search Filter
CitySearchAdapter adapter;
inputSearch = (EditText) findViewById(R.id.inputSearch);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Listview name of the class
CitySearch.this.adapter.getFilter().filter(s);
}
#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
}
});
}
});
}
}
}
Here my CitylistAdapter :
public class CitySearchAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
public CitySearchAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.te, null);
TextView city_id = (TextView) vi.findViewById(R.id.cid_li);
TextView image = (TextView) vi.findViewById(R.id.cimg_li);
TextView city_name = (TextView) vi.findViewById(R.id.cname);
ImageView thumb_image = (ImageView) vi.findViewById(R.id.cimage);
HashMap<String, String> city_li = new HashMap<String, String>();
city_li = data.get(position);
city_id.setText(city_li.get(CityActivity.TAG_CID_LI));
image.setText(city_li.get(CityActivity.TAG_CIMG_LI));
city_name.setText(city_li.get(CityActivity.TAG_CNAME_LI));
imageLoader.DisplayImage(city_li.get(CityActivity.TAG_CIMG_LI),thumb_image);
return vi;
}
public Object getFilter() {
// TODO Auto-generated method stub
return null;
}
}
Pleace Help me.
Thanks all

Custom Listadapter Filterable no results

I am struggling with this problem for a while now. I am building a filterable list with edittext. The list populated fine initially BUT once I type something in the edittext field. The whole list is gone and returns no results. The following are my codes.
Note: My codes are mainly based on sacoskun's post.
ThreedListViewActivity.java
public class ThreedListViewActivity extends ActionBarActivity
{
// All static variables
static final String URL = "http://api.androidhive.info/music/music.xml";
// XML node keys
static final String KEY_SONG = "song"; // parent node
static final String KEY_ID = "id";
static final String KEY_TITLE = "title";
static final String KEY_ARTIST = "artist";
static final String KEY_DURATION = "duration";
static final String KEY_THUMB_URL = "thumb_url";
ListView list;
ThreedListAdapterFilterable adapter;
ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
EditText filterText = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.threed_listview);
setTitle(R.string.view_3d);
list=(ListView)findViewById(R.id.list);
adapter = new ThreedListAdapterFilterable(this, songsList);
new MyAsyncTask().execute();
filterText = (EditText) findViewById(R.id.search_box);
filterText.addTextChangedListener(filterTextWatcher);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
adapter.getFilter().filter(s.toString());
}
};
public class MyAsyncTask extends AsyncTask<Void,Void,Void>{
private final ProgressDialog dialog=new ProgressDialog(ThreedListViewActivity.this);
#Override
protected Void doInBackground(Void... params) {
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML from URL
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_SONG);
// looping through all song nodes <song>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_ID, parser.getValue(e, KEY_ID));
map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
map.put(KEY_ARTIST, parser.getValue(e, KEY_ARTIST));
map.put(KEY_DURATION, parser.getValue(e, KEY_DURATION));
map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));
// adding HashList to ArrayList
songsList.add(map);
}
return null;
}
#Override
protected void onPreExecute()
{
dialog.setMessage("Loading ...");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected void onPostExecute(Void result)
{
if(dialog.isShowing() == true)
{
dialog.dismiss();
}
// Getting adapter by passing xml data ArrayList
list.setAdapter(adapter);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.action_items, menu);
return true;
}
}
ThreedListAdapterFilterable.java
public class ThreedListAdapterFilterable extends BaseAdapter implements Filterable {
private Activity activity;
ArrayList<HashMap<String, String>> mDataShown;
ArrayList<HashMap<String, String>> mAllData;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public ThreedListAdapterFilterable(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
mDataShown= (ArrayList<HashMap<String, String>>) d;
mAllData = (ArrayList<HashMap<String, String>>) mDataShown.clone();
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return mDataShown.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.threed_listrow, null);
TextView title = (TextView)vi.findViewById(R.id.title); // title
TextView artist = (TextView)vi.findViewById(R.id.artist); // artist name
TextView duration = (TextView)vi.findViewById(R.id.duration); // duration
ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image
HashMap<String, String> song = new HashMap<String, String>();
song = mDataShown.get(position);
// Setting all values in listview
title.setText(song.get(ThreedListViewActivity.KEY_TITLE));
artist.setText(song.get(ThreedListViewActivity.KEY_ARTIST));
duration.setText(song.get(ThreedListViewActivity.KEY_DURATION));
imageLoader.DisplayImage(song.get(ThreedListViewActivity.KEY_THUMB_URL), thumb_image);
return vi;
}
public Filter getFilter() {
Filter nameFilter = new Filter() {
#SuppressWarnings("unchecked")
#Override
public String convertResultToString(Object resultValue) {
return ((HashMap<String, String>)(resultValue)).get(ThreedListViewActivity.KEY_TITLE);
}
#Override
protected FilterResults performFiltering(CharSequence s) {
if(s != null)
{
ArrayList<HashMap<String, String>> tmpAllData = mAllData;
ArrayList<HashMap<String, String>> tmpDataShown = mDataShown;
tmpDataShown.clear();
for(int i = 0; i < tmpAllData.size(); i++)
{
if(tmpAllData.get(i).get(ThreedListViewActivity.KEY_TITLE).toLowerCase().startsWith(s.toString().toLowerCase()))
{
tmpDataShown.add(tmpAllData.get(i));
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = tmpDataShown;
filterResults.count = tmpDataShown.size();
return filterResults;
}
else
{
return new FilterResults();
}
}
#Override
protected void publishResults(CharSequence s,
FilterResults results) {
if(results != null && results.count > 0)
{
notifyDataSetChanged();
}
}};
return nameFilter;
}
}
EDIT:
This is an updated adapter that will filter my list. BUT, it doesnt update my list when I backspace the text in the input text.
public class ProjectListAdapter extends BaseAdapter implements Filterable{
private Activity activity;
ArrayList<HashMap<String, String>> mDataShown;
ArrayList<HashMap<String, String>> mAllData;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
HashMap<String, String> song = new HashMap<String, String>();
ArrayList<HashMap<String, String>> filteredItems;
public ProjectListAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
mDataShown= (ArrayList<HashMap<String, String>>) d;
mAllData = (ArrayList<HashMap<String, String>>) mDataShown.clone();
filteredItems = mDataShown;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mDataShown.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 position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi;
if(convertView==null){
vi=new View(activity);
vi = inflater.inflate(R.layout.recents_listrow, null);
}else{
vi = (View)convertView;
}
TextView title = (TextView)vi.findViewById(R.id.title); // title
TextView artist = (TextView)vi.findViewById(R.id.company); // artist name
ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image
title.setText(filteredItems.get(position).get(RecentsFragment.KEY_TITLE));
artist.setText(filteredItems.get(position).get(RecentsFragment.KEY_COMPANY));
imageLoader.DisplayImage(filteredItems.get(position).get(RecentsFragment.KEY_THUMB_URL), thumb_image);
return vi;
}
public Filter getFilter() {
Filter nameFilter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
if(constraint != null && constraint.toString().length() > 0) {
constraint = constraint.toString().toUpperCase();
ArrayList<HashMap<String, String>> filt = mDataShown;
ArrayList<HashMap<String, String>> tmpItems = mAllData;
filt.clear();
for(int i = 0; i < tmpItems.size(); i++) {
if(tmpItems.get(i).get(RecentsFragment.KEY_TITLE).toLowerCase().startsWith(constraint.toString().toLowerCase()))
{
filt.add(tmpItems.get(i));
}
}
FilterResults filterResults = new FilterResults();
filterResults.count = filt.size();
filterResults.values = filt;
return filterResults;
}else{
return new FilterResults();
}
}
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
mDataShown = (ArrayList<HashMap<String, String>>)results.values;
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
return nameFilter;
}
}
The list fragment i am trying to implement: RecentsFragment
public class RecentsFragment extends ListFragment {
// All static variables
static final String URL = "http://www.sundancepost.com/ivue/projects.xml";
// XML node keys
static final String KEY_PROJECT = "project"; // parent node
static final String KEY_TITLE = "title";
static final String KEY_COMPANY = "company";
static final String KEY_THUMB_URL = "thumb_url";
int mCurCheckPosition = 0;
ListView list;
ProjectListAdapter adapter;
ArrayList<HashMap<String, String>> projectsList = new ArrayList<HashMap<String, String>>();
EditText filterText = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.recents_list, container, false);
list = (ListView)view.findViewById(android.R.id.list);
filterText = (EditText)view.findViewById(R.id.filter_box);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if(null == savedInstanceState){
ConnectivityManager cMgr = (ConnectivityManager)getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
if (cMgr.getActiveNetworkInfo() != null && cMgr.getActiveNetworkInfo().isConnectedOrConnecting()) {
new MyAsyncTask().execute();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Please check your internet connection");
builder.setTitle("Failed to download resources");
builder.setCancelable(false);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
return;
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
adapter = new ProjectListAdapter(getActivity(), projectsList);
list.requestFocus();
list.setTextFilterEnabled(true);
filterText.addTextChangedListener(filterTextWatcher);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(getActivity(), DetailsActivity.class);
intent.putExtra("title",projectsList.get(position).get(KEY_TITLE));
intent.putExtra("company", projectsList.get(position).get(KEY_COMPANY));
startActivity(intent);
}
});
}
#Override
public void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putInt("workaround", mCurCheckPosition);
}
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
adapter.getFilter().filter(s);
}
};
#Override
public void onDestroy() {
super.onDestroy();
filterText.removeTextChangedListener(filterTextWatcher);
}
public class MyAsyncTask extends AsyncTask<Void,Void,Void>{
private final ProgressDialog recents_dialog = new ProgressDialog(getActivity());
#Override
protected Void doInBackground(Void... params) {
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML from URL
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_PROJECT);
// looping through all song nodes <song>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
map.put(KEY_COMPANY, parser.getValue(e, KEY_COMPANY));
map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));
// adding HashList to ArrayList
projectsList.add(map);
}
return null;
}
#Override
protected void onPreExecute()
{
projectsList.clear();
recents_dialog.setMessage("Loading ...");
recents_dialog.show();
recents_dialog.setCancelable(false);
}
#Override
protected void onPostExecute(Void result)
{
if(recents_dialog.isShowing() == true)
{
recents_dialog.dismiss();
}
// Getting adapter by passing xml data ArrayList
list.setAdapter(adapter);
}
}
}
public class FriendsListActivity extends Activity implements OnClickListener {
private Handler mHandler;
static final String KEY_ID = "id";
static final String KEY_NAME = "name";
static final String KEY_INSTALLED = "installed";
static final String KEY_THUMB_URL = "picture";
protected ListView friendsList;
protected static JSONArray jsonArray;
FriendsListAdapter adapter;
ArrayList> friendslist;
EditText filterText;
String apiResponse;
Button play, invite;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.friends_list);
friendslist = new ArrayList<HashMap<String, String>>();
mHandler = new Handler();
ActionBar actionBar = (ActionBar) findViewById(R.id.actionbar);
actionBar.setTitle("Facebook Friends");
actionBar.setHomeAction(new IntentAction(this, TruthorDareActivity
.createIntent(this), R.drawable.ic_home));
friendsList = (ListView) findViewById(R.id.friendsList);
filterText = (EditText) findViewById(R.id.searchBox);
filterText.addTextChangedListener(filterTextWatcher);
friendsList.setTextFilterEnabled(true);
friendsList.requestFocus();
play = (Button) findViewById(R.id.play);
invite = (Button) findViewById(R.id.invite);
play.setOnClickListener(this);
invite.setOnClickListener(this);
Bundle extras = getIntent().getExtras();
apiResponse = extras.getString("API_RESPONSE");
callPlayList();
}
#Override
public void onBackPressed() {
super.onBackPressed();
this.finish();
}
#Override
protected void onResume() {
super.onResume();
friendsList.requestFocus();
}
public void callPlayList() {
try {
jsonArray = new JSONObject(apiResponse).getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json_data = jsonArray.getJSONObject(i);
if (json_data.has("installed")
&& json_data.getBoolean("installed") == true) {
HashMap<String, String> map = new HashMap<String, String>();
map.put(KEY_ID, json_data.getString("id"));
map.put(KEY_NAME, json_data.getString("name"));
map.put(KEY_THUMB_URL, json_data.getString("picture"));
map.put(KEY_INSTALLED, json_data.getString("installed"));
friendslist.add(map);
}
}
} catch (JSONException e) {
showToast("Error: " + e.getMessage());
return;
}
adapter = new FriendsListAdapter(FriendsListActivity.this, friendslist);
friendsList.setAdapter(adapter);
}
public void callInviteList() {
try {
jsonArray = new JSONObject(apiResponse).getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json_data = jsonArray.getJSONObject(i);
if (!json_data.has("installed")) {
HashMap<String, String> map = new HashMap<String, String>();
map.put(KEY_ID, json_data.getString("id"));
map.put(KEY_NAME, json_data.getString("name"));
map.put(KEY_THUMB_URL, json_data.getString("picture"));
map.put(KEY_INSTALLED, "false");
friendslist.add(map);
}
}
} catch (JSONException e) {
showToast("Error: " + e.getMessage());
return;
}
adapter = new FriendsListAdapter(FriendsListActivity.this, friendslist);
friendsList.setAdapter(adapter);
}
public void clearAdapter(String params) {
friendslist.clear();
adapter.notifyDataSetChanged();
adapter.notifyDataSetInvalidated();
if (params.equals("invite")) {
callInviteList();
} else {
callPlayList();
}
}
public class PostDialogListener extends BaseDialogListener {
#Override
public void onComplete(Bundle values) {
final String postId = values.getString("post_id");
if (postId != null) {
showToast("Message posted on the wall.");
} else {
showToast("No message posted on the wall.");
}
}
}
public void showToast(final String msg) {
mHandler.post(new Runnable() {
#Override
public void run() {
Toast toast = Toast.makeText(FriendsListActivity.this, msg,
Toast.LENGTH_LONG);
toast.show();
}
});
}
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
adapter.getFilter().filter(s);
}
};
#Override
protected void onDestroy() {
super.onDestroy();
filterText.removeTextChangedListener(filterTextWatcher);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.play:
clearAdapter("play");
break;
case R.id.invite:
clearAdapter("invite");
break;
default:
break;
}
}
}
The next part is the adapter class I use in a separate class file.
public class FriendsListAdapter extends BaseAdapter implements Filterable {
private Activity activity;
public ArrayList<HashMap<String, String>> data;
public ArrayList<HashMap<String, String>> allData;
public HashMap<String, String> friends;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
private ItemsFilter mFilter;
static SharedPreferences TODLoginPrefs;
#SuppressWarnings({ "unchecked", "static-access" })
public FriendsListAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data = (ArrayList<HashMap<String, String>>) d;
allData = (ArrayList<HashMap<String, String>>) data.clone();
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext());
TODLoginPrefs = activity.getSharedPreferences("LogInSession",
activity.MODE_PRIVATE);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.friends_list_row, null);
TextView user = (TextView) vi.findViewById(R.id.gname);
Button play = (Button) vi.findViewById(R.id.btnPlay);
Button invite = (Button) vi.findViewById(R.id.btnInvite);
ImageView thumb_image = (ImageView) vi.findViewById(R.id.list_image);
friends = new HashMap<String, String>();
friends = data.get(position);
user.setText(friends.get(FriendsListActivity.KEY_NAME));
imageLoader.DisplayImage(
friends.get(FriendsListActivity.KEY_THUMB_URL), thumb_image);
final String friendrId = (friends.get(FriendsListActivity.KEY_ID));
final String name = (friends.get(FriendsListActivity.KEY_NAME));
final String installed = (friends
.get(FriendsListActivity.KEY_INSTALLED));
if (installed.equals("false")) {
play.setVisibility(View.GONE);
invite.setVisibility(View.VISIBLE);
}
play.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new AlertDialog.Builder(activity)
.setTitle("Create game with " + name + "?")
.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
UserFunction userFunction = new UserFunction();
JSONObject json_game = userFunction
.newGame(
activity,
"Facebook",
TODLoginPrefs
.getString(
"UserID",
""),
friendrId, null, null);
if (json_game.has("success")) {
activity.startActivity(new Intent(
activity,
TruthorDareActivity.class));
} else {
try {
Toast.makeText(
activity,
json_game
.getString("error_msg"),
Toast.LENGTH_SHORT)
.show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}).setNegativeButton(R.string.no, null).show();
}
});
invite.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new AlertDialog.Builder(activity)
.setTitle("Invite " + name + "?")
.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
UserFunction userFunction = new UserFunction();
JSONObject json_game = userFunction
.newInvite(
activity,
"Facebook",
TODLoginPrefs
.getString(
"UserID",
""),
friendrId, null, null);
if (json_game.has("success")) {
Bundle params = new Bundle();
params.putString("to", friendrId);
params.putString(
"message",
activity.getResources()
.getString(
R.string.app_request_message));
Utilities.facebook.dialog(activity,
"apprequests", params,
new AppRequestsListener());
} else {
try {
Toast.makeText(
activity,
json_game
.getString("error_msg"),
Toast.LENGTH_SHORT)
.show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}).setNegativeButton(R.string.no, null).show();
}
});
return vi;
}
#Override
public Filter getFilter() {
if (mFilter == null) {
mFilter = new ItemsFilter();
}
return mFilter;
}
private class ItemsFilter extends Filter {
#SuppressWarnings("unchecked")
#Override
public String convertResultToString(Object resultValue) {
return ((HashMap<String, String>) (resultValue))
.get(FriendsListActivity.KEY_NAME);
}
#Override
protected FilterResults performFiltering(CharSequence s) {
if (s != null) {
ArrayList<HashMap<String, String>> tmpAllData = allData;
ArrayList<HashMap<String, String>> tmpDataShown = data;
tmpDataShown.clear();
for (int i = 0; i < tmpAllData.size(); i++) {
if (tmpAllData.get(i).get(FriendsListActivity.KEY_NAME)
.toLowerCase()
.startsWith(s.toString().toLowerCase())) {
tmpDataShown.add(tmpAllData.get(i));
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = tmpDataShown;
filterResults.count = tmpDataShown.size();
return filterResults;
} else {
return new FilterResults();
}
}
#SuppressWarnings("unchecked")
protected void publishResults(CharSequence prefix, FilterResults results) {
data = (ArrayList<HashMap<String, String>>) results.values;
if (results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
}
public class AppRequestsListener extends BaseDialogListener {
#Override
public void onComplete(Bundle values) {
Toast.makeText(activity, "App request sent", Toast.LENGTH_SHORT)
.show();
activity.startActivity(new Intent(activity,
TruthorDareActivity.class));
}
#Override
public void onFacebookError(FacebookError error) {
Toast.makeText(activity, "Facebook Error: " + error.getMessage(),
Toast.LENGTH_SHORT).show();
}
#Override
public void onCancel() {
Toast.makeText(activity, "App request cancelled",
Toast.LENGTH_SHORT).show();
}
}
}
In the getFilter() method try this
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
mDataShown = (ArrayList<HashMap<String, String>>)results.values;
ProjectListAdapter.this.setListData(mDataShown);
ProjectListAdapter.this.notifyDataSetChanged();
};
And to refresh the list on backspace
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
if(s.toString().equalsIgnoreCase(""))
{
adapter.setListData(projectListdata)
adapter.notifyDataSetChanged();
}
else
adapter.getFilter().filter(s);
}
};

Categories

Resources