Filter Dynamic listview android - android

Hello i have made a dynamic listview..Now i want to add filter in listview.if i enter text in edittext then item which mathces the search should display..have called addTextChangedListener to my edittext..and called a method filter in my adapter..but m not getting any idea what should i write in my filter method as it is a dynamic listview...
Here is my code:
package com.XXXXX.XXXXX;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.AdapterView.OnItemClickListener;
import com.XXXXX.adapter.UpdateSingleItemViewActivity;
import com.XXXXX.adapter.UpdatesAdapterList;
import com.XXXXX.local.database.DBController;
import com.XXXXX.XXXXX.XXXXX.constant.Constant;
import com.XXXXX.XXXXX.XXXXX.utils.Utility;
public class Cardiology_updates extends Activity implements OnClickListener,
OnRefreshListener {
EditText et ;
private Context appContext;
// ProgressDialog mProgressDialog;
private Dialog dialog;
private boolean isFinish = false;
String result = "";
JSONObject jsonobject;
JSONArray jsonArray;
ArrayList<HashMap<String, String>> UpdatesHmList;
public static ArrayList<HashMap<String, String>> FinalLocalDataList;
ArrayList<HashMap<String, String>> LocalDataList;
DBController controller = new DBController(this);
HashMap<String, String> queryValues;
ListView list;
UpdatesAdapterList adapter;
public static String UpdateID = "UpdateID";
public static String UpdateTitle = "Title";
/*
* public static String UpdateDescription = "Description"; public static
* String POPULATION = "UpdateDate"; public static String UpdateImage =
* "Photo";
*/
public static String UpdateDescription = "Description";
public static String POPULATION = "Title";
public static String UpdateImage = "Complete_imagePath";
public static String Complete_imagePath;
public static String Title;
public static String Description;
SwipeRefreshLayout swipeLayout;
private ProgressBar progressbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cardiology_updates);
// controller.deleteAllJsonData();
appContext = this;
animationView();
initComponent();
}
private void animationView() {
// TODO Auto-generated method stub
progressbar = (ProgressBar) findViewById(R.id.loading);
}
private void initComponent() {
// TODO Auto-generated method stub
swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setColorScheme(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
dialog = new Dialog(appContext);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.alert_dialog);
((Button) findViewById(R.id.Button01)).setOnClickListener(this);
((Button) dialog.findViewById(R.id.btnOk)).setOnClickListener(this);
new GetUpdatesInfo().execute();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.Button01) {
finish();
// finishActivity() ;
} else if (v.getId() == R.id.btnOk) {
dialog.dismiss();
if (isFinish) {
this.finish();
}
}
}
public class GetUpdatesInfo extends AsyncTask<String, Void, String> {
protected void onPreExecute() {
super.onPreExecute();
if (progressbar.getVisibility() != View.VISIBLE) {
progressbar.setVisibility(View.VISIBLE);
}
}
#Override
protected String doInBackground(String... params) {
// Create an array
UpdatesHmList = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
String url = null;
url = Constant.serverUrl + "/GetUpdateList";
result = Utility.postParamsAndfindJSON(url);
Log.e("result doInBackground", "" + result);
if (!(result == null)) {
try {
controller.deleteAllJsonData();
// Locate the array name in JSON
jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonArray.getJSONObject(i);
// Retrive JSON Objects
map.put("UpdateID", jsonobject.getString("UpdateID"));
map.put("Title", jsonobject.getString("Title"));
String Upadates_Photo = jsonobject.optString("Photo")
.toString();
String Complete_imagePath = Constant.prifixserverUrl
+ Upadates_Photo;
String Title = jsonobject.getString("Title").toString();
String Description = jsonobject
.getString("Description").toString();
String noHtml = Description.replaceAll("<[^>]*>", "");
String parseResponse = noHtml.replaceAll(" ", "");
map.put("Photo", Complete_imagePath);
map.put("Description", Description);
map.put("UpdateDate",
jsonobject.getString("UpdateDate"));
Log.e("UpdateID ",
" "
+ jsonobject.getString("UpdateID")
.toString());
Log.e("Title ", " "
+ jsonobject.getString("Title").toString());
Log.e("Complete_imagePath ",
" " + Complete_imagePath.toString());
Log.e("Description ", " " + parseResponse);
Log.e("UpdateDate ",
" "
+ jsonobject.getString("UpdateDate")
.toString());
queryValues = new HashMap<String, String>();
queryValues.put("Complete_imagePath",
Complete_imagePath);
queryValues.put("Title", Title);
queryValues.put("Description", Description);
controller.insertAllJsonData(queryValues);
// Set the JSON Objects into the array
UpdatesHmList.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
return result;
}
#Override
protected void onPostExecute(String result) {
// Locate the listview in listview_main.xml
if (progressbar.getVisibility() == View.VISIBLE) {
progressbar.setVisibility(View.GONE);
}
/*
* if (result == null) { //mProgressDialog.dismiss();
* localalldata();
*
* }
*/
localalldata();
/*
* list = (ListView) findViewById(R.id.list_Upadates); // Pass the
* results into ListViewAdapter.java adapter = new
* UpdatesAdapterList(Cardiology_updates.this, FinalLocalDataList);
* // Set the adapter to the ListView list.setAdapter(adapter);
*/
// Close the progressdialog
// mProgressDialog.dismiss();
}
}
#Override
public void onRefresh() {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
getSomeData();
// localalldata();
swipeLayout.setRefreshing(false);
}
}, 5000);
}
protected void getSomeData() {
// TODO Auto-generated method stub
// localalldata();
new GetUpdatesInfo().execute();
adapter.notifyDataSetChanged();
/*
* if (LocalDataList == null) { Log.e("LocalDataList inside if ",
* "LocalDataList inside if "); new GetUpdatesInfo().execute();
*
* } else { // adapter.imageLoader.clearCache();
* Log.e("LocalDataList else ", "LocalDataList else ");
*
* adapter.notifyDataSetChanged(); }
*/
}
private void localalldata() {
// TODO Auto-generated method stub
LocalDataList = controller.getAllJsonData();
FinalLocalDataList = new ArrayList<HashMap<String, String>>();
for (HashMap<String, String> hashMap : LocalDataList) {
System.out.println(hashMap.keySet());
HashMap<String, String> map = new HashMap<String, String>();
for (String key : hashMap.keySet()) {
System.out.println(hashMap.get(key));
Complete_imagePath = hashMap.get("Complete_imagePath");
Title = hashMap.get("Title");
Description = hashMap.get("Description");
map.put("Complete_imagePath", Complete_imagePath);
map.put("Title", Title);
map.put("Description", Description);
Log.v("All Json CodiateUpdate Title", "" + Complete_imagePath);
Log.v("All Json CodiateUpdate Title", "" + Title);
}
FinalLocalDataList.add(map);
}
list = (ListView) findViewById(R.id.list_Upadates);
// Pass the results into ListViewAdapter.java
adapter = new UpdatesAdapterList(Cardiology_updates.this,
FinalLocalDataList);
// Set the adapter to the ListView
list.setAdapter(adapter);
// adapter.notifyDataSetChanged();
et = (EditText) findViewById(R.id.search);
// Capture Text in EditText
et.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
//String text = et.getText().toString().toLowerCase(Locale.getDefault());
adapter.getFilter().filter(arg0);
}
});
}
}
Here is my adapter class includes filter:
package com.XXXXX.adapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import com.XXXXX.XXXXX.Cardiology_updates;
import com.XXXXX.XXXXX.R;
import com.XXXXX.imageloader.ImageLoader;
public class UpdatesAdapterList extends BaseAdapter implements Filterable {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
public ImageLoader imageLoader;
private Activity activity;
HashMap<String, String> resultp = new HashMap<String, String>();
public UpdatesAdapterList(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context.getApplicationContext());
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView UpdateTitle;
TextView country;
TextView population;
ImageView UpdateImage;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.listview_updateitem, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
UpdateTitle = (TextView) itemView.findViewById(R.id.txtUpdatetitle);
//country = (TextView) itemView.findViewById(R.id.country);
// population = (TextView) itemView.findViewById(R.id.population);
// Locate the ImageView in listview_item.xml
UpdateImage = (ImageView) itemView.findViewById(R.id.list_UpdateImage);
// Capture position and set results to the TextViews
UpdateTitle.setText(resultp.get(Cardiology_updates.UpdateTitle));
// country.setText(resultp.get(UpdatesActivity.COUNTRY));
// population.setText());
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(Cardiology_updates.UpdateImage), UpdateImage);
// Capture ListView item click
itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, UpdateSingleItemViewActivity.class);
// Pass all data rank
intent.putExtra("UpdateTile", resultp.get(Cardiology_updates.UpdateTitle));
// Pass all data country
intent.putExtra("UpdateDescription", resultp.get(Cardiology_updates.UpdateDescription));
// Pass all data population
intent.putExtra("population",resultp.get(Cardiology_updates.POPULATION));
// Pass all data flag
intent.putExtra("UpdateImage", resultp.get(Cardiology_updates.UpdateImage));
// Start SingleItemView Class
intent.putExtra("position", position);
context.startActivity(intent);
}
});
return itemView;
}
public Filter getFilter() {
Filter filter = new Filter() {
FilterResults results;
ArrayList<HashMap<String, String>> filteredList;
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
// Has the filtered values
data = (ArrayList<HashMap<String, String>>) results.values;
notifyDataSetChanged();
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
// Holds the results of a filtering operation in values
results = new FilterResults();
filteredList= new ArrayList<HashMap<String, String>>();
//This is the search string user typed in EditText.
String searchString = constraint.toString().toUpperCase(Locale.getDefault());
/*
* Code to update the filteredList based on Search String.
*
* I'm just writing pseudo code for search, based on
* Cardiology_updates.UpdateTitle
*/
int mCount=data.size();
for (int i = 0; i < mCount; i++) {
HashMap<String, String> obj= data.get(i);
String updateTitle=obj.get(Cardiology_updates.UpdateTitle);
if(updateTitle.contains(searchString)){
filteredList.add(obj);
}
}
synchronized (this) {
// set the Filtered result to return
results.count = filteredList.size();
results.values = filteredList;
}
return results;
}
};
return filter;
}
}

