searchview for multicolum listview - android

I am using a ListViewAdapter which extends ArrayAdapter to display results in ListView. I have 3 TextView in the ListView to display the output. I want to implement a searchview but when I type in search bar the screen goes blank. How do I implement it? I tried with addTextChangedListener using EditText also but no output.This is Activity
searchView = (SearchView)findViewById(R.id.searchView);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
});
}
private void loadDescriptionList() {
final ProgressDialog progressDialog = new ProgressDialog(TestDetails.this);
progressDialog.setMessage("Loading Data...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response)
{
progressDialog.dismiss();
try {
JSONObject obj = new JSONObject(response);
JSONArray heroArray = obj.getJSONArray("list");
for (int i = 0; i < heroArray.length(); i++) {
JSONObject heroObject = heroArray.getJSONObject(i);
TDescription hero = new TDescription(heroObject.getString("test_code"), heroObject.getString("test_description"),heroObject.getString("test_price"));
heroList.add(hero);
}
adapter = new ListViewAdapter(heroList, getApplicationContext());
listView.setAdapter(adapter);
} catch (JSONException e) {
progressDialog.dismiss();
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
LISTVIEWADAPTER.JAVA
public class ListViewAdapter extends ArrayAdapter<TDescription> {
private List<TDescription> heroList;
private Context mCtx;
Typeface typeface;
TextView rup;
public ListViewAdapter(List<TDescription> heroList, Context mCtx) {
super(mCtx, R.layout.list_items, heroList);
this.heroList = heroList;
this.mCtx = mCtx;
typeface = Typeface.createFromAsset(mCtx.getAssets(), "fontawesome-webfont.ttf");
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
View listViewItem = inflater.inflate(R.layout.list_items, null, true);
TextView code = (TextView)listViewItem.findViewById(R.id.code);
TextView desc = (TextView)listViewItem.findViewById(R.id.desc);
TextView price = (TextView)listViewItem.findViewById(R.id.price);
rup = (TextView)listViewItem.findViewById(R.id.rupee);
rup.setTypeface(typeface);
TDescription hero = heroList.get(position);
code.setText(hero.getCode());
desc.setText(hero.getDesc());
price.setText(hero.getPrice());
return listViewItem;
}
}
enter image [description]1 here

You have to implement filterable interface to get your result just change your listview adapter class to below code
public class ListViewAdapter extends ArrayAdapter<TDescription> implements Filterable {
private List<TDescription> heroList;
private List<TDescription> mFilterData;
private Context mCtx;
private ItemFilter mFilter = new ItemFilter();
private TextView rup;
public ListViewAdapter(List<TDescription> heroList, Context mCtx) {
super(mCtx, R.layout.list_items, heroList);
this.heroList = heroList;
this.mFilterData = heroList;
this.mCtx = mCtx;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
View listViewItem = inflater.inflate(R.layout.list_items, null, true);
TextView code = (TextView) listViewItem.findViewById(R.id.code);
TextView desc = (TextView) listViewItem.findViewById(R.id.desc);
TextView price = (TextView) listViewItem.findViewById(R.id.price);
rup = (TextView) listViewItem.findViewById(R.id.rupee);
TDescription hero = mFilterData.get(position);
code.setText(hero.getCode());
desc.setText(hero.getDesc());
price.setText(hero.getPrice());
return listViewItem;
}
public int getCount() {
return mFilterData.size();
}
public TDescription getItem(int position) {
return mFilterData.get(position);
}
public long getItemId(int position) {
return position;
}
#NonNull
public Filter getFilter() {
return mFilter;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String userString = constraint.toString().toLowerCase();
FilterResults filterResults = new FilterResults();
final List<TDescription> originalList = heroList;
int count = originalList.size();
final ArrayList<TDescription> resultList = new ArrayList<>(count);
TDescription tDescription;
for (int i = 0; i < count; i++) {
tDescription = originalList.get(i);
if (tDescription.getDesc().toLowerCase().contains(userString)) {
resultList.add(tDescription);
}
}
filterResults.values = resultList;
filterResults.count = resultList.size();
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
mFilterData = (ArrayList<TDescription>) results.values;
notifyDataSetChanged();
}
}
}
it will filter the data based on your description

Related

Search items from listview with custom adapter

Am trying search from listview using custom adapter. i have search widget in toolbar menu and i can display widget. when i click on search icon, it expands, but when i start typing, search does not happen and list gets cleared. can someone plz trace this issue .
Here's my code from Main Activity:
public class VideoActivity extends BaseActivity {
ListView listView;
ArrayList<Video> videoArrayList;
public VideoListAdapter videoListAdapter;
String vid_id, vid_title, vid_type, vid_path, vid_img;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
initializeToolbar();
listView = (ListView) findViewById(R.id.listview_video);
videoArrayList = new ArrayList<Video>();
videoListAdapter = new VideoListAdapter(VideoActivity.this, videoArrayList);
jsonParser = new JSONParser();
new VideoTask().execute();
public class VideoTask extends AsyncTask<String, String, JSONObject> {
#Override
protected JSONObject doInBackground(String... strings) {
jsonObject = jsonParser.makeHttpRequest2(Network_constants.video_list_page, "POST");
Log.e("json data", "" + jsonObject);
return jsonObject;
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
progressDialog.dismiss();
if (jsonObject != null) {
try {
jsonArray = jsonObject.getJSONArray("videos");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
Log.d("jsonObject1", "" + jsonObject1);
Video video = new Video();
vid_id = jsonObject1.getString("video_id");
vid_title = jsonObject1.getString("video_channel_name");
vid_type = jsonObject1.getString("video_channel_link");
vid_path = jsonObject1.getString("video_channel_description");
vid_img = jsonObject1.getString("video_img_path");
video.set_vTitle(vid_title);
TextView t1 = (TextView) findViewById(R.id.video_title);
TextView t2 = (TextView) findViewById(R.id.video_type);
video.set_vArtist(vid_title);
video.set_vType(vid_type);
videoArrayList.add(video);
}
} catch (JSONException e) {
e.printStackTrace();
}
listView.setAdapter(videoListAdapter);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView cnt = (TextView) view.findViewById(R.id.video_type);
String cn = cnt.getText().toString();
Intent i = new Intent(VideoActivity.this, Youtube.class);
i.putExtra("url", cn);
startActivity(i);
}
});
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.clear();
getMenuInflater().inflate(R.menu.main,menu);
MenuItem menuItem = menu.findItem(R.id.menu_search);
final SearchView searchView = (SearchView) menuItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
if(TextUtils.isEmpty(newText)){
LogHelper.e("Query Result","Filter is Empty");
}else{
videoListAdapter.filter(newText);
}
return true;
}
});
return true;
}
}
And this is my CustomAdapter class :
public class VideoListAdapter extends BaseAdapter {
private Activity activity;
private static LayoutInflater inflater = null;
ImageView imageView;
private String mCurrentArtUrl;
private ArrayList<Video> video;
private ArrayList<Video> searchListView = null;
public VideoListAdapter(Activity a, ArrayList<Video> b){
this.activity = a;
this.video = b;
this.searchListView = new ArrayList<Video>();
this.searchListView.addAll(video);
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return video.size();
}
#Override
public Object getItem(int position) {
return video.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.video_list_item, null);
final TextView v_title = (TextView)vi.findViewById(R.id.video_title);
final TextView v_type = (TextView)vi.findViewById(R.id.video_type);
final TextView v_artist = (TextView)vi.findViewById(R.id.video_artist);
imageView = (ImageView) vi.findViewById(R.id.video_image);
Video video1 = video.get(position);
v_title.setText(video1.get_vTitle());
v_type.setText(video1.get_vType());
v_artist.setText(video1.get_vArtist());
String img = video1.get_vImage();
String profile = Network_constants.image_url + img;
fetchImageAsync(profile);
return vi;
}
// Filter method
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
video.clear();
if(charText.length() == 0){
video.addAll(searchListView);
}else{
for(Video v : searchListView){
LogHelper.e("Query","Entered For Loop");
if(v.get_vTitle().contains(charText)){
video.add(v);
}else{
LogHelper.e("Query","Could not create list");
}
}
}
notifyDataSetChanged();
}
}
I think my code is not working with the for loop in the filter function i guess.
You should implements Filterable in your Adapter

