filter search in android - android

I am making a filter search to my listview. My listview code is executing well. I put an edittext object and I will make the filter search. How can i make this? My codes are below.
package com.nexum.imageloadingromjson;
public class MainActivity extends Activity {
private ListView list;
private MyAdapter adapter;
private final String parsingUrl = "someurl";
private String tag_coord = "Coord";
private String tag_lat = "Lat";// Double
private String tag_lon = "Lon";// Double
private String tag_image = "Image";
private String tag_InIzmir = "InIzmir";// Boolean
private String tag_name = "Name";
private ImageLoader imageLoader;
private EditText filteredittext;
private ProgressDialog pDialog;
private static int clickedItemPosition = -1;
private final int REQUEST_CODE_DETAIL = 1;
ArrayList<CoordItem> items;
ArrayList<CoordItem> filterlist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
items = new ArrayList<CoordItem>();
filterlist = new ArrayList<CoordItem>();
adapter = new MyAdapter(this, R.layout.list_item, items);
list = (ListView) findViewById(R.id.exampList);
list.setAdapter(adapter);
list.setTextFilterEnabled(true);
filteredittext = (EditText)findViewById(R.id.filtersearchedittext);
filteredittext.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
viewitems.clear();
String search = filteredittext.getText().toString();
for (int i = 0; i < items.size(); i++) {
if(items.get(i).name.equals(search)){
viewitems.add(items.get(i));
adapter.notifyDataSetChanged();
}
}
}
#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
}
});
pDialog = new ProgressDialog(this);
pDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
pDialog.setMessage("Veriler alınıyor...");
new ListViewLoad().execute();
list.setOnItemClickListener(new OnItemClickListener() {
#SuppressLint("ShowToast")
#Override
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
/*
* String bulunma = ""; if (items.get(position).inIzmir) {
* bulunma+="İzmir de bulundu."; }else{
* bulunma+="İzmir de bulunmadı."; } String
* s="Name:"+items.get(position).name+"\nInIzmir:"+bulunma;
* Toast.makeText(getApplicationContext(), s,
* Toast.LENGTH_LONG).show();
*/
clickedItemPosition = position;
Intent myIntent = new Intent(MainActivity.this,
DetailActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelable(
"parcelable_key",
new CoordItem(items.get(position).name, items
.get(position).img, items.get(position).lat,
items.get(position).lon,
items.get(position).inIzmir));
myIntent.putExtras(bundle);
// Güncelleme olayı burada baÅŸlıyor
// startActivityForResult(myIntent, REQUEST_CODE_DETAIL);
startActivityForResult(myIntent, REQUEST_CODE_DETAIL);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_DETAIL && resultCode == RESULT_OK
&& data != null) {
CoordItem coorditem = new CoordItem(data.getStringExtra("name"),
items.get(clickedItemPosition).img, Double.parseDouble(data
.getStringExtra("lat")), Double.parseDouble(data
.getStringExtra("lon")),
items.get(clickedItemPosition).inIzmir);
items.set(clickedItemPosition, coorditem);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Guncelleme yapıldı.",
Toast.LENGTH_SHORT).show();
}
}
private class ListViewLoad extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
String json = getStringFromURL(parsingUrl);
try {
final JSONArray jArray = new JSONArray(json);
for (int i = 0; i < jArray.length(); i++) {
JSONObject c = jArray.getJSONObject(i);
JSONObject coord = c.getJSONObject(tag_coord);
double lat = coord.getDouble(tag_lat);
double lon = coord.getDouble(tag_lon);
String image = c.getString(tag_image);
boolean InIzmir = c.getBoolean(tag_InIzmir);
String name = c.getString(tag_name);
CoordItem item = new CoordItem(name, image, lat, lon,
InIzmir);
items.add(item);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
adapter.notifyDataSetChanged();
pDialog.dismiss();
}
}
private class MyAdapter extends ArrayAdapter<CoordItem> {
private LayoutInflater inflater;
public MyAdapter(Context context, int textViewResourceId,
ArrayList<CoordItem> objects) {
super(context, textViewResourceId, objects);
imageLoader = ImageLoader.getInstance();
imageLoader.init(ImageLoaderConfiguration.createDefault(context));
this.inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
if (items != null)
return items.size();
else
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewholder = null;
if (convertView == null) {
viewholder = new ViewHolder();
convertView = inflater.inflate(R.layout.list_item, parent,
false);
viewholder.listItemImage = (ImageView) convertView
.findViewById(R.id.listItemImage);
viewholder.listItemName = (TextView) convertView
.findViewById(R.id.listItemName);
viewholder.listItemInIzmir = (TextView) convertView
.findViewById(R.id.listItemInIzmir);
viewholder.listItemLatitude = (TextView) convertView
.findViewById(R.id.listItemLatitude);
viewholder.listItemLongitude = (TextView) convertView
.findViewById(R.id.listItemLongitude);
convertView.setTag(viewholder);
} else {
viewholder = (ViewHolder) convertView.getTag();
}
viewholder.listItemName.setText(items.get(position).name);
if (items.get(position).inIzmir) {
viewholder.listItemInIzmir.setText("Izmirde.");
} else {
viewholder.listItemInIzmir.setText("Izmirde degil.");
}
DisplayImageOptions options = new DisplayImageOptions.Builder().delayBeforeLoading(1000).build();
imageLoader.displayImage(items.get(position).img,viewholder.listItemImage,options);
return convertView;
}
public Drawable getDrawableFromUrl(URL url) {
try {
InputStream is = (InputStream) url.getContent();
Drawable d = Drawable.createFromStream(is, "src");
return d;
} catch (Exception e) {
return null;
}
}
}
static class ViewHolder {
ImageView listItemImage;
TextView listItemName, listItemInIzmir, listItemLatitude,
listItemLongitude;
}
public String getStringFromURL(String url) {
// Making HTTP request
String json = "";
InputStream is = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
// return JSON String
return json;
}
}
What must i write to onTextChanged method in these codes? I researched but I didn't find codes for this class. Or I did not edit.