You need to implement Filterable interface in your UpdatesAdapterList class.
For detailed explanation visit How to implement getfilter() with custom adapter that extends baseadapter?.
public class UpdatesAdapterList extends BaseAdapter implements Filterable {
...
#Override
public Filter getFilter(){
// Your Search logic goes here..
Filter filter = new Filter() {
FilterResults results;
ArrayList<HashMap<String, String>> filteredList;
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
// Has the filtered values
data = (ArrayList<HashMap<String, String>>) results.values;
notifyDataSetChanged();
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
// Holds the results of a filtering operation in values
results = new FilterResults();
filteredList= new ArrayList<HashMap<String, String>>();
//This is the search string user typed in EditText.
String searchString = constraint.toString();
/*
* Code to update the filteredList based on Search String.
*
* I'm just writing pseudo code for search, based on
* Cardiology_updates.UpdateTitle
*/
int mCount=data.size();
for (int i = 0; i < mCount; i++) {
HashMap<String, String> obj= data.get(i);
String updateTitle=obj.get(Cardiology_updates.UpdateTitle);
if(updateTitle.contains(searchString)){
filteredList.add(obj);
}
}
synchronized (this) {
// set the Filtered result to return
results.count = filteredList.size();
results.values = filteredList;
}
}
return results;
}
};
return filter;
}
}

Related

Display Filtered Data on ListView