Image not match item in listview when search with SearchView Android

I have listview in fragment populated from Activity with bundle , i have custom baseadapter and custom object with image and text , listview work fine with image and text , but when i do search with searchview i can get text and it's position and onclicklistener is ok without any problem, the issue is that i can't have image(logos ) with the correcte item(texttitle) , images is ranged by it's own position and not item text position
First here is my Custom object
public class Channel {
public String name;
public String logoUrl;
public Channel(String name, String logoUrl) {
this.name = name;
this.logoUrl = logoUrl;
}
#Override
public String toString() {
return "Channel {" +
"name='" + name + '\'' +
", logoUrl='" + logoUrl + '\'' +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLogoUrl() {
return logoUrl;
}
public void setLogoUrl(String logoUrl) {
this.logoUrl = logoUrl;
}
}
and here is my custom Base Adapter
public class ChannelAdapter extends BaseAdapter implements Filterable{
private Activity context;
private ArrayList<Channel> channelNames = new ArrayList<>(); //mList
private ArrayList<Channel> channelLogos = new ArrayList<>();
private ArrayList<Channel> tmpNames= null;
private ArrayList<Channel> tmpLogos= null;
private CustomFilter myFilter = new CustomFilter();
ColorSpace.Model model;
public ChannelAdapter(Context context, ArrayList<Channel> channels, ArrayList<Channel> logos){
this.context = (Activity) context;
this.channelNames = channels;
this.channelLogos = logos;
this.tmpNames = channels;
this.tmpLogos = logos;
// Names.addAll(channelLogos);
}
#Override
public int getCount() {
// return Names.size();
return tmpNames.size();
}
#Override
public String getItem(int position) {
return String.valueOf(tmpNames.get(position));
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row =null;
if(convertView==null) {
LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row=inflater.inflate(R.layout.custom_row,parent, Boolean.parseBoolean(null));
}else{
row=convertView;
}
TextView textView= (TextView) row.findViewById(R.id.textv);
ImageView image=(ImageView) row.findViewById(R.id.imageView);
textView.setText((CharSequence) tmpNames.get(position));
Picasso.with(context)
.load(String.valueOf(tmpLogos.get(position)))
.into(image);
return row;
}
#Override
public Filter getFilter() {
if (myFilter == null) {
myFilter = new CustomFilter();
}
return myFilter;
}
public class CustomFilter extends Filter{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
// TODO Auto-generated method stub
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
final ArrayList<Channel> list = channelNames; //remettre channelNames
int count = list.size();
final ArrayList<String> nlist = new ArrayList<String>(count);
String filterableString ;
for (int i = 0; i < count; i++) {
filterableString = String.valueOf(list.get(i));
if (filterableString.toLowerCase().contains(filterString)) {
nlist.add(filterableString);
}
}
results.values = nlist;
results.count = nlist.size();
return results;
}
#Override
protected void publishResults(CharSequence constraint,FilterResults results) {
// TODO Auto-generated method stub
// Names.clear();
// addAll((List<Channel>) results.values);
tmpNames = (ArrayList<Channel>) results.values;
notifyDataSetChanged();
}
}
}
and finaly my OnqueryTextChange
#Override
public boolean onQueryTextChange(String newText) {
((ChannelAdapter)listView.getAdapter()).getFilter().filter(newText.toString());
}
});
Please need help if possible and thank's in advance
here is my adapter class
public class ChannelAdapter extends MatchableArrayAdapter<Channel>{
private Activity context;
private ArrayList<Channel> channelNames = new ArrayList<>(); //mList
private ArrayList<Channel> channelLogos = new ArrayList<>();
private ArrayList<Channel> tmpNames= new ArrayList<Channel>();
private ArrayList<Channel> tmpLogos= null;
boolean notifyChanged = false;
public ChannelAdapter(Context context, ArrayList<Channel> channels,
ArrayList<Channel> logos){
super(context, 0, channels);
this.context = (Activity) context;
this.channelNames = channels;
this.channelLogos = logos;
this.tmpNames = channels;
this.tmpLogos = channels;
// Names.addAll(channelLogos);
}
#Override
public int getCount() {
// return Names.size();
return channelNames.size();
}
#Override
public Channel getItem(int position) {
return channelNames.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row =null;
if(convertView==null) {
LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row=inflater.inflate(R.layout.custom_row,parent, Boolean.parseBoolean(null));
}else{
row=convertView;
}
// TextView textView = null;
TextView textView= (TextView) row.findViewById(R.id.textv);
// ((TextView)row.findViewById(R.id.textv)).getText().toString();
ImageView image=(ImageView) row.findViewById(R.id.imageView);
textView.setText((CharSequence) channelNames.get(position));
Picasso.with(context)
.load(String.valueOf(channelLogos.get(position)))
.into(image);
return row;
}
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
final FilterResults oReturn = new FilterResults();
final ArrayList<Channel> results = new ArrayList<Channel>();
if (channelNames == null)
channelNames = tmpNames;
if (constraint != null) {
if (channelNames != null && channelNames.size() > 0) {
for (final Channel g : channelNames) {
if (g.getName().toLowerCase()
.contains(constraint.toString()))
results.add(g);
}
}
oReturn.values = results;
}
return oReturn;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
tmpNames = (ArrayList<Channel>) results.values;
notifyDataSetChanged();
}
};
}
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
notifyChanged = true;
}
}
public class Channel {
private String name;
private String logoUrl;
public Channel(String name, String logoUrl) {
this.name = name;
this.logoUrl = logoUrl;
}
#Override
public String toString() {
return "Channel{" +
"name='" + name + '\'' +
", logoUrl='" + logoUrl + '\'' +
'}';
}
public String getName() {
return String.valueOf(name);
}
public void setName(ArrayList<String> name) {
this.name = String.valueOf(name);
}
public String getLogoUrl() {
return String.valueOf(logoUrl);
}
public void setLogoUrl(ArrayList<String> logoUrl) {
this.logoUrl = String.valueOf(logoUrl);
}
}
public class ChannelAdapter extends MatchableArrayAdapter<Channel> {
public ChannelAdapter(Context context, List<Channel> objects) {
super(context, R.layout.custom_row, objects);
}
#Override
protected void onBind(Channel item, View itemView, int position) {
TextView tv = (TextView) itemView.findViewById(R.id.textv);
tv.setText(item.getName());
ImageView iv = (ImageView) itemView.findViewById(R.id.imageView);
Picasso.with(iv.getContext())
.load(item.getLogoUrl())
.into(iv);
}
#Override
protected boolean matches(Channel value, CharSequence constraint,
CharSequence lowerCaseConstraint) {
return value.getName().toLowerCase().contains(lowerCaseConstraint);
}
}