For searching on listview check the link here.
How can I filter ListView data when typing on EditText in android
If you want make custom search you can use the code below
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<EditText
android:id="#+id/search"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
Main Activity
public class MainActivity extends Activity {
ArrayList<NewData> mTemp=new ArrayList<NewData>(); //temporary list for search data
ArrayList<NewData> mPostingData=new ArrayList<NewData>(); //data to post in listview
ArrayList< NewData> mOri = new ArrayList<NewData>() ;//original data
// You can have two arraylist instead of three. 1. for original values 2. one for search result.
Myadapter ma;
EditText search;
NewData nd;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for(int i = 0; i < 20; i++)
{
// Add your Json Parsed Data here
// each item from json add it to hash map in NewData class. Arraylist of 0 contains jsondata of customer1
nd=new NewData();
nd.newDatacus.put(NewData.TAG_CUSTOMER_CODE, "i"+i);
nd.newDatacus.put(NewData.TAG_CUSTOMER_NAME, "a"+i);
nd.newDatacus.put(NewData.TAG_CUSTOMER_MOBILE, "number");
nd.newDatacus.put(NewData.TAG_CUSTOMER_ADDRESS, "address");
mOri.add(nd);
}
ma= new Myadapter(MainActivity.this);
mPostingData=mOri;
mTemp=mOri;
ListView lv= (ListView) findViewById(R.id.list);
lv.setAdapter(ma);
search= (EditText) findViewById(R.id.search); //editext
search.addTextChangedListener(new TextWatcher() { //supply edittext value to filter
public void onTextChanged(CharSequence s, int start, int before, int count) {
ma.getFilter().filter(s);
ma.notifyDataSetChanged();
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
}
});
}
class Myadapter extends ArrayAdapter
{
LayoutInflater mInflater;
public void setData(ArrayList<NewData> mPpst) { //function to set data based on search result
mPostingData = mPpst;//contains class items data.
}
#Override
public Filter getFilter() { //implement getFilter
return new Filter() {
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count >= 0) {
setData((ArrayList<NewData>) results.values);//if results of search is null set the searched results data
} else {
setData(mOri);// set original values
}
notifyDataSetInvalidated();//refresh listview
}
//this performs filtering data.//check if data matches whats typed in editext
//add it to list if found. return list (founditems)
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults result = new FilterResults();
if (!TextUtils.isEmpty(constraint)) {
constraint = constraint.toString().toLowerCase();
ArrayList<NewData> foundItems = new ArrayList<NewData>();
if(mTemp!=null)
{
for(int i=0;i<mTemp.size();i++)
{
if (mTemp.get(i).newDatacus.get(NewData.TAG_CUSTOMER_CODE).toString().contains(constraint)) {
System.out.println("My datas"+mTemp.get(i).newDatacus.get(NewData.TAG_CUSTOMER_CODE).toString());
foundItems.add(mTemp.get(i));
}
else
{
}
}
}
result.count = foundItems.size();//search results found return count
result.values = foundItems;// return values
}
else
{
result.count=-1;// no search results found
}
return result;
}
};
}
public Myadapter(Context context) {
super(context, 0);
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// TODO Auto-generated constructor stub
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mPostingData.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(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
if(mOri == null ){
return null;
}
// When convertView is not null, we can reuse it directly, there is no need
// to reinflate it. We only inflate a new View when the convertView supplied
// by ListView is null.
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list, null);
convertView.setLayoutParams(new AbsListView.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
// Creates a ViewHolder and store references to the two children views
// we want to bind data to.
holder = new ViewHolder();
holder.t1=(TextView) convertView.findViewById(R.id.textView1);
holder.t2 = (TextView) convertView.findViewById(R.id.textView2);
holder.t3 = (TextView) convertView.findViewById(R.id.textView3);
convertView.setTag(holder);
} else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();
}
holder.t1.setText(mPostingData.get(position).newDatacus.get(NewData.TAG_CUSTOMER_CODE).toString());
holder.t2.setText(mPostingData.get(position).newDatacus.get(NewData.TAG_CUSTOMER_NAME).toString());
holder.t3.setText(mPostingData.get(position).newDatacus.get(NewData.TAG_CUSTOMER_MOBILE).toString());
return convertView;
}
}
class ViewHolder
{
TextView t1,t2,t3;
}
}
list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="20dp"
android:text="TextView" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="20dp"
android:text="TextView" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="20dp"
android:text="TextView" />
</LinearLayout>
NewData Class- Holds all data in hashmap
public class NewData {
public static final String TAG_CUSTOMER_CODE = "customer_code";
public static final String TAG_CUSTOMER_NAME = "customer_name";
public static final String TAG_CUSTOMER_MOBILE = "customer_mobile";
public static final String TAG_CUSTOMER_ADDRESS = "customer_address";
Hashtable newDatacus=new Hashtable();
public NewData()
{
newDatacus.put(NewData.TAG_CUSTOMER_CODE,new String());
newDatacus.put(NewData.TAG_CUSTOMER_ADDRESS,new String());
newDatacus.put(NewData.TAG_CUSTOMER_NAME,new String());
newDatacus.put(NewData.TAG_CUSTOMER_MOBILE,new String());
newDatacus.put(NewData.TAG_CUSTOMER_ADDRESS,new String());
}
}

Please try with the below code.
you must integrate this line .. where you are setting adapter .
listView.setAdapter(new MyAddapter(this));
array_sort.clear();
array_sort.addAll(Service_Listitems);
then use below lines.
edittext_search.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){
}
public void onTextChanged(CharSequence s, int start, int before, int count){
try {
Service_Listitems.clear();// Clear your arraylist initially
for (int i = 0; i < array_sort.size(); i++) {
if (array_sort.get(i) instanceof yourServiceSetterGetterClass) {
yourServiceSetterGetterClass cp1 = (yourServiceSetterGetterClass)array_sort.get(i);
String strOrig = "";
if (cp1.getFirstName() == null) {
strOrig = "";
} else {
strOrig = cp1.getFirstName().toUpperCase().trim();
}
String str = edittext_search.getText().toString().toUpperCase().trim();
if (strOrig.startsWith(str)) { Service_Listitems.add(cp1);
}
}
}
listView.setAdapter(new MyAddapter(this));
} catch (Exception e) {
e.printStackTrace();
}
}
});;
EDIT
ArrayList<CoordItem> Service_Listitems= new ArrayList<CoordItem>();
private ArrayList<Object> array_sort = new ArrayList<Object>();
or you can use like below also
private ArrayList<CoordItem> array_sort = new ArrayList<CoordItem>();

Related