I'm having an issue while trying to display my filtered list on my list view.
I print out the data after filtering and it's actually correct but it doesn't display on my ListView please what I am doing wrong? My code is below
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Icon;
import android.media.Image;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.BaseAdapter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
public class SchoolListAdapter extends BaseAdapter implements Filterable {
private Activity activity;
ArrayList<HashMap<String, String>> data;
ArrayList<HashMap<String, String>> displayedData;
private static LayoutInflater inflater=null;
public SchoolListAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
displayedData = d;
inflater = LayoutInflater.from(a);
}
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.school_details_list, null);
}
ImageView schoolLogo = (ImageView) vi.findViewById(R.id.schoolLogo);
TextView lblSchoolId = (TextView)vi.findViewById(R.id.lblSchoolId);
TextView lblSchoolName = (TextView)vi.findViewById(R.id.lblSchoolName);
HashMap<String, String> school = data.get(position);
// Setting all values in listview
lblSchoolId.setText(school.get("id"));
lblSchoolName.setText(school.get("name"));
String logo = school.get("logo");
byte []img = Base64.decode(logo,Base64.DEFAULT);
Bitmap bmp = BitmapFactory.decodeByteArray(img, 0, img.length);
schoolLogo.setImageBitmap(bmp);
return vi;
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected void publishResults(CharSequence constraint,FilterResults results) {
if(results.count == 0){
notifyDataSetInvalidated();
}else{
displayedData = (ArrayList<HashMap<String, String>>) results.values; // has the filtered values
notifyDataSetChanged(); // notifies the data with new filtered values
}
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults(); // Holds the results of a filtering operation in values
ArrayList<HashMap<String, String>> FilteredArrList = new ArrayList();
if (data == null) {
data = new ArrayList(displayedData); // saves the original data in data
}
/********
*
* If constraint(CharSequence that is received) is null returns the data(Original) values
* else does the Filtering and returns FilteredArrList(Filtered)
*
********/
if (constraint == null || constraint.length() == 0) {
// set the Original result to return
results.count = data.size();
results.values = data;
} else {
constraint = constraint.toString().toUpperCase();
HashMap <String, String>schools = new HashMap();
for (int i = 0; i < data.size(); i++) {
String dat = data.get(i).get("name");
if(dat.toString().matches(".*"+constraint+".*")){
schools.put("id",data.get(i).get("id"));
schools.put("name",data.get(i).get("name"));
schools.put("logo",data.get(i).get("logo"));
FilteredArrList.add(schools);
}
}
// set the Filtered result to return
results.count = FilteredArrList.size();
results.values = FilteredArrList;
}
return results;
}
};
return filter;
}
}
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class SelectSchoolActivity extends ListActivity implements AdapterView.OnItemClickListener {
private ProgressDialog pDialog;
private ListView lv;
private SharedPreferences sharedPreferences;
public static String SCHOOLING_PREFERENCES = "SCHOOL_PREF";
private ArrayList<HashMap<String, String>> schoolList;
private EditText txtSearch;
private SchoolListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_school);
sharedPreferences = getSharedPreferences(SCHOOLING_PREFERENCES, Context.MODE_PRIVATE);
txtSearch = (EditText)findViewById(R.id.txtSearch);
schoolList = new ArrayList();
if(sharedPreferences.contains("school")){
Intent intent = new Intent(SelectSchoolActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}else{
new GetSchoolList(SelectSchoolActivity.this).execute();
lv = getListView();
lv.setOnItemClickListener(this);
// Add Text Change Listener to EditText
txtSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Call back the Adapter with current character to Filter
adapter.getFilter().filter(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String school = ((TextView)view.findViewById(R.id.lblSchoolId)).getText().toString();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("school", school);
editor.commit();
Intent intent = new Intent(SelectSchoolActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
private class GetSchoolList extends AsyncTask<Void, Void, Void> {
private Activity context;
public GetSchoolList(Activity context){
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(context);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
String url = "http://192.168.34.1:8085/SchoolWebService/rest/Student/school_list";
// Making a request to url and getting response
String details = sh.makeServiceCall(url, ServiceHandler.GET);
if (details != null) {
try {
JSONArray results = new JSONArray(details);
for(int i = 0; i<results.length(); i++) {
JSONObject c = results.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String logo = c.getString("logo");
// tmp hashmap for single feeDetails
HashMap <String, String>school = new HashMap();
school.put("id", id);
school.put("name", name);
school.put("logo", logo);
schoolList.add(school);
}
} catch (Exception e) {
Log.e("Exception", Log.getStackTraceString(e));
}
} else {
//snackbar.setText("Connection Failed!").show();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing()) {
pDialog.dismiss();
}
adapter = new SchoolListAdapter(context, schoolList);
setListAdapter(adapter);
}
}
}
#medhdj pointed out and error in my code so I was able to find and fix the problem.
Please refer to his comment

Dynamic listview save state

I am working on laundry app. I have a listview (Fragment) like this so user can select the items.
My Problem is when I click the continue and then I come back to this screen again its value become zero. How can I save listview state.
I tried this code in my fragment but no luck. And also try save and restore instance state method but facing same problem.
// Save the ListView state (= includes scroll position) as a Parceble
Parcelable state = listView.onSaveInstanceState();
// e.g. set new items
listView.setAdapter(adapter);
// Restore previous state (including selected item index and scroll position)
listView.onRestoreInstanceState(state);
ManFragment.java
package info.tranetech.laundry.activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import info.tranetech.laundry.R;
import info.tranetech.laundry.adapter.JSONParser;
public class ManFragment extends Fragment {
private View rootView;
//Dry
public static String TAG_ITEM_MAN = "name";
public static String TAG_PRICE_DRY = "drycleaning_price";
public static String TAG_PRICE_WASH_IRON = "washiron_price";
public static String TAG_PRICE_WASH = "wash_price";
public static String TAG_PRICE_IRON = "iron_price";
public static String Name, Price_Dry, price_wash_iron, price_wash, price_iron;
public static String url_dry = "http://openspace.tranetech.com/mis/Laundry/men_dry.php";
static TextView ItemName, ItemPrice;
public static int Cat_Position;
ArrayList<HashMap<String, String>> DryList = new ArrayList<HashMap<String, String>>();
ArrayList<HashMap<String, String>> WashList = new ArrayList<HashMap<String, String>>();
ArrayList<HashMap<String, String>> WashIronList = new ArrayList<HashMap<String, String>>();
ArrayList<HashMap<String, String>> IronList = new ArrayList<HashMap<String, String>>();
ListView list;
ProgressDialog pdialog;
static Spinner Spin_Man;
public ManFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.man_pricelist, container, false);
// Locate the listview in listview_main.xml
list = (ListView) rootView.findViewById(R.id.man_listView);
Spin_Man = (Spinner) rootView.findViewById(R.id.spinner_man);
new DryData().execute();
Spin_Man.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
try {
switch (position) {
case 0:
Cat_Position = position;
Filllist();
getView();
break;
case 1:
Cat_Position = position;
Filllist();
getView();
break;
case 2:
Cat_Position = position;
Filllist();
getView();
break;
case 3:
Cat_Position = position;
Filllist();
getView();
break;
}
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(getActivity(), "Position " + position, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
return rootView;
}
private class DryData extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pdialog = new ProgressDialog(getActivity());
pdialog.setMessage("Please Wait...");
pdialog.setCancelable(true);
pdialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
JSONParser jp = new JSONParser();
String jsonStr = jp.makeServiceCall(url_dry, JSONParser.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jobj = new JSONObject(jsonStr);
JSONArray jarray = jobj.getJSONArray("Data");
for (int i = 0; i < jarray.length(); i++) {
JSONObject jobjin = jarray.getJSONObject(i);
String name = jobjin.getString(TAG_ITEM_MAN);
String price_dry = jobjin.getString(TAG_PRICE_DRY);
String price_wash_iron = jobjin.getString(TAG_PRICE_WASH_IRON);
String price_wash = jobjin.getString(TAG_PRICE_WASH);
String price_iron = jobjin.getString(TAG_PRICE_IRON);
HashMap<String, String> add_dry = new HashMap<String, String>();
add_dry.put(TAG_ITEM_MAN, name);
add_dry.put(TAG_PRICE_DRY, price_dry);
HashMap<String, String> add_wash_iron = new HashMap<String, String>();
add_wash_iron.put(TAG_ITEM_MAN, name);
add_wash_iron.put(TAG_PRICE_WASH_IRON, price_wash_iron);
HashMap<String, String> add_wash = new HashMap<String, String>();
add_wash_iron.put(TAG_ITEM_MAN, name);
add_wash.put(TAG_PRICE_WASH, price_wash);
HashMap<String, String> add_iron = new HashMap<String, String>();
add_iron.put(TAG_ITEM_MAN, name);
add_iron.put(TAG_PRICE_IRON, price_iron);
DryList.add(add_dry);
WashList.add(add_wash);
WashIronList.add(add_wash_iron);
IronList.add(add_iron);
}
} catch (JSONException e) {
e.printStackTrace();
// TODO: handle exception
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url_dry");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (pdialog.isShowing()) {
pdialog.dismiss();
}
Filllist();
}
}
public void Filllist() {
// TODO Auto-generated method stub
Cus adapter = new Cus();
list.setAdapter(adapter);
// Helper.getListViewSize(list);
}
private class Cus extends BaseAdapter {
#Override
public int getCount() {
// TODO Auto-generated method stub
return DryList.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) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.price_row, null);
}
ItemName = (TextView) convertView.findViewById(R.id.item_name);
ItemPrice = (TextView) convertView.findViewById(R.id.price);
Name = DryList.get(position).get(TAG_ITEM_MAN).toString();
Price_Dry = DryList.get(position).get(TAG_PRICE_DRY).toString();
price_wash_iron = WashIronList.get(position).get(TAG_PRICE_WASH_IRON).toString();
price_wash = WashList.get(position).get(TAG_PRICE_WASH).toString();
price_iron = IronList.get(position).get(TAG_PRICE_IRON).toString();
if (Cat_Position == 0) {
//set item name
ItemName.setText("" + Name);
ItemPrice.setText("Rs." + Price_Dry);
} else if (Cat_Position == 1) {
//set item name
ItemName.setText("" + Name);
ItemPrice.setText("Rs." + price_iron);
} else if (Cat_Position == 2) {
//set item name
ItemName.setText("" + Name);
ItemPrice.setText("Rs." + price_wash);
} else if (Cat_Position == 3) {
//set item name
ItemName.setText("" + Name);
ItemPrice.setText("Rs." + price_wash_iron);
}
return convertView;
}
}
}
Define Arraylist globally and call webservices as:
if (catListDao.size() > 0) {
adapter = new ExpertViewAdapter(act, R.layout.custom_expert, catListDao);
list.setAdapter(adapter);
list.setTextFilterEnabled(true);
} else {
if (!isViewShown) {
new FetchAllData(getActivity(), 2, 10, 0).execute();
}
}
}