AutoCompleteTextView didnt work

now i am using autocompleteTextview for showing suggestion , i get the data from webservice and and i set the adapter.
i dont get an error but when i click the Textview it wont show anything.and then I check the list and its contains the data.
am i doing a mistake here ?
here is my code
<AutoCompleteTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/acCustomer"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/etCustomerOther"
android:layout_marginBottom="10dp"
android:layout_alignLeft="#+id/spCustomer"/>
--class--
private static List<String> customerList;
private class LoadCustomer extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
pBar.setVisibility(View.VISIBLE);
pBar.setIndeterminate(false);
pBar.setClickable(false);
}
#Override
protected Void doInBackground(Void... params) {
try {
RESTClient client = new RESTClient(URLService+"get?method=getallcustomerlist&value=");
client.Execute(RESTClient.RequestMethod.GET);
responseCustomer = client.getResponse();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
try{
responseCustomer = responseCustomer.replace("\\\"","\"");
responseCustomer = responseCustomer.substring(1, responseCustomer.length() - 1);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(responseCustomer);
String Status = jsonObject.get("Status").toString();
if (Status == "true"){
// JSONArray structure = (JSONArray) jsonObject.get("DataList");
String dataku = jsonObject.get("DataList").toString();
try {
dataku = CRYYPT.decrypt(Enc_Pass, dataku);
}catch (GeneralSecurityException e){
//handle error - could be due to incorrect password or tampered encryptedMsg
}
JSONParser parser = new JSONParser();
JSONArray structure = (JSONArray) parser.parse(dataku);
customerList = new ArrayList<String>();
customerList.add("--Choose--");
for (int i = 0; i < structure.size(); i++) {
JSONObject customerlist = (JSONObject) structure.get(i);
customerList.add(customerlist.get("CustomerName").toString());
}
customerList.add("Other");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(WorkflowActivity.this, android.R.layout.simple_list_item_1, customerList);
acCustomer.setAdapter(adapter);
}else {
}
}
catch(Exception e)
{
e.printStackTrace();
}
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
pBar.setClickable(true);
pBar.setVisibility(View.GONE);
}
}
--List Customer Item--
public class ListCustomerItem {
public String CustName;
/*public String CustLocation;
public String CustID;*/
}
--List Customer Adapter--
public class ListCustomerAdapter extends ArrayAdapter<ListCustomerItem> {
public ListCustomerAdapter(Context context, List<ListCustomerItem> items)
{
super(context, R.layout.style_fragment_list_customer, items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if(convertView == null) {
// inflate the GridView item layout
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.style_fragment_list_customer, parent, false);
// initialize the view holder
viewHolder = new ViewHolder();
viewHolder.tvCustName = (TextView) convertView.findViewById(R.id.tvCustName);
// viewHolder.tvCustLocation = (TextView) convertView.findViewById(R.id.tvCustLocation);
convertView.setTag(viewHolder);
} else {
// recycle the already inflated view
viewHolder = (ViewHolder) convertView.getTag();
}
// update the item view
ListCustomerItem item = getItem(position);
viewHolder.tvCustName.setText(item.CustName);
// viewHolder.tvCustLocation.setText(item.CustLocation);
return convertView;
}
private static class ViewHolder {
TextView tvCustName;
TextView tvCustLocation;
}
}
Have you tried using android:completionThreshold="1" inside AutoCompleteTextView?
or called mAutoCompleteTextView.setThreshold(1) to AutoCompleteTextView reference?
mAutoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
Set your AutoCompleteTextView with Custom Adapter
mAutoCompleteTextView.setSelection(0);
mCustomAutoFilterAdapter = new CustomAutoFilterAdapter(this,R.layout.spinner_row, yourList);
mAutoCompleteTextView.setThreshold(1);
mAutoCompleteTextView.setAdapter(mCustomAutoFilterAdapter);
In your Custom Adapter Class include
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(viewResourceId, null);
}
return v;
}
#Override
public Filter getFilter() {
return nameFilter;
}
Filter nameFilter = new Filter() {
#Override
public String convertResultToString(Object resultValue) {
String str = "get your values from resultValue";
return str;
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
if(constraint != null) {
suggestions.clear();
"DO your Activities"
}
FilterResults filterResults = new FilterResults();
filterResults.values = suggestions;
filterResults.count = suggestions.size();
return filterResults;
} else {
return new FilterResults();
}
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
"Do your Activities here"
}
};