No searching results after onTextChanged in android Listview [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I can't resolve this problem. I want to add search functionality by EditText. Results should dynamically display after typing letters but now there is no results.
Thanks for Your quick response :)
ParkingActivity.java
public class ParkingActivity extends FragmentActivity {
private final String URL_TO_HIT = "http://www-users.mat.umk.pl/~discordia/dane.json";
private ListView lvParking;
private EditText inputSearch;
public ParkingAdapter adapter;
public ArrayList<ParkingModel> parkingModelList = new ArrayList();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_activity);
lvParking = (ListView) findViewById(R.id.lvParking);
inputSearch = (EditText) findViewById(R.id.editText);
new JSONTask().execute(URL_TO_HIT);
}
public class JSONTask extends AsyncTask<String,String, List<ParkingModel> > {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected List<ParkingModel> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line ="";
while ((line = reader.readLine()) != null){
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("parkingInfo");
ArrayList<ParkingModel> parkingModelList = new ArrayList<>();
Gson gson = new Gson();
for(int i=0; i<parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
/**
* below single line of code from Gson saves you from writing the json parsing yourself which is commented below
*/
ParkingModel parkingModel = gson.fromJson(finalObject.toString(), ParkingModel.class);
parkingModelList.add(parkingModel);
}
return parkingModelList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if(connection != null) {
connection.disconnect();
}
try {
if(reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(final List<ParkingModel> result) {
super.onPostExecute(result);
if(result != null) {
adapter = new ParkingAdapter(getApplicationContext(), R.layout.row, result);
lvParking.setAdapter(adapter);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
ParkingActivity.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
lvParking.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ParkingModel parkingModel = result.get(position);
Intent intent = new Intent(ParkingActivity.this, DetailActivity.class);
intent.putExtra("parkingModel", new Gson().toJson(parkingModel));
startActivity(intent);
}
});
}
}
}
public class ParkingAdapter extends ArrayAdapter {
private List<ParkingModel> parkingModelList;
private int resource;
private LayoutInflater inflater;
public ParkingAdapter(Context context, int resource, List<ParkingModel> objects) {
super(context, resource, objects);
parkingModelList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if(convertView == null){
holder = new ViewHolder();
convertView = inflater.inflate(resource, null);
holder.tvLokalizacja = (TextView)convertView.findViewById(R.id.tvLokalizacja);
holder.tvIle_wolnych_zwyklych = (TextView)convertView.findViewById(R.id.tvIle_wolnych_zwyklych);
holder.tvIle_wszystkich_zwyklych = (TextView)convertView.findViewById(R.id.tvIle_wszystkich_zwyklych);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tvLokalizacja.setText(parkingModelList.get(position).getLokalizacja());
holder.tvIle_wolnych_zwyklych.setText("Wolne: " + parkingModelList.get(position).getIle_wolnych_zwyklych());
holder.tvIle_wszystkich_zwyklych.setText("Wszystkie:" + parkingModelList.get(position).getIle_wszystkich_zwyklych());
return convertView;
}
class ViewHolder{
private TextView tvLokalizacja;
private TextView tvIle_wolnych_zwyklych;
private TextView tvIle_wszystkich_zwyklych;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_parking, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
}
This is my model which I use to create final array with data.
ParkingModel.java
public class ParkingModel {
private String lokalizacja;
private int ile_wolnych_zwyklych;
private int ile_wszystkich_zwyklych;
public String getLokalizacja() {
return lokalizacja;
}
public void setLokalizacja(String lokalizacja) {
this.lokalizacja = lokalizacja;
}
public int getIle_wolnych_zwyklych() {
return ile_wolnych_zwyklych;
}
public void setIle_wolnych_zwyklych(int ile_wolnych_zwyklych) {
this.ile_wolnych_zwyklych = ile_wolnych_zwyklych;
}
public int getIle_wszystkich_zwyklych() {
return ile_wszystkich_zwyklych;
}
public void setIle_wszystkich_zwyklych(int ile_wszystkich_zwyklych) {
this.ile_wszystkich_zwyklych = ile_wszystkich_zwyklych;
}
}
Here is my xml file.
list_activity.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".ParkingActivity">
<EditText
android:layout_width="319dp"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:inputType="text"
android:layout_gravity="center_horizontal" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/lvParking" />
</LinearLayout>
Because in onPostExecute of JSONTask you have created new object of ParkingAdapter class and below that
ParkingActivity.this.adapter.getFilter().filter(cs); you are using this line.
this is always null;
To set adapter just use
adapter = new ParkingAdapter(getApplicationContext(), R.layout.row, result);
lvParking.setAdapter(adapter);
change this line
ParkingAdapter adapter = new ParkingAdapter(getApplicationContext(), R.layout.row, result);
To This
adapter = new ParkingAdapter(getApplicationContext(), R.layout.row, result);

Android filter listview custom adapter

Hello everybody I'm doing an app which has an edittext to search for items on the listview. If the user types a letter. The data come from my json string (database) and then display on my listview. So far this is what I've tried:
ListViewAdapter adapter2;
ArrayList<HashMap<String, String>> arraylist;
ArrayList<String> list = new ArrayList<String>();
wsSearch.addTextChangedListener(new TextWatcher (){
public void afterTextChanged(Editable cs) {
// TODO Auto-generated method stub
}
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
public void onTextChanged(CharSequence cs, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
//BAPTISMAL_SONG.this.adapter2.getFilter().filter(cs);
String searchString = cs.toString();
if(searchString.length() != 2) {
adapter2 = new ListViewAdapterBaptismal(BAPTISMAL_SONG.this, arraylist);
listview.setAdapter(adapter2);
return;
}
ArrayList<HashMap<String, String>> arrayTemplist = new ArrayList<HashMap<String,String>>();
for (int i = 0; i < arraylist.size(); i++)
{
String currentString = arraylist.get(i).get(BAPTISMAL_SONG.TAG_TITLE);
if (searchString.equalsIgnoreCase(currentString))
{
arrayTemplist.add(arraylist.get(i));
}
}
adapter2 = new ListViewAdapterBaptismal(BAPTISMAL_SONG.this, arrayTemplist);
listview.setAdapter(adapter2);
}
});
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
// Pass the results into ListViewAdapter.java
adapter2 = new ListViewAdapter(Activity2.this, arraylist);
// Binds the Adapter to the ListView
listview.setAdapter(adapter2);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
What I want to achieve, if the user types a letter like B, all the items that start with the said letter should be filtered. But using the code I posted above, it does not do exactly what I want. It just filters whenever I typed the whole item name. Any ideas? Your help will be greatly appreciated. Thanks.
As far as I can see you are only checking if the two Strings match exactly.
You might want to use boolean startsWith(String prefix)
Which would make something like
if (currentString.trim().toLowerCase().startsWith(searchString.trim().toLowerCase()))
{
arrayTemplist.add(arraylist.get(i));
}
I got complete solution, i put filter method in custom adapter for multiple fields search functionality.
Note: for image loading i took lazy loading so you need ImageLoader.java, FileCache.java, Utils.java and MemoryCache.java.
Check bellow code.....
list_layout.xml ( layout folder )
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
android:background="#ffffff" >
<EditText
android:id="#+id/et_search"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="search...."
android:paddingLeft="5dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
/>
<ListView
android:id="#+id/list_view"
android:layout_width="match_parent"
android:layout_marginTop="5dp"
android:layout_height="match_parent"
android:layout_below="#+id/et_search">
</ListView>
</RelativeLayout>
custom_row.xml ( layout folder )
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#33B5E5" >
<ImageView
android:id="#+id/image_view"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginBottom="23dp"
android:layout_marginLeft="23dp"
android:layout_marginTop="23dp"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/txt_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/image_view"
android:layout_marginLeft="15dp"
android:layout_toRightOf="#+id/image_view"
android:text="id"
android:textColor="#ffffff" />
<TextView
android:id="#+id/txt_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/txt_id"
android:layout_below="#+id/txt_id"
android:text="name"
android:textColor="#ffffff" />
</RelativeLayout>
put sample.json file in assets folder
sample.json
{
"sample":[
{
"id":"1",
"name":"nirav kalola",
"image":"http://www.wallpaperfunda.com/wp-content/uploads/2014/03/images-2.jpg",
"description":"def"
},
{
"id":"2",
"name":"abc",
"image":"http://www.wallpaperfunda.com/wp-content/uploads/2014/03/images-2.jpg",
"description":"abc"
},
{
"id":"3",
"name":"def",
"image":"http://www.wallpaperfunda.com/wp-content/uploads/2014/03/images-2.jpg",
"description":"ghi"
},
{
"id":"55",
"name":"ghi",
"image":"http://www.wallpaperfunda.com/wp-content/uploads/2014/03/images-2.jpg",
"description":"jkl"
},
{
"id":"5",
"name":"jkl",
"image":"http://www.wallpaperfunda.com/wp-content/uploads/2014/03/images-2.jpg",
"description":"mno"
},
{
"id":"11",
"name":"mno",
"image":"http://www.wallpaperfunda.com/wp-content/uploads/2014/03/images-2.jpg",
"description":"pqr"
},
{
"id":"10",
"name":"nirav007",
"image":"http://www.wallpaperfunda.com/wp-content/uploads/2014/03/images-2.jpg",
"description":"stu"
}
]
}
ListActivity.java ( src folder )
public class ListActivity extends Activity {
private ListView listView;
private ProgressDialog progressDialog;
private List<SampleData> sampleData;
private ArrayList<SampleData> sampleList;
private SampleAdapter sampleAdapter;
private EditText etSearch;
ArrayList<SampleData> arraylist = new ArrayList<SampleData>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_layout);
listView=(ListView) findViewById(R.id.list_view);
BackGroundTask bt = new BackGroundTask();
bt.execute();
etSearch=(EditText) findViewById(R.id.et_search);
etSearch.setSingleLine(true);
etSearch.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
String text = etSearch.getText().toString().toLowerCase(Locale.getDefault());
sampleAdapter.filter(text);
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
});
}
private class BackGroundTask extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute(){
super.onPreExecute();
progressDialog = new ProgressDialog(ListActivity.this);
progressDialog.setCancelable(false);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
#Override
protected String doInBackground(Void... arg0) {
try {
JSONObject jsonObject = new JSONObject(loadJSONFromAsset());
JSONArray jsonArray = jsonObject.getJSONArray("sample");
sampleData=new ArrayList<SampleData>();
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject jsonObjectInside = jsonArray.getJSONObject(i);
String id = jsonObjectInside.getString("id");
String name = jsonObjectInside.getString("name");
String imagePath = jsonObjectInside.getString("image");
String description = jsonObjectInside.getString("description");
sampleData.add(new SampleData(id, name, imagePath, description));
Log.e("id",id+"");
Log.e("name",name+"");
Log.e("imagPath",imagePath+"");
Log.e("description",description+"");
}
handlePostsList(sampleData);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
progressDialog.dismiss();
}
}// End of Background AsyncTask
private void handlePostsList(final List<SampleData> sampleData) {
this.sampleData = sampleData;
runOnUiThread(new Runnable() {
public void run() {
try {
// logic for retrieve data first time in list view.
sampleList = new ArrayList<SampleData>();
for (int i = 0; i < sampleData.size(); i++) {
sampleList.add(new SampleData(sampleData.get(i).getId().toString(),sampleData.get(i).getName().toString(),sampleData.get(i).getImage().toString(),sampleData.get(i).getDescription().toString()));
}
sampleAdapter= new SampleAdapter(ListActivity.this, sampleList);
listView.setAdapter(sampleAdapter);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public class SampleAdapter extends BaseAdapter
{
Context context;
List<SampleData> sampleData=null;
ArrayList<SampleData> arraylist;
LayoutInflater inflater;
ImageLoader imageLoader;
public SampleAdapter(Context context, List<SampleData> sampleData) {
this.context = context;
this.sampleData = sampleData;
this.arraylist = new ArrayList<SampleData>();
this.arraylist.addAll(sampleData);
imageLoader=new ImageLoader(ListActivity.this);
}
public class ViewHolder {
TextView txtID,txtName,txtDescription;
ImageView image;
}
public int getCount() {
return sampleData.size();
}
public Object getItem(int position) {
return sampleData.get(position);
}
public long getItemId(int position) {
return sampleData.indexOf(getItem(position));
}
public View getView(final int position, View convertView, ViewGroup parent)
{
final ViewHolder holder;
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.custom_row, null);
holder = new ViewHolder();
holder.txtID = (TextView) convertView.findViewById(R.id.txt_id);
holder.txtName = (TextView) convertView.findViewById(R.id.txt_name);
holder.image = (ImageView) convertView.findViewById(R.id.image_view);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.txtID.setText(sampleData.get(position).getId());
holder.txtName.setText(sampleData.get(position).getName());
imageLoader.DisplayImage(sampleData.get(position).getImage(), holder.image);
// convertView.setOnClickListener(new OnClickListener() {
// Intent intent=null;
// #Override
// public void onClick(View v) {
// Log.e("description....",sampleData.get(position).getDescription()+"");
// intent=new Intent(ListActivity.this, DetailActivity.class);
// intent.putExtra("description", sampleData.get(position).getDescription());
// startActivity(intent);
// finish();
// }
// });
return convertView;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
sampleData.clear();
if (charText.length() == 0) {
sampleData.addAll(arraylist);
} else {
for (SampleData st : arraylist) {
if (st.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
sampleData.add(st);
}else if (st.getId().toLowerCase(Locale.getDefault()).contains(charText)) {
sampleData.add(st);
}
else if (st.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
sampleData.add(st);
}
}
}
notifyDataSetChanged();
}
}
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("sample.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
}
SampleData.java ( src folder )
public class SampleData
{
private String id;
private String name;
private String image;
private String description;
public SampleData(String id, String name, String image, String description) {
super();
this.id = id;
this.name = name;
this.image = image;
this.description = description;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
add following permissions in AndroidManifest.xml file
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
thats it..
enjoy coding
//Main Activity
Intent intent = new Intent(getApplicationContext(),
ListActivity.class);
intent.putExtra("name", name);
intent.putExtra("number", number);
startActivity(intent);
Then
ListActivity.class
EditText search;
ListView lvDetail;
Contact data;
MyBaseAdapter adapter;
ArrayList<Contact> myList = new ArrayList<Contact>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
lvDetail = (ListView) findViewById(R.id.lvCustomList);
search = (EditText) findViewById(R.id.inputSearch);
String[] name = getIntent().getStringArrayExtra("name");
String[] number = getIntent().getStringArrayExtra("number");
// System.out.println((1>2?1:(1==2?1:(2>3?2:3))));
for (int i = 0; i < name.length; i++) {
data = new Contact();
data.setName(name[i]);
data.setPhonenum(number[i]);
data.setImgResId(img[i]);
myList.add(data);
}
adapter = new MyBaseAdapter(getApplicationContext(), myList);
lvDetail.setAdapter(adapter);
lvDetail.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
search.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int start, int before,
int count) {
String text = search.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
#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
}
});
}
//Custom Adapter
public class MyBaseAdapter extends BaseAdapter {
ArrayList<Contact> myList = new ArrayList<Contact>();
LayoutInflater inflater;
Context context;
private ArrayList<Contact> privatearray;
public MyBaseAdapter(Context context,ArrayList<Contact> myList) {
this.myList = myList;
this.context = context;
inflater = LayoutInflater.from(this.context);
privatearray=new ArrayList<Contact>();
privatearray.addAll(myList);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return myList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return myList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View view, ViewGroup arg2) {
//LayoutInflater inflater = getLayoutInflater();
View row;
row = inflater.inflate(R.layout.layout_list_item, arg2, false);
TextView title, detail;
ImageView i1;
i1=(ImageView)row.findViewById(R.id.ivIcon);
title = (TextView) row.findViewById(R.id.name);
detail = (TextView) row.findViewById(R.id.phonenumber);
i1=(ImageView)row.findViewById(R.id.ivIcon);
//ListActivity activity=(ListActivity)Arrays.asList(myList)[0];
//ListData data=myList.get(0);
// Log.d("list", String.valueOf(myList.size())+" "+String.valueOf(data.getDescription()));
i1.setImageResource(myList.get(position).getImgResId());
title.setText(myList.get(position).getName());
detail.setText(myList.get(position).getPhonenum());
return (row);
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
myList.clear();
if(charText.length()==0){
myList.addAll(privatearray);
}
else{
for (Contact c : privatearray) {
if (c.getName().toLowerCase(Locale.getDefault())
.contains(charText)) {
myList.add(c);
}
}
}
notifyDataSetChanged();
}
}
//and Model
public class Contact {
String phonenum;
String name;
int imgResId;
public String getPhonenum() {
return phonenum;
}
public void setPhonenum(String phonenum) {
this.phonenum = phonenum;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getImgResId() {
return imgResId;
}
public void setImgResId(int imgResId) {
this.imgResId = imgResId;
}
}
You could give this a try:
public class MyAdapter extends ArrayAdapter<Model> {
public MyAdapter(Context context, int textViewResourceId,
List<model> objects) {
super(context, textViewResourceId, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView tx = (TextView)convertView;
SpannableString text = getItem(position);
for(char:typedChar)
if(tx.getText().contains(char)){
// make "text" (characters pos-1 to pos) red
text.setSpan(new ForegroundColorSpan(Color.RED),
tx.getText().indexOf(char) - 1, tx.getText().indexOf(char), 0);
textView.setText(text, BufferType.SPANNABLE);
}
}
}
Then Finally Register Editext here:
edit.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable s) {
//Modify letter here by simple parsing
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){}
});
Hope this could help you ...
Update your own code only:
searchString = searchString.trim().toLowerCase();
for (int i = 0; i < arraylist.size(); i++)
{
String currentString = arraylist.get(i).get(BAPTISMAL_SONG.TAG_TITLE).trim().toLowerCase();
if (currentString.startsWith(searchString))
{
arrayTemplist.add(arraylist.get(i));
}
}
The code below maybe help you.
private ArrayList<HashMap<String, String>> arrayDatalist = new ArrayList<HashMap<String,String>>();
...
#Override
protected void onCreate(Bundle savedInstanceState) {
....
arrayDatalist.addAll(arraylist);
adapter2 = new ListViewAdapterBaptismal(BAPTISMAL_SONG.this, arrayDatalist);
listview.setAdapter(adapter2);
searchInput.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){
if (searchInput.isEnabled()){
searchString = searchInput.getText().toString().trim().toLowerCase();
if (searchLocationOperation!=null && searchLocationOperation.getStatus().equals(Status.RUNNING)){
searchLocationOperation.cancel(true);
}
searchLocationOperation = new SearchLocationOperation(searchString);
searchLocationOperation.execute();
}
}
});
}
private class SearchLocationOperation extends AsyncTask<Void, Void, String> {
private ArrayList<HashMap<String, String>> searchResult = new ArrayList<HashMap<String,String>>();
private String searchString;
public SearchLocationOperation(String str){
searchString = str;
}
#Override
protected String doInBackground(Void... params) {
if (searchString.length() <= 2) {
searchResult.addAll(arraylist);
}else{
for (HashMap<String, String> rowItem: arraylist)
{
//if (rowItem.get(BAPTISMAL_SONG.TAG_TITLE).toLowerCase().contains(searchString)) //If get filter with any part of the name
if (rowItem.get(BAPTISMAL_SONG.TAG_TITLE).toLowerCase().startWiths(searchString))
{
searchResult.add(rowItem);
}
if (isCancelled()) return null;
}
}
return null;
}
#Override
protected void onPreExecute() {
//Show progress if needed
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
//Hide progress if showed
if (!isCancelled() && arrayDatalist!=null && adapter2!=null){
arrayDatalist.clear();
arrayDatalist.addAll(searchResult);
adapter2.notifyDataSetChanged();
}
super.onPostExecute(result);
}
}
arrayTemplist.clear();
for (int i = 0; i < mainArray.size(); i++) {
if (searchString.length()<= mainArray.get(i).length()) {
if (editText
.getText()
.toString()
.equalsIgnoreCase(
(String) mainArray.get(i).subSequence(0,
searchString.length()))) {
arrayTemplist.add(mainArray.get(i));
}
}
}
adapter = new ListViewAdapterBaptismal(BAPTISMAL_SONG.this, arrayTemplist);
listview.setAdapter(adapter);
adapter.notifyDataSetChanged();
use this `onTextChanged() method, might be it will help you.

Listview with filter

i am trying to filter the listview using edit text at the top but it providing null pointer exception in the adapter2.filter(text) of add text changed listener . please provide me some suggestion`
Here is my edit text`
friendsList.setAdapter(new FriendListAdapter(this));
search.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = search.getText().toString().toLowerCase(Locale.getDefault());
System.out.println("test=="+text);
adapter2.filter(text);
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
//adapter.getFilter().filter(arg0.toString());
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
Here is my adapter
public class FriendListAdapter extends BaseAdapter {
private LayoutInflater mInflater;
FriendsList friendsList;
Context context;
ViewHolder holder;
private boolean userSelected = false;
private RadioButton mCurrentlyCheckedRB;
private int mResourceId = 0;
private LayoutInflater mLayoutInflater;
private RadioButton mSelectedRB;
private int mSelectedPosition = -1;
public FriendListAdapter(FriendsList friendsList) {
this.friendsList = friendsList;
if (Utility.model == null) {
Utility.model = new FriendsGetProfilePics();
}
Utility.model.setListener(this);
mInflater = LayoutInflater.from(friendsList.getBaseContext());
}
#Override
public int getCount() {
return jsonArray.length();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup viewgroup) {
JSONObject jsonObject = null;
Model model = (Model) getItem(position);
try {
jsonObject = jsonArray.getJSONObject(position);
} catch (JSONException e1) {
e1.printStackTrace();
}
View hView = convertView;
if (convertView == null) {
hView = mInflater.inflate(R.layout.friend_item, null);
ViewHolder holder = new ViewHolder();
holder.profile_pic = (ImageView) hView
.findViewById(R.id.profile_pic);
holder.name = (TextView) hView.findViewById(R.id.name);
holder.info = (TextView) hView.findViewById(R.id.info);
holder.radiobt = (RadioButton) hView.findViewById(R.id.radio);
hView.setTag(holder);
}
ViewHolder holder = (ViewHolder) hView.getTag();
if (position == getCount() - 1 && userSelected == false) {
holder.radiobt.setChecked(true);
mCurrentlyCheckedRB = holder.radiobt;
} else {
holder.radiobt.setChecked(false);
}
holder.radiobt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if((position != mSelectedPosition && mSelectedRB != null)){
mSelectedRB.setChecked(false);
}
mSelectedPosition = position;
mSelectedRB = (RadioButton)v;
System.out.println("onItemClick ");
try {
if (graph_or_fql.equals("graph")) {
System.out.println("in if loop ");
friendId = jsonArray.getJSONObject(position).getLong("id");
image = jsonArray.getJSONObject(position).getString("picture");
// sb.append(friendId).append(",");
freind_id = String.valueOf(friendId);
} else {
System.out.println("in else loop ");
friendId = jsonArray.getJSONObject(position).getLong("uid");
image = jsonArray.getJSONObject(position).getString(
"pic_square");
// sb.append(friendId).append(",");
freind_id = String.valueOf(friendId);
}
check = true;
name = jsonArray.getJSONObject(position).getString("name");
Toast.makeText(getApplicationContext(), "You Selected : " + name,
Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
e.getMessage();
}
}
});
if(mSelectedPosition != position){
holder.radiobt.setChecked(false);
}else{
holder.radiobt.setChecked(true);
if(mSelectedRB != null && holder.radiobt != mSelectedRB){
mSelectedRB = holder.radiobt;
}
}
try {
if (graph_or_fql.equals("graph")) {
holder.profile_pic.setImageBitmap(Utility.model.getImage(
jsonObject.getString("id"),
jsonObject.getString("picture")));
} else {
holder.profile_pic.setImageBitmap(Utility.model.getImage(
jsonObject.getString("uid"),
jsonObject.getString("pic_square")));
}
} catch (JSONException e) {
holder.name.setText("");
}
try {
holder.name.setText(jsonObject.getString("name"));
} catch (JSONException e) {
holder.name.setText("");
}
try {
if (graph_or_fql.equals("graph")) {
holder.info.setText(jsonObject.getJSONObject("location")
.getString("name"));
} else {
JSONObject location = jsonObject
.getJSONObject("current_location");
holder.info.setText(location.getString("city") + ", "
+ location.getString("state"));
}
} catch (JSONException e) {
holder.info.setText("");
}
return hView;
}
// Filter Class
public void filter(String charText) {
System.out.println("in adapter filter");
charText = charText.toLowerCase(Locale.getDefault());
System.out.println("1");
rowitems.clear();
System.out.println("2");
if (charText.length() == 0) {
System.out.println("3");
rowitems.addAll(listData);
} else {
for (Model wp : listData) {
if (wp.getName().toLowerCase(Locale.getDefault())
.contains(charText)) {
rowitems.add(wp);
}
}
}
notifyDataSetChanged();
}
private class ViewHolder {
ImageView profile_pic;
TextView name;
TextView info;
// CheckBox check;
RadioButton radiobt;
}
}
Here is my main activity
public class FriendsList extends Activity implements OnItemClickListener{
private Handler mHandler;
public static Long friendId;
public static String name = "";
protected ListView friendsList;
protected static JSONArray jsonArray;
protected String graph_or_fql;
public Button bt;
public static String image = "0";
public boolean check = false;
public static String freind_id = "";
public boolean select = false;
public RadioButton radiobtn;
public ListView friendList;
private List<Model> rowitems=null;
ArrayList<Model> listData;
AdapterList adapter;
EditText search;
FriendListAdapter adapter2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHandler = new Handler();
setContentView(R.layout.friends_list);
//radioSexGroup = (RadioGroup) findViewById(R.id.radioSex);
bt = (Button) findViewById(R.id.com_facebook_picker_done_button);
radiobtn = (RadioButton) findViewById(R.id.radio);
search=(EditText) findViewById(R.id.editText100);
Bundle extras = getIntent().getExtras();
String apiResponse = extras.getString("API_RESPONSE");
graph_or_fql = extras.getString("METHOD");
try {
if (graph_or_fql.equals("graph")) {
jsonArray = new JSONObject(apiResponse).getJSONArray("data");
} else {
jsonArray = new JSONArray(apiResponse);
}
} catch (JSONException e) {
e.printStackTrace();
e.getMessage();
return;
}
friendsList = (ListView) findViewById(R.id.friends_list);
// friendsList.setAdapter(new FriendListAdapter(this));
adapter2=new FriendListAdapter(this);
friendsList.setAdapter(adapter2);
friendsList.setOnItemClickListener(this);
search.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
adapter2.getFilter().filter(arg0.toString());
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
i am passing the facebook friend list to the listview.please provide some suggestion
Thanks in advance
For filter the listview using edit text at the top .
I used this code.
Make one list called searchResults than in onTextChanged method of edittext simply do this-
String searchString = `your edittext object`.getText().toString();
int textLength = searchString.length();
searchResults.clear();
for (int i = 0; i < `your main list of items`.size(); i++) {
String name = `your main list of items`.get(i).get("`your key`").toString();
System.out.println(" name " + name);
if (textLength <= title.length()) {
// compare the String in EditText with Names in the
// ArrayList
if (searchString.equalsIgnoreCase(name.substring(0, textLength))) {
searchResults.add(`your main list of items`.get(i));
System.out.println("the array list is "+ `your main list of items`.get(i));
mAdapter = new Adapter(this, searchResults);
`your ListView object`.setAdapter(mAdapter);
}
}
}
if (searchResults.isEmpty()) {
Toast toast = Toast.makeText(getApplicationContext(),"No Items Matched",Toast.LENGTH_SHORT);
toast.show();
mAdapter = new Adapter(this, searchResults);
`your ListView object`.setAdapter(mAdapter);
}
mAdapter.notifyDataSetChanged();
and on setOnItemClickListener just check searchResults.isEmpty() if true than use your your main list of items and if false than use searchResults list.
May be it will help you.try this.
change your filter with following code:
#Override
public Filter getFilter() {
//Log.d("in filter", "yes");
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
final FilterResults oReturn = new FilterResults();
and set your list in this function and after set your list :
oReturn.values = YourList;
and finall
return oReturn;
and in Your search.addTextChangedListener(new TextWatcher()) just in onTextChanged add following line:
adapter2.getFilter().filter(s.toString());
Try this,
adapter2=new FriendListAdapter(this);
friendsList.setAdapter(adapter2);

how custom listview search i do not pass array list to custom listview class

Edit: this answer is not suitable for me , i need more answer according to my condition, Thanks
How to search with custom listview when I call list view I don't pass array with it.
Now I want to perform search on Name and mobile number, please help how could I achieve it?
name and mobile number have check box , if name checkbox is select then search name if mobile number checkbox is checked then search mobile number
public class AndroidJSONParsingActivity extends ListActivity {
// JSON Node names
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ID = "id";
private static final String TAG_PHONE_MOBILE = "mobile";
EditText search;
int textlength=0;
ListView lv;
ArrayList<String> text_sort = new ArrayList<String>();
ArrayList<Integer> image_sort = new ArrayList<Integer>();
ListViewAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//access the controls
showList();
CheckBox Name = (CheckBox) findViewById(R.id.checkBox1);
CheckBox Mobile = (CheckBox) findViewById(R.id.checkBox2);
if(Name.isChecked()==true){
//search on name
}
if(Mobile.isChecked()==true){
//search on mobile
}
Button addnew = (Button) findViewById(R.id.btnAddNew);
// selecting single ListView item
lv = getListView();
addnew.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getApplicationContext(), Insrt.class);
startActivity(intent);
}
});
search = (EditText)findViewById(R.id.etSearch);
search.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
adapter.getFilter().filter(s);
adapter.notifyDataSetChanged();
}
});
}
private void showList() {
// TODO Auto-generated method stub
ListAdapter adapter = new ListViewAdapter(this);
setListAdapter(adapter);
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long ids) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
String id = ((TextView) view.findViewById(R.id.id)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
in.putExtra(TAG_ID, id);
startActivity(in);
}
});
}
}
now i want to perform search on NAME and mobile number, please help how i did it?, please help
public class ListViewAdapter extends ArrayAdapter {
private Filter filter;
public ListViewAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
// TODO Auto-generated constructor stub
}
#Override
public Filter getFilter()
{
if (filter == null)
filter = new PkmnNameFilter();
return filter;
}
// url to make request
private static String url = "https://abc.net/api/api/employees/";
// JSON Node names
ArrayList<String> TAG_ID= new ArrayList<String>();
ArrayList<String> TAG_NAME= new ArrayList<String>();
ArrayList<String> TAG_EMAIL= new ArrayList<String>();
ArrayList<String> TAG_PHONE_MOBILE= new ArrayList<String>();
static Context context;
JSONArray employee = null;
String id,name,email,mobile;
ArrayList<Integer> close =new ArrayList<Integer>();
private Activity activity;
ViewHolder view;
//constructor
public ListViewAdapter(Activity activity)
{
super(context, 0);
this.activity = activity;
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Employee
employee = json.getJSONArray("Employee");
// looping through All Employee
for(int i = 0; i < employee.length(); i++)
{
JSONObject c = employee.getJSONObject(i);
// Storing each json item in variable
id = String.valueOf(c.getInt("Id"));
name = c.getString("Name");
email = c.getString("Email");
mobile = c.getString("Mobile");
//adding all get values into array
if(name!="null"&&mobile!="null"){
TAG_NAME.add(name);
TAG_ID.add(id);
TAG_EMAIL.add(email);
TAG_PHONE_MOBILE.add(mobile);
close.add(R.drawable.close);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return TAG_NAME.size();
}
#Override
public Object getItem(int paramInt) {
// TODO Auto-generated method stub
return TAG_NAME.size();
}
#Override
public long getItemId(int paramInt) {
// TODO Auto-generated method stub
return 0;
}
public static class ViewHolder {
public ImageView deleteButtonImg;
public TextView name,email,mobile,id;
}
#Override
public View getView(final int paramInt, View paramView, final ViewGroup paramViewGroup) {
// TODO Auto-generated method stub
LayoutInflater inflator = activity.getLayoutInflater();
if (paramView == null) {
view = new ViewHolder();
paramView = inflator.inflate(R.layout.list_item, null);
view.name = (TextView) paramView.findViewById(R.id.name);
view.email = (TextView) paramView.findViewById(R.id.email);
view.mobile = (TextView) paramView.findViewById(R.id.mobile);
view.id = (TextView) paramView.findViewById(R.id.id);
view.deleteButtonImg = (ImageView) paramView.findViewById(R.id.ibclose);
paramView.setTag(view);
} else {
view = (ViewHolder) paramView.getTag();
}
view.name.setText(TAG_NAME.get(paramInt));
view.email.setText(TAG_EMAIL.get(paramInt));
view.mobile.setText(TAG_PHONE_MOBILE.get(paramInt));
view.deleteButtonImg.setImageResource(close.get(paramInt));
view.id.setText(TAG_ID.get(paramInt));
view.name.setFocusableInTouchMode(false);
view.name.setFocusable(false);
view.deleteButtonImg.setFocusableInTouchMode(false);
view.deleteButtonImg.setFocusable(false);
view.deleteButtonImg.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
DefaultHttpClient client = new DefaultHttpClient();
SchemeRegistry registry = new SchemeRegistry();
SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
registry.register(new Scheme("https", socketFactory, 443));
SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());
HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
HttpDelete httpDelete = new HttpDelete("https://abc.net/api/api/employees/"+TAG_ID.get(paramInt));
httpDelete.setHeader("content-type", "application/json");
JSONObject data = new JSONObject();
try {
data.put("Id", TAG_ID.get(paramInt));
/*StringEntity entity = new StringEntity(data.toString());
httpPost.setEntity(entity);*/
HttpResponse response = httpClient.execute(httpDelete);
String responseString = EntityUtils.toString(response.getEntity());
//int workoutId = responseJSON.getInt("id");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
TAG_NAME.remove(paramInt);
TAG_EMAIL.remove(paramInt);
TAG_PHONE_MOBILE.remove(paramInt);
TAG_ID.remove(paramInt);
close.remove(paramInt);
notifyDataSetChanged();
}
});
return paramView;
}
private class PkmnNameFilter extends Filter
{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
// We implement here the filter logic
if (constraint == null || constraint.length() == 0) {
// No filter implemented we return all the list
results.values = TAG_NAME;
results.count = TAG_NAME.size();
}
else {
// We perform filtering operation
List<Object> nPlanetList = new ArrayList<Object>(TAG_NAME);
for (Object p : TAG_NAME) {
if (((Scheme) p).getName().toUpperCase().startsWith(constraint.toString().toUpperCase()))
nPlanetList.add(p);
}
results.values = nPlanetList;
results.count = nPlanetList.size();
}
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
final ArrayList<String> localItems = (ArrayList<String>) results.values;
notifyDataSetChanged();
clear();
for (Iterator<String> iterator = localItems.iterator(); iterator
.hasNext();) {
String gi = (String) iterator.next();
add(gi);
}
}
}
}
I searched on google but I didn't understand how to implement in this ?
Rohit -
Sorry, but at a glance, I see a number of potential problems. Without time to build and run your code, I can only guess about your specific requirements. I'll address the first two opportunities for re-factoring. My gut thinks you'll find the answer in the process.
First, you are calling a method called, "showList()" before your activity has initialized. (In my opinion, you should be calling this method later. For example, in onResume.)
Then you are creating local reference variables which will not be in scope after onCreate runs (which occurs one and only one time per instance).
BTW, I find this sort of problem much easier to solve when inline class definitions (e.g. new View.OnClickListener) resolve to a proper, named class and/or instances of the class are member variables. If such changes might create memory management issues, you can optimize after your program is working as a user would expect.
Good luck!
-Brandon
You need to pass the string that is being typed in editext to your filter
youradapter.getFilter().filter(s);
youradapter.notifyDataSetChanged();
Override getFilter() and performFiltering(params) in your adapter class
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count >= 0) {
//set reeulst
} else {
// set original values
}
notifyDataSetInvalidated();
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults result = new FilterResults();
if (!TextUtils.isEmpty(constraint)) {
ArrayList<type> foundItems = new ArrayList<type>();
//do something
//filter resutls
}
result.count = foundItems.size();//search results found return count
result.values = foundItems;// return values
else
{
result.count=-1;// no search results found
}
return result;
}
Edit:
public class MainActivity extends Activity {
EditText search;
ListView lv;
CustomAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv=(ListView) findViewById(R.id.lv);
adapter = new CustomAdapter(this,0);
search = (EditText)findViewById(R.id.editText1);
search.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
adapter.getFilter().filter(s);
adapter.notifyDataSetChanged();
}
});
}
class CustomAdapter extends ArrayAdapter
{
public CustomAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
// TODO Auto-generated constructor stub
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
return super.getView(position, convertView, parent);
}
#Override
public Filter getFilter() {
// TODO Auto-generated method stub
return super.getFilter();
}
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:ems="10" />
<ListView
android:id="#+id/lv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/editText1" >
</ListView>
</RelativeLayout>
Edit :
Heres's the link of the working code
Search in ListView with EditText
I don't know if someone will code for you. But if you try you should be able to make changes to implement the same in your code..

Using filter in listview adapter inflate

I'm having problem I can not do a search on my listview!
I tried to implement listview with inflate and do a search, but unfortunately I could not ... There appears no error in the logcat and tried to debug but unfortunately apparently it's alright ... Simply write when not in textview in listview filtar begins ...
Below is my code
FriendRequestListener.class
/*
* callback after friends are fetched via me/friends.
*
*/
public class FriendsRequestListener extends BaseRequestListener {
#Override
public void onComplete(final String response, final Object state) {
dialog.dismiss();
try{
arrayName = new ArrayList<String>();
jsonArray = new JSONObject(response).getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json_data = jsonArray.getJSONObject(i);
if(json_data.has("name")){
String getFriendName = json_data.getString("name");
arrayName.add(getFriendName);
}else{
String getFriendName = null;
arrayName.add(getFriendName);
}
}
}catch(JSONException e){
Log.d(TAG, e.getMessage());
return;
}
stringName = new String[arrayName.size()];
stringName = arrayName.toArray(stringName);
EscolhaAmigosFacebook.this.runOnUiThread(new Runnable() {
#Override
public void run() {
adapter = new FriendListAdapter(EscolhaAmigosFacebook.this, stringName, arrayName);
friendsListView.setTextFilterEnabled(true);
friendsListView.setAdapter(adapter);
}
});
}
FriendApapter.class
/**
* Definition of the list adapter
*/
public class FriendListAdapter extends BaseAdapter implements Filterable {
String[] fetFriendName;
List<String> arrayList;
List<String> mOriginalValues;
LayoutInflater mInflater = null;
EscolhaAmigosFacebook friendsList;
FriendListAdapter(EscolhaAmigosFacebook friendsList, String[] stringName, ArrayList<String> arrayName) {
this.friendsList = friendsList;
if (Utility.model == null) {
Utility.model = new FriendsGetProfilePics();
}
Utility.model.setListener(this);
fetFriendName = stringName;
arrayList = new ArrayList<String>();
mOriginalValues = arrayName;
mInflater = LayoutInflater.from(friendsList.getBaseContext());
}
#Override
public int getCount() {
return mOriginalValues.size();
}
#Override
public Object getItem(int position) {
return mOriginalValues.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
JSONObject jsonObject = null;
final ViewHolder holder;
View vi = convertView;
try {
jsonObject = jsonArray.getJSONObject(position);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (vi == null) {
vi = mInflater.inflate(R.layout.friend_item, null);
holder = new ViewHolder();
holder.profile_pic = (ImageView) vi.findViewById(R.id.profile_pic);
TextView txtFriendsName = (TextView)vi.findViewById(R.id.name);
txtFriendsName.setText(fetFriendName[position]);
vi.setTag(holder);
}else{
holder = (ViewHolder) vi.getTag();
}
try {
holder.profile_pic.setImageBitmap(Utility.model.getImage(
jsonObject.getString("id"), jsonObject.getString("picture")));
} catch (JSONException e) {
holder.name.setText("");
}
return vi;
}
#Override
public Filter getFilter() {
Filter filter = new Filter(){
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
arrayList = (List<String>) results.values;
notifyDataSetChanged();
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
List<String> FilteredArrList = new ArrayList<String>();
if (constraint == null || constraint.length() == 0) {
results.count = mOriginalValues.size();
results.values = mOriginalValues;
} else {
constraint = constraint.toString();
for (int i = 0; i < mOriginalValues.size(); i++) {
String data = mOriginalValues.get(i);
if (data.toLowerCase().startsWith(constraint.toString())) {
FilteredArrList.add(data);
}
}
results.count = FilteredArrList.size();
results.values = FilteredArrList;
}
return results;
}
};
return filter;
}
}
Method onComplete
et_search = (EditText) findViewById(R.id.et_Search);
et_search.addTextChangedListener(filterTextWatcher);
}
private TextWatcher filterTextWatcher = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
adapter.getFilter().filter(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
};
I know it looked great, but if anyone has the patience to help me, please!
I've tried looking at various posts but got nothing!
I haven't used Filter yet on an adapter, but I've used adapter a lot and from what I can tell after filtering you put the results on the arraylist, but you don't use arrayList on the getCount, getItem, getView, so the filter you created on the data is not used, but the full list of items.

Categories

Resources