Issues with Filtering listview with edittext

Hello I'm working on an app which has an edittext to search for items on the listview. If the user types a letter in the edittext the listview is getting filtered perfectlty.Have used Adapter also.Now i have following issues:
1)when i m clearing letters edittext my listview is not getting Updated..
2) if i enter wrong letter or letter which does not corrorsponds to any item of a listview the listview is getting clear.
Have gone thorugh exmaples in SO
Android filter listview custom adapter
And googled also for same problem but not getting solved it..Plz anybody help me..
Here is my code:
package com.AAAAA.AAAAA;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.AdapterView.OnItemClickListener;
import com.AAAAA.adapter.UpdateSingleItemViewActivity;
import com.AAAAA.adapter.UpdatesAdapterList;
import com.AAAAA.local.database.DBController;
import com.AAAAA.AAAAA.AAAAA.constant.Constant;
import com.AAAAA.AAAAA.AAAAA.utils.Utility;
public class Cardiology_updates extends Activity implements OnClickListener,
OnRefreshListener {
EditText et ;
private Context appContext;
// ProgressDialog mProgressDialog;
private Dialog dialog;
private boolean isFinish = false;
String result = "";
JSONObject jsonobject;
JSONArray jsonArray;
ArrayList<HashMap<String, String>> UpdatesHmList;
public static ArrayList<HashMap<String, String>> FinalLocalDataList;
ArrayList<HashMap<String, String>> LocalDataList;
DBController controller = new DBController(this);
HashMap<String, String> queryValues;
ListView list;
UpdatesAdapterList adapter;
public static String UpdateID = "UpdateID";
public static String UpdateTitle = "Title";
/*
* public static String UpdateDescription = "Description"; public static
* String POPULATION = "UpdateDate"; public static String UpdateImage =
* "Photo";
*/
public static String UpdateDescription = "Description";
public static String POPULATION = "Title";
public static String UpdateImage = "Complete_imagePath";
public static String Complete_imagePath;
public static String Title;
public static String Description;
SwipeRefreshLayout swipeLayout;
private ProgressBar progressbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cardiology_updates);
// controller.deleteAllJsonData();
appContext = this;
animationView();
initComponent();
}
private void animationView() {
// TODO Auto-generated method stub
progressbar = (ProgressBar) findViewById(R.id.loading);
}
private void initComponent() {
// TODO Auto-generated method stub
swipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setColorScheme(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
dialog = new Dialog(appContext);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.alert_dialog);
((Button) findViewById(R.id.Button01)).setOnClickListener(this);
((Button) dialog.findViewById(R.id.btnOk)).setOnClickListener(this);
new GetUpdatesInfo().execute();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.Button01) {
finish();
// finishActivity() ;
} else if (v.getId() == R.id.btnOk) {
dialog.dismiss();
if (isFinish) {
this.finish();
}
}
}
public class GetUpdatesInfo extends AsyncTask<String, Void, String> {
protected void onPreExecute() {
super.onPreExecute();
if (progressbar.getVisibility() != View.VISIBLE) {
progressbar.setVisibility(View.VISIBLE);
}
}
#Override
protected String doInBackground(String... params) {
// Create an array
UpdatesHmList = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
String url = null;
url = Constant.serverUrl + "/GetUpdateList";
result = Utility.postParamsAndfindJSON(url);
Log.e("result doInBackground", "" + result);
if (!(result == null)) {
try {
controller.deleteAllJsonData();
// Locate the array name in JSON
jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonArray.getJSONObject(i);
// Retrive JSON Objects
map.put("UpdateID", jsonobject.getString("UpdateID"));
map.put("Title", jsonobject.getString("Title"));
String Upadates_Photo = jsonobject.optString("Photo")
.toString();
String Complete_imagePath = Constant.prifixserverUrl
+ Upadates_Photo;
String Title = jsonobject.getString("Title").toString();
String Description = jsonobject
.getString("Description").toString();
String noHtml = Description.replaceAll("<[^>]*>", "");
String parseResponse = noHtml.replaceAll(" ", "");
map.put("Photo", Complete_imagePath);
map.put("Description", Description);
map.put("UpdateDate",
jsonobject.getString("UpdateDate"));
Log.e("UpdateID ",
" "
+ jsonobject.getString("UpdateID")
.toString());
Log.e("Title ", " "
+ jsonobject.getString("Title").toString());
Log.e("Complete_imagePath ",
" " + Complete_imagePath.toString());
Log.e("Description ", " " + parseResponse);
Log.e("UpdateDate ",
" "
+ jsonobject.getString("UpdateDate")
.toString());
queryValues = new HashMap<String, String>();
queryValues.put("Complete_imagePath",
Complete_imagePath);
queryValues.put("Title", Title);
queryValues.put("Description", Description);
controller.insertAllJsonData(queryValues);
// Set the JSON Objects into the array
UpdatesHmList.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
return result;
}
#Override
protected void onPostExecute(String result) {
// Locate the listview in listview_main.xml
if (progressbar.getVisibility() == View.VISIBLE) {
progressbar.setVisibility(View.GONE);
}
/*
* if (result == null) { //mProgressDialog.dismiss();
* localalldata();
*
* }
*/
localalldata();
/*
* list = (ListView) findViewById(R.id.list_Upadates); // Pass the
* results into ListViewAdapter.java adapter = new
* UpdatesAdapterList(Cardiology_updates.this, FinalLocalDataList);
* // Set the adapter to the ListView list.setAdapter(adapter);
*/
// Close the progressdialog
// mProgressDialog.dismiss();
}
}
#Override
public void onRefresh() {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
getSomeData();
// localalldata();
swipeLayout.setRefreshing(false);
}
}, 5000);
}
protected void getSomeData() {
// TODO Auto-generated method stub
// localalldata();
new GetUpdatesInfo().execute();
adapter.notifyDataSetChanged();
/*
* if (LocalDataList == null) { Log.e("LocalDataList inside if ",
* "LocalDataList inside if "); new GetUpdatesInfo().execute();
*
* } else { // adapter.imageLoader.clearCache();
* Log.e("LocalDataList else ", "LocalDataList else ");
*
* adapter.notifyDataSetChanged(); }
*/
}
private void localalldata() {
// TODO Auto-generated method stub
LocalDataList = controller.getAllJsonData();
FinalLocalDataList = new ArrayList<HashMap<String, String>>();
for (HashMap<String, String> hashMap : LocalDataList) {
System.out.println(hashMap.keySet());
HashMap<String, String> map = new HashMap<String, String>();
for (String key : hashMap.keySet()) {
System.out.println(hashMap.get(key));
Complete_imagePath = hashMap.get("Complete_imagePath");
Title = hashMap.get("Title");
Description = hashMap.get("Description");
map.put("Complete_imagePath", Complete_imagePath);
map.put("Title", Title);
map.put("Description", Description);
Log.v("All Json CodiateUpdate Title", "" + Complete_imagePath);
Log.v("All Json CodiateUpdate Title", "" + Title);
}
FinalLocalDataList.add(map);
}
list = (ListView) findViewById(R.id.list_Upadates);
// Pass the results into ListViewAdapter.java
adapter = new UpdatesAdapterList(Cardiology_updates.this,
FinalLocalDataList);
// Set the adapter to the ListView
list.setTextFilterEnabled(true);
list.setAdapter(adapter);
// adapter.notifyDataSetChanged();
et = (EditText) findViewById(R.id.search);
// Capture Text in EditText
et.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
adapter.filter(arg0.toString());
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
//String text = et.getText().toString().toLowerCase(Locale.getDefault());
//adapter.getFilter().filter(arg0);
}
});
}
}
Here is my Adapter:
package com.AAAA.adapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import com.AAAA.AAAA.Cardiology_updates;
import com.AAAA.AAAA.R;
import com.AAAA.imageloader.ImageLoader;
public class UpdatesAdapterList extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
public ImageLoader imageLoader;
private Activity activity;
//HashMap<String, String> resultp = new HashMap<String, String>();
private ArrayList<HashMap<String,String>> filterData;
public UpdatesAdapterList(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context.getApplicationContext());
filterData = new ArrayList<HashMap<String,String>>();
filterData.addAll(this.data);
}
#Override
public int getCount() {
return filterData.size();
}
#Override
public Object getItem(int position) {
return filterData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
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.listview_updateitem, null);
holder.UpdateTitle = (TextView) convertView.findViewById(R.id.txtUpdatetitle);
holder.UpdateImage = (ImageView) convertView.findViewById(R.id.list_UpdateImage);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.UpdateTitle.setText(filterData.get(position).get(Cardiology_updates.UpdateTitle));
imageLoader.DisplayImage(filterData.get(position).get(Cardiology_updates.UpdateImage), holder.UpdateImage);
// Capture ListView item click
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
//resultp = data.get(position);
Intent intent = new Intent(context, UpdateSingleItemViewActivity.class);
// Pass all data rank
intent.putExtra("UpdateTile", filterData.get(position).get(Cardiology_updates.UpdateTitle));
// Pass all data country
intent.putExtra("UpdateDescription", filterData.get(position).get(Cardiology_updates.UpdateDescription));
// Pass all data population
intent.putExtra("population",filterData.get(position).get(Cardiology_updates.POPULATION));
// Pass all data flag
intent.putExtra("UpdateImage", filterData.get(position).get(Cardiology_updates.UpdateImage));
// Start SingleItemView Class
intent.putExtra("position", position);
context.startActivity(intent);
}
}); return convertView;
}
class ViewHolder{
TextView UpdateTitle;
ImageView UpdateImage;
}
public void filter(String constraint) {
filterData.clear();
if (constraint.length() == 0) {
filterData.addAll(data);
}else{
for (HashMap<String,String> row: data) {
if(row.get(Cardiology_updates.UpdateTitle).toUpperCase().startsWith(constraint.toString().toUpperCase())){
filterData.add(row);
}
}
}
notifyDataSetChanged();
}
}
Activity opens on cliking listview items:
package com.AAAAA.adapter;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import com.AAAAA.AAAAA.Cardiology_updates;
import com.AAAAA.AAAAA.R;
public class UpdateSingleItemViewActivity extends Activity {
int position;
String UpdateTile;
String UpdateDescription;
String population;
String UpdateImage;
//String position;
ViewPager viewPager;
PagerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_update_single_item_view);
Log.e("UpdateSingleItemViewActivity class",
"UpdateSingleItemViewActivity class");
/*
* WebView webview = new WebView(this); setContentView(webview);
*/
Button btnback = (Button) findViewById(R.id.Button01);
btnback.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
//WebView webview = (WebView) findViewById(R.id.webview);
Intent i = getIntent();
// Get the result of rank
UpdateTile = i.getStringExtra("UpdateTile");
// Get the result of country
UpdateDescription = i.getStringExtra("UpdateDescription");
// Get the result of population
population = i.getStringExtra("population");
// Get the result of flag
UpdateImage = i.getStringExtra("UpdateImage");
//i.putExtra("POSITION_KEY", position);
position = i.getExtras().getInt("position");
//webview.loadData(UpdateDescription, "text/html", null);
viewPager = (ViewPager) findViewById(R.id.viewpager_layout);
// Pass results to ViewPagerAdapter Class
adapter = new ViewPagerAdapter(UpdateSingleItemViewActivity.this, Cardiology_updates.FinalLocalDataList);
// Binds the Adapter to the ViewPager
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(position);
}
}
its Corrosponding adapter:
package com.AAAAA.adapter;
import java.util.ArrayList;
import java.util.HashMap;
import com.AAAAA.AAAAA.Cardiology_updates;
import com.AAAAA.AAAAA.R;
import com.AAAAA.imageloader.ImageLoader;
import android.app.Activity;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.LinearLayout;
public class ViewPagerAdapter extends PagerAdapter {
String UpdateTile;
String UpdateDescription;
//String population;
String UpdateImage;
String position;
LayoutInflater inflater;
Context context;
ArrayList<HashMap<String, String>> data;
public ImageLoader imageLoader;
private Activity activity;
//HashMap<String, String> resultp = new HashMap<String, String>();
ArrayList<HashMap<String,String>> filterData;
public ViewPagerAdapter(Context context, ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
filterData = new ArrayList<HashMap<String,String>>();
filterData.addAll(this.data);
}
#Override
public int getCount() {
return filterData.size();
}
public Object getItem(int position) {
return filterData.get(position);
}
public long getItemId(int position) {
return position;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((LinearLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
WebView webview;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.viewpager_item, container,
false);
//resultp =data.get(position);
webview=(WebView)itemView.findViewById(R.id.webview1);
//webview.setText(webview[position]);
webview.loadData(filterData.get(position).get(Cardiology_updates.UpdateDescription), "text/html", null);
((ViewPager) container).addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// Remove viewpager_item.xml from ViewPager
((ViewPager) container).removeView((LinearLayout) object);
}
}
When used custom adapter always try to implement ViewHolder design pattern for ListView performance and use custom filter function instead Filterable implementation :
Custom filter funcation required two array list one is filterable data list and another one is for orignal data list :
public void filter(String constraint) {
filterData.clear();
if (constraint.length() == 0) {
filterData.addAll(orignalData);
}else{
for (HashMap<String,String> row: orignalData) {
if(row.get(Cardiology_updates.UpdateTitle).toUpperCase().startsWith(constraint.toString().toUpperCase())){
filterData.add(row);
}
}
}
notifyDataSetChanged();
}
Example :
et.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
adapter.filter(arg0.toString());
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,int arg2, int arg3) {
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,int arg3) {
}
});
public class UpdatesAdapterList extends BaseAdapter {
private Context context;
private ArrayList<HashMap<String,String>> filterData;
private ArrayList<HashMap<String,String>> orignalData;
public ImageLoader imageLoader;
public UpdatesAdapterList(Context context,ArrayList<HashMap<String, String>> orignalData) {
this.context = context;
this.orignalData = orignalData;
filterData = new ArrayList<HashMap<String,String>>();
filterData.addAll(this.orignalData);
imageLoader = new ImageLoader(this.context);
}
#Override
public int getCount() {
return filterData.size();
}
#Override
public Object getItem(int position) {
return filterData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
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.listview_updateitem, null);
holder.UpdateTitle = (TextView) convertView.findViewById(R.id.txtUpdatetitle);
holder.UpdateImage = (ImageView) convertView.findViewById(R.id.list_UpdateImage);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.UpdateTitle.setText(filterData.get(position).get(Cardiology_updates.UpdateTitle));
imageLoader.DisplayImage(filterData.get(position).get(Cardiology_updates.UpdateImage), holder.UpdateImage);
// Capture ListView item click
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(context, UpdateSingleItemViewActivity.class);
// Pass all data rank
intent.putExtra("UpdateTile", filterData.get(position).get(Cardiology_updates.UpdateTitle));
// Pass all data country
intent.putExtra("UpdateDescription", filterData.get(position).get(Cardiology_updates.UpdateDescription));
// Pass all data population
intent.putExtra("population",filterData.get(position).get(Cardiology_updates.POPULATION));
// Pass all data flag
intent.putExtra("UpdateImage", filterData.get(position).get(Cardiology_updates.UpdateImage));
// Start SingleItemView Class
intent.putExtra("position", position);
context.startActivity(intent);
}
});
return convertView;
}
class ViewHolder{
TextView UpdateTitle;
ImageView UpdateImage;
}
public void filter(String constraint) {
filterData.clear();
if (constraint.length() == 0) {
filterData.addAll(orignalData);
}else{
for (HashMap<String,String> row: orignalData) {
if(row.get(Cardiology_updates.UpdateTitle).toUpperCase().startsWith(constraint.toString().toUpperCase())){
filterData.add(row);
}
}
}
notifyDataSetChanged();
}
}