Android get data from Listview and show in a new activity

I am new to Android. I called lv.setOnItemClickListener to pick a selected item from ListView and show the data in a new activity through a new intent. But I don't know the could to do this works. I need some help.
MainActivity
public class MainActivity extends Activity implements
SearchView.OnQueryTextListener {
ListView lv;
SearchView search_view;
String[] country_names, iso_codes;
TypedArray country_flags;
ArrayList<Country> countrylist;
CustomAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.list_view);
search_view = (SearchView) findViewById(R.id.search_view);
country_names = getResources().getStringArray(R.array.country_names);
iso_codes = getResources().getStringArray(R.array.iso_Code);
country_flags = getResources().obtainTypedArray(R.array.country_flags);
countrylist = new ArrayList<Country>();
for (int i = 0; i < country_names.length; i++) {
Country country = new Country(country_names[i], iso_codes[i],
country_flags.getResourceId(i, -1));
countrylist.add(country);
}
adapter = new CustomAdapter(getApplicationContext(), countrylist);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
**// I DON'T KNOW WHAT PUT HERE**
}
});
search_view.setOnQueryTextListener(this);
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
}
Country
public class Country {
String name;
int flag;
String iso_code;
Country(String name, String iso_code, int flag) {
this.name = name;
this.iso_code = iso_code;
this.flag = flag;
}
public String getIso_code() {
return iso_code;
}
public void setIso_code(String iso_code) {
this.iso_code = iso_code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getFlag() {
return flag;
}
public void setFlag(int flag) {
this.flag = flag;
}
}
Custom Adapter
public class CustomAdapter extends BaseAdapter implements Filterable {
Context context;
ArrayList<Country> countrylist;
ArrayList<Country> mStringFilterList;
ValueFilter valueFilter;
CustomAdapter(Context context, ArrayList<Country> countrylist) {
this.context = context;
this.countrylist = countrylist;
mStringFilterList = countrylist;
}
#Override
public int getCount() {
return countrylist.size();
}
#Override
public Object getItem(int position) {
return countrylist.get(position);
}
#Override
public long getItemId(int position) {
return countrylist.indexOf(getItem(position));
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = null;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
TextView name_tv = (TextView) convertView.findViewById(R.id.name);
TextView iso_tv = (TextView) convertView.findViewById(R.id.code);
ImageView iv = (ImageView) convertView.findViewById(R.id.flag);
Country country = countrylist.get(position);
name_tv.setText(country.getName());
iso_tv.setText(country.getIso_code());
iv.setImageResource(country.getFlag());
}
return convertView;
}
#Override
public Filter getFilter() {
if (valueFilter == null) {
valueFilter = new ValueFilter();
}
return valueFilter;
}
private class ValueFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint != null && constraint.length() > 0) {
ArrayList<Country> filterList = new ArrayList<Country>();
for (int i = 0; i < mStringFilterList.size(); i++) {
if ((mStringFilterList.get(i).getName().toUpperCase())
.contains(constraint.toString().toUpperCase())) {
Country country = new Country(mStringFilterList.get(i)
.getName(), mStringFilterList.get(i)
.getIso_code(), mStringFilterList.get(i)
.getFlag());
filterList.add(country);
}
}
results.count = filterList.size();
results.values = filterList;
} else {
results.count = mStringFilterList.size();
results.values = mStringFilterList;
}
return results;
}
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
countrylist = (ArrayList<Country>) results.values;
notifyDataSetChanged();
}
}
}
Intent intent=new Intent(getActivity(),StartAnotherActitivity.class);
intent.putExtra(key,value);
startActivity(intent);
http://developer.android.com/reference/android/content/Intent.html
Here are the steps.
Get the position of the item clicked: This value will be passed to the method onItemClick
Now put this value as an Intent extra when you try to start the next activity
Read the index of the clicked item from your next Activity
Fetch the contents of the detail activity
Intent intent = new Intent(MainActivity.this,NewActivity.class);
intent.putExtra("Counttry",countrylist.get(arg2));
startActivity(intent);

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();
}

Categories

Resources