How to make search listview android?

public class kuliner extends ListActivity {
private static String url = "http://kulinermalang.zz.mu/kuliner/daftar_kuliner.php";
private static final String no_id = "id";
private static final String gambar = "gambar";
private static final String nama = "nama_toko";
JSONArray menu = null;
ListView list;
ArrayList<HashMap<String, String>> daftar_kuliner = new ArrayList<HashMap<String, String>>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main_listview);
EditText search = (EditText) findViewById(R.id.tfCari);
//ambil();
search.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
loadingData loading = new loadingData();
loading.execute();
}
//this method for call data to listView
private class loadingData extends AsyncTask<String, Void, String> {
private ProgressDialog Dialog;
String response;
#Override
protected void onPreExecute() {
Dialog = new ProgressDialog(kuliner.this);
Dialog.setMessage("Loading Data...");
Dialog.show();
}
#Override
protected String doInBackground(String... urls) {
response = "Success";
return response;
}
#Override
protected void onPostExecute(String result) {
if (response.equalsIgnoreCase("Success")) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.AmbilJson(url);
String id_nama;
String gambar_toko = null;
String nama_toko;
String image_url;
try {
menu = json.getJSONArray("daftar");
for (int i = 0; i < menu.length(); i++) {
JSONObject ar = menu.getJSONObject(i);
id_nama = ar.getString(no_id);
gambar_toko = ar.getString(gambar);
nama_toko = ar.getString(nama);
HashMap<String, String> map = new HashMap<String, String>();
map.put(no_id, id_nama);
map.put(gambar, gambar_toko);
map.put(nama, nama_toko);
daftar_kuliner.add(map);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
Dialog.dismiss();
}
}
}
You could probably do something like this
//get your ListView with attached SimpleAdapter
ListAdapter adapter = listView.getAdapter();
for(int i = 0; i < adapter.getCount(); i++) {
String value = ((HashMap<String, String>)adapter.getItem(i)).get("Your_key");
}
But i'm not sure i understand the question correctly, what is it that you want to accomplish exactly? I'm sorry for asking a question here but i'm not allowed to comment yet :/
in the onTextChangedMethod of TextWatcher, write an if condition that - the edittext values is in the list you are inflating in your listview, if yes them add that edittext value to another list and set that list to your adapter. For Example Here is my Code :- ( Just focus on ListView, ArrayList and TextWatcher. Dont mind other code)
package com.example.alaramsms;
import java.util.ArrayList;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ContactActivity extends Activity implements OnItemClickListener{
String textlength;
ArrayList<String> filtered_name;
ArrayList<String> filtered_phone;
ArrayList<String> name1 = new ArrayList<String>();
ArrayList<String> phno1 = new ArrayList<String>();
ArrayList<String> phno0 = new ArrayList<String>();
ArrayList<String> list = new ArrayList<String>();
ArrayList<String> mOriginalValues;
MyAdapter mAdapter ;
Button send,btnselect;
ListView lv;
EditText myFilter;
boolean flag = false;
ArrayList<Integer> checkedPositions = new ArrayList<Integer>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.get);
lv =(ListView)findViewById(R.id.lv);
getAllCallLogs(this.getContentResolver());
mAdapter = new MyAdapter(this,name1,phno1);
lv.setAdapter(mAdapter);
lv.setOnItemClickListener(this);
lv.setItemsCanFocus(false);
lv.setTextFilterEnabled(true);
send = (Button) findViewById(R.id.button1);
CheckBox chkAll = ( CheckBox ) findViewById(R.id.chkAll);
chkAll.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
flag = !flag;
mAdapter.notifyDataSetChanged();
}
});
myFilter = (EditText) findViewById(R.id.myFilter);
myFilter.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count,int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
#SuppressLint("DefaultLocale")
public void onTextChanged(CharSequence s,
int start, int before, int count)
{
textlength = myFilter.getText().toString();
filtered_name = new ArrayList<String>();
filtered_phone = new ArrayList<String>();
for (int i = 0; i < name1.size(); i++)
{
if(name1.get(i).toString().toUpperCase().contains(myFilter.getText().toString().toUpperCase()))
{
System.err.println("Selection: " + textlength);
filtered_name.add(name1.get(i));
filtered_phone.add(phno1.get(i));
}
}
mAdapter = new MyAdapter(ContactActivity.this,filtered_name,filtered_phone);
lv.setAdapter(mAdapter); // Here inflating two other lists containing he searched items
}
});
send.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
StringBuilder checkedcontacts= new StringBuilder();
System.out.println(".............."+mAdapter.mCheckStates.size());
for(int i = 0; i < name1.size(); i++)
{
if(mAdapter.mCheckStates.get(i)==true)
{
phno0.add(phno1.get(i).toString()) ;
checkedcontacts.append(name1.get(i).toString());
checkedcontacts.append("\n");
}
else
{
System.out.println("..Not Checked......"+name1.get(i).toString());
}
}
Toast.makeText(ContactActivity.this, checkedcontacts,1000).show();
Intent returnIntent = new Intent();
returnIntent.putStringArrayListExtra("name",phno0);
setResult(RESULT_OK,returnIntent);
finish();
}
});
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
mAdapter.toggle(arg2);
}
public void getAllCallLogs(ContentResolver cr) {
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println(".................."+phoneNumber);
name1.add(name);
phno1.add(phoneNumber);
}
phones.close();
}
class MyAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener
{
private SparseBooleanArray mCheckStates;
ArrayList<String> name1;
ArrayList<String> phno1;
LayoutInflater mInflater;
TextView tv1,tv;
CheckBox cb;
MyAdapter(ContactActivity contactActivity, ArrayList<String> name1, ArrayList<String> phno1)
{
mCheckStates = new SparseBooleanArray(name1.size());
mInflater = (LayoutInflater)ContactActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.name1 = name1;
this.phno1 = phno1;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return name1.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
vi = mInflater.inflate(R.layout.row, null);
tv= (TextView) vi.findViewById(R.id.textView1);
tv1= (TextView) vi.findViewById(R.id.textView2);
cb = (CheckBox) vi.findViewById(R.id.checkBox1);
tv.setText("Name :"+ name1.get(position));
tv1.setText("Phone No :"+ phno1.get(position));
cb.setTag(position);
cb.setChecked(flag); // You just have to add this line
cb.setOnCheckedChangeListener(this);
return vi;
}
/*
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,FilterResults results) {
//ArrayList<String> name1 = new ArrayList<String>();
arrayList = (ArrayList<String>) results.values; // has the filtered values
notifyDataSetChanged(); // notifies the data with new filtered values
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults(); // Holds the results of a filtering operation in values
ArrayList<String> FilteredArrList = new ArrayList<String>();
if (mOriginalValues == null) {
mOriginalValues = new ArrayList<String>(name1); // saves the original data in mOriginalValues
}
/********
*
* If constraint(CharSequence that is received) is null returns the mOriginalValues(Original) values
* else does the Filtering and returns FilteredArrList(Filtered)
*
********/
/* if (constraint == null || constraint.length() == 0) {
// set the Original result to return
results.count = mOriginalValues.size();
results.values = mOriginalValues;
} else {
constraint = constraint.toString().toLowerCase();
for (int i = 0; i < mOriginalValues.size(); i++) {
String name1 = mOriginalValues.get(i).toString();
if (name1.toLowerCase().startsWith(constraint.toString())) {
FilteredArrList.add(name1);
}
}
// set the Filtered result to return
results.count = FilteredArrList.size();
results.values = FilteredArrList;
}
return results;
}
};
return filter;
}*/
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
}

How to Filter data Date wise Location wiase in Given Example within same List

package com.nous.demoexample;
import static com.nous.demoexample.Constant.EIGTH_COLUMN;
import static com.nous.demoexample.Constant.FIFTH_COLUMN;
import static com.nous.demoexample.Constant.FIRST_COLUMN;
import static com.nous.demoexample.Constant.FOURTH_COLUMN;
import static com.nous.demoexample.Constant.SECOND_COLUMN;
import static com.nous.demoexample.Constant.SEVENTH_COLUMN;
import static com.nous.demoexample.Constant.SIXTH_COLUMN;
import static com.nous.demoexample.Constant.THIRD_COLUMN;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;
import com.paresh.demoexample.R;
public class MultiColumnActivity extends Activity implements OnClickListener {
private ArrayList<HashMap<String, String>> list;
Button filterButton;
Context context = this;
ListView lview;
// GridView lview;
final CharSequence[] items = { "Select all", " Date ", " Locationto",
" Client Name ", " Product code ", "Product Description",
"Location from", "Quantity", "Pallets" };
protected ArrayList<CharSequence> selectedInterests = new ArrayList<CharSequence>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
}
private void init() {
// lview = (GridView) findViewById(R.id.listview);
lview = (ListView) findViewById(R.id.listview);
filterButton = (Button) findViewById(R.id.filterbutton);
filterButton.setOnClickListener(this);
populateList();
listviewAdapter adapter = new listviewAdapter(this, list);
lview.setAdapter(adapter);
int lm = lview.getCount();
System.out.println(lm);
}
private void populateList() {
list = new ArrayList<HashMap<String, String>>();
HashMap<String, String> temp = new HashMap<String, String>();
temp.put(FIRST_COLUMN, "DATE");
temp.put(SECOND_COLUMN, "LOCATION TO");
temp.put(THIRD_COLUMN, "CLIENT NAME");
temp.put(FOURTH_COLUMN, "PRODUCT CODE");
temp.put(FIFTH_COLUMN, "PRODUCT DESCRIPTION");
temp.put(SIXTH_COLUMN, "LOCATION FROM");
temp.put(SEVENTH_COLUMN, "QUANTITY");
temp.put(EIGTH_COLUMN, "PALLETS");
list.add(temp);
HashMap<String, String> temp1 = new HashMap<String, String>();
temp1.put(FIRST_COLUMN, "7 / 2 / 2013");
temp1.put(SECOND_COLUMN, "SW00-000");
temp1.put(THIRD_COLUMN, "Mercury Direct");
temp1.put(FOURTH_COLUMN, "MERCUR-A5WW2013-491-000-000-Loose");
temp1.put(FIFTH_COLUMN, "A5 WORLDWIDE HOLS 13 C");
temp1.put(SIXTH_COLUMN, "Warehouse");
temp1.put(SEVENTH_COLUMN, " 5000");
temp1.put(EIGTH_COLUMN, "1");
list.add(temp1);
HashMap<String, String> temp2 = new HashMap<String, String>();
temp2.put(FIRST_COLUMN, "7 / 2 / 2013");
temp2.put(SECOND_COLUMN, "DAH22A");
temp2.put(THIRD_COLUMN, "Hurtigruten Ltd");
temp2.put(FOURTH_COLUMN, "HURTI-NORWY13-000-000-000-10");
temp2.put(FIFTH_COLUMN, "NORWAY 2013");
temp2.put(SIXTH_COLUMN, "ShrinkWrap");
temp2.put(SEVENTH_COLUMN, " 4000");
temp2.put(EIGTH_COLUMN, "1");
list.add(temp2);
HashMap<String, String> temp3 = new HashMap<String, String>();
temp3.put(FIRST_COLUMN, "7 / 2 / 2013");
temp3.put(SECOND_COLUMN, "DAH22A/02");
temp3.put(THIRD_COLUMN, "Hurtigruten Ltd");
temp3.put(FOURTH_COLUMN, "HURTI-NORWY13-000-000-000-10");
temp3.put(FIFTH_COLUMN, "NORWAY 2013");
temp3.put(SIXTH_COLUMN, "ShrinkWrap");
temp3.put(SEVENTH_COLUMN, " 4000");
temp3.put(EIGTH_COLUMN, "1");
list.add(temp3);
HashMap<String, String> temp4 = new HashMap<String, String>();
temp4.put(FIRST_COLUMN, "7 / 2 / 2013");
temp4.put(SECOND_COLUMN, "DAH22A/02");
temp4.put(THIRD_COLUMN, "Hurtigruten Ltd");
temp4.put(FOURTH_COLUMN, "HURTI-NORWY13-000-000-000-10");
temp4.put(FIFTH_COLUMN, "NORWAY 2013");
temp4.put(SIXTH_COLUMN, "ShrinkWrap");
temp4.put(SEVENTH_COLUMN, " 4000");
temp4.put(EIGTH_COLUMN, "1");
list.add(temp4);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.filterbutton: {
showDialog();
break;
}
default:
break;
}
}
private void showDialog() {
// arraylist to keep the selected items
final ArrayList seletedItems = new ArrayList();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select The Fields");
/*
* boolean[] checkedInterests = new boolean[items.length]; int count =
* items.length;
*
* for (int i = 0; i < count; i++) { checkedInterests[i] =
* selectedInterests .contains(items[i]);
*
* }
*/
builder.setMultiChoiceItems(items, null,
new DialogInterface.OnMultiChoiceClickListener() {
// indexSelected contains the index of item (of which
// checkbox checked)
#Override
public void onClick(DialogInterface dialog,
int indexSelected, boolean isChecked) {
if (isChecked) {
// If the user checked the item, add it to the
// selected items
// write your code when user checked the checkbox
seletedItems.add(indexSelected);
selectedInterests.add(items[indexSelected]); // by
// anup
} else if (seletedItems.contains(indexSelected)) {
// Else, if the item is already in the array, remove
// it
// write your code when user Uchecked the checkbox
seletedItems.remove(Integer.valueOf(indexSelected));
}
onChangeSelectedSelection();
}
})
// Set the action buttons
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// Your code when user clicked on OK
// You can write the code to save the selected item here
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// Your code when user clicked on Cancel
}
});
AlertDialog dialog = builder.create();
dialog = builder.create();// AlertDialog dialog; create like this
// outside onClick
dialog.show();
}
protected void onChangeSelectedSelection() {
StringBuilder stringBuilder = new StringBuilder();
for (CharSequence selection : selectedInterests)
stringBuilder.append(selection + ",");
// filterButton.setText(stringBuilder.toString());
String input = selectedInterests.toString();
System.out.println(input);
if (input.contains("Date")) {
//here i want to display Date Only Listview
}
if(input.contains("Locationto")){
// here i want to display location to only in same list
}
}
}
Constant.java
package com.nous.demoexample;
public class Constant {
public static final String FIRST_COLUMN = "First";
public static final String SECOND_COLUMN = "Second";
public static final String THIRD_COLUMN = "Third";
public static final String FOURTH_COLUMN = "Fourth";
public static final String FIFTH_COLUMN = "Fifth";
public static final String SIXTH_COLUMN = "Sixth";
public static final String SEVENTH_COLUMN = "Seventh";
public static final String EIGTH_COLUMN = "Eighth";
}
listvieadapter.java
package com.nous.demoexample;
import static com.nous.demoexample.Constant.FIRST_COLUMN;
import static com.nous.demoexample.Constant.FOURTH_COLUMN;
import static com.nous.demoexample.Constant.SECOND_COLUMN;
import static com.nous.demoexample.Constant.THIRD_COLUMN;
import static com.nous.demoexample.Constant.FIFTH_COLUMN;
import static com.nous.demoexample.Constant.SIXTH_COLUMN;
import static com.nous.demoexample.Constant.SEVENTH_COLUMN;
import static com.nous.demoexample.Constant.EIGTH_COLUMN;
import java.util.ArrayList;
import java.util.HashMap;
import com.paresh.demoexample.R;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class listviewAdapter extends BaseAdapter {
public ArrayList<HashMap<String, String>> list;
Activity activity;
public listviewAdapter(Activity activity,
ArrayList<HashMap<String, String>> list) {
super();
this.activity = activity;
this.list = list;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
private class ViewHolder {
TextView txtFirst;
TextView txtSecond;
TextView txtThird;
TextView txtFourth, txtFifth, txtSixth, txtSeventh, txtEigth;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
ViewHolder holder;
LayoutInflater inflater = activity.getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.listview_row, null);
holder = new ViewHolder();
holder.txtFirst = (TextView) convertView
.findViewById(R.id.FirstText);
holder.txtSecond = (TextView) convertView
.findViewById(R.id.SecondText);
holder.txtThird = (TextView) convertView
.findViewById(R.id.ThirdText);
holder.txtFourth = (TextView) convertView
.findViewById(R.id.FourthText);
holder.txtFifth = (TextView) convertView
.findViewById(R.id.FifthText);
holder.txtSixth = (TextView) convertView
.findViewById(R.id.SixthText);
holder.txtSeventh = (TextView) convertView
.findViewById(R.id.SeventhText);
holder.txtEigth = (TextView) convertView
.findViewById(R.id.EigthText);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
HashMap<String, String> map = list.get(position);
holder.txtFirst.setText(map.get(FIRST_COLUMN));
holder.txtSe
cond.setText(map.get(SECOND_COLUMN));
holder.txtThird.setText(map.get(THIRD_COLUMN));
holder.txtFourth.setText(map.get(FOURTH_COLUMN));
holder.txtFifth.setText(map.get(FIFTH_COLUMN));
holder.txtSixth.setText(map.get(SIXTH_COLUMN));
holder.txtSeventh.setText(map.get(SEVENTH_COLUMN));
holder.txtEigth.setText(map.get(EIGTH_COLUMN));
return convertView;
}
}
I am able to display all data date wise location wise and ....together But i want to Filter data -date wise location means if we check in location wise then it should Print location Only if filter date wise it should display date ..in list please help i have tired much But unable to do this....i have create check Box for select option date wise filter , location wise filter so please check my code if u want i can send complete code .
If you are using EditText to search then you have to write your own filter method..here is an example Custom ListView Search .
you have to change filter method something like this.
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(isDate)
{
if (wp.getDate().toLowerCase(Locale.getDefault()).contains(charText))
{
worldpopulationlist.add(wp);
}
}else{
if(wp.getLocation().toLowerCase(Locale.getDefault()).contains(charText))
{
worldpopulationlist.add(wp);
}
}
}
}
notifyDataSetChanged();
}

Categories

Resources