i want to make search data that i want to show from my database into list view.
but first i must type in in search view then parsing it in list view, not parsing file then filter the list.
here is my Main Activity code:
public class MainActivity extends Activity{
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
static String FIRSTNAME = "First_Name_Person";
private List<Person> personlist = null;
SearchView searchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listviewmain);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setOnQueryTextListener(new OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
new DownloadXML().execute();
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
// TODO Auto-generated method stub
return false;
}
});
return true;
}
private class DownloadXML extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setTitle("Sabar");
mProgressDialog.setMessage("Ambil");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
personlist = new ArrayList<Person>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl("http://10.0.2.2/getall.xml");
Document doc = parser.getDomElement(xml);
try {
NodeList nl = doc.getElementsByTagName("Person");
for (int i = 0; i < nl.getLength(); i++) {
Element e = (Element) nl.item(i);
Person map = new Person();
map.setFirstname(parser.getValue(e, FIRSTNAME));
personlist.add(map);
}
} catch (Exception e) {
// TODO: handle exception
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args){
listview = (ListView) findViewById(R.id.listView);
adapter = new ListViewAdapter(MainActivity.this, personlist);
listview.setAdapter(adapter);
mProgressDialog.dismiss();
}
}
}
then this is my adapter list
public class ListViewAdapter extends BaseAdapter {
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
private List<Person> personlist = null;
private ArrayList<Person> arraylist;
public ListViewAdapter(Context context, List<Person> personlist) {
// TODO Auto-generated constructor stub
this.context = context;
this.personlist = personlist;
inflater = LayoutInflater.from(context);
this.arraylist = new ArrayList<Person>();
this.arraylist.addAll(personlist);
}
public class ViewHolder{
TextView firstname;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return personlist.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return personlist.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View view, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listview, null);
holder.firstname = (TextView) view.findViewById(R.id.firstname);
view.setTag(holder);
} else{
holder = (ViewHolder) view.getTag();
}
holder.firstname.setText(personlist.get(position).getFirstname());
return view;
}
public void filter(String chartext) {
// TODO Auto-generated method stub
chartext = chartext.toLowerCase(Locale.getDefault());
personlist.clear();
if (chartext.length() == 0) {
personlist.addAll(arraylist);
} else {
for (Person ps : arraylist){
if (ps.getFirstname().toLowerCase(Locale.getDefault()).contains(chartext)){
personlist.add(ps);
}
}
}
}
}
please help me..
Related
Here is my code:
public class MainActivity extends Activity implements OnQueryTextListener {
ListView list ;
ListAdapter listAdapter;
ArrayList<String> listTest;
String name;
Uri uri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView)findViewById(R.id.list);
listTest = new ArrayList<String>( );
list.setTextFilterEnabled(true);
Scanner(Environment.getRootDirectory()+"/");
if(listTest.size() != 0)
{
listAdapter=new ListAdapter(getApplicationContext(),listTest);
list.setAdapter(listAdapter);
list.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
name = (String) ((TextView) view).getText();
view.setSelected(true);
uri = Uri.parse(listTest.get(position).toString());
File fl = new File(uri.toString());
deleteFile(uri.toString());
Log.e("msg", "deleted");
Toast.makeText(getApplicationContext(), name+".apk"+" is deleted from internal storage", Toast.LENGTH_SHORT).show();
/*if(fl.exists())
{
fl.delete();
Log.e("msg", "deleted");
Toast.makeText(getApplicationContext(), name+".apk"+" is deleted from internal storage", Toast.LENGTH_SHORT).show();
}*/
list.setSelection(position);
}});
}
}
private void Scanner(String path) {
// TODO Auto-generated method stub
{
try
{
File fl = new File(path);
File[] listOfFiles = fl.listFiles();
for (File listOfFile : listOfFiles)
{
String s = listOfFile.getName();
if(s.endsWith(".apk"))
{
// store file name in listSoundNames
int pos = s.lastIndexOf(".");
if (pos > 0)
{
name = s.substring(0, pos);
}
listTest.add(name);
}
/////////////////////////////////
File f = new File(path+s+"/");
if (f.exists() && f.isDirectory()) {
Scanner(path+s+"/");
}
////////////////////////////////
}
}
catch (Exception e) { }
}
}
/* private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
};
*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
// Inflate menu to add items to action bar if it is present.
inflater.inflate(R.menu.main, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =
(SearchView) menu.findItem(R.id.menu_search).getActionView();
searchView.setSubmitButtonEnabled(true);
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName()));
//Sets the hint text to display in the query text field
searchView.setQueryHint("...");
searchView.setOnQueryTextListener(this);
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
// TODO Auto-generated method stub
listAdapter.getFilter().filter(newText);
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
return true;
}
/*
#Override
public boolean onQueryTextChange(String newText) {
// TODO Auto-generated method stub
if (TextUtils.isEmpty(newText)) {
//clear text filter so that list displays all items
list.clearTextFilter();
} else {
// apply filter so that list displays only
//matching child items
//list.setFilterText(newText.toString());
//listTest.addTextChangedListener(filterTextWatcher);
//listAdapter.notifyDataSetChanged();
//list.setSelectionAfterHeaderView();
}
listAdapter.getFilter().filter(newText);
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), query, Toast.LENGTH_SHORT).show();
return true;
}
*/
}
ListAdapter.java
public class ListAdapter extends BaseAdapter implements Filterable{
private List<Item> filteredData;
private Context _context;
private List<String> list;
ViewHolder holder=null;
View row=null;
private ItemFilter mFilter = new ItemFilter();
private LayoutInflater mInflater;
private List<Item> items;
/*public ListAdapter(Context _context,List<String> list,List<Item> items)
{
this._context=_context;
this.list=list;
this.items=items;
}*/
public ListAdapter(Context _context,List<String> list)
{
this._context=_context;
this.list=list;
mInflater = LayoutInflater.from(_context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return list.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
private static class ViewHolder
{
public TextView textView;
public ImageView imageThumbnail;
public ViewHolder(View row) {
// TODO Auto-generated constructor stub
textView = (TextView) row.findViewById(R.id.rowTextView);
}
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
// TODO Auto-generated method stub
row=convertView;
holder=null;
// Item i = items.get(position);
try{
if(row==null)
{
LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.simplerow, viewGroup, false);
holder=new ViewHolder(row);
row.setTag(holder);
Log.d("newrow", "New row");
/*/View row = convertView;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) _context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.simplerow, viewGroup, false);
}
TextView textView = (TextView) row.findViewById(R.id.rowTextView);*/
holder.textView.setText(list.get(position).toString());
/* if(holder.imageThumbnail != null)
{
Bitmap myBitmap = BitmapFactory.decodeFile(path);
if(myBitmap != null)
holder.imageThumbnail.setImageBitmap(myBitmap);
}*/
/* bmThumbnail = ThumbnailUtils.createVideoThumbnail(Thumbnails.MICRO_KIND);*/
/*ContentResolver crThumb = getContentResolver();
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize = 1;
bmThumbnail = MediaStore.Video.Thumbnails.getThumbnail(crThumb, position, MediaStore.Video.Thumbnails.MICRO_KIND, options);*/
}
else
{
holder= (ViewHolder) row.getTag();
Log.d("recycle", "Recycling stuff");
}
}
catch(Exception e)
{
e.printStackTrace();
}
/* try
{
if(row!=null)
{
if(position==MP4.selected_item)
{
row.setBackgroundColor(Color.RED);
}
else
{
row.setBackgroundColor(Color.BLACK);
}
}
}
catch(Exception e)
{
}
*/
return row;
}
/*public Object getFilter() {
// TODO Auto-generated method stub
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
FilterResults results = new FilterResults();
if (charSequence == null || charSequence.length() == 0) {
results.values = items;
results.count = items.size();
} else {
List<Item> filtered_items = new ArrayList<Item>();
for (int i = 0; i < items.size(); i++) {
if (items.get(i).getText().toString().contains(charSequence))
filtered_items.add(items.get(i));
}
results.values = filtered_items;
results.count = filtered_items.size();
}
return results;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
filteredData = (List<Item>) filterResults.values;
notifyDataSetChanged();
}
};
}*/
public Filter getFilter() {
// TODO Auto-generated method stub
/*if (mFliter == null)
mFliter = new CustomFilter();*/
return mFilter;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
int count = list.size();
final ArrayList<String> nlist = new ArrayList<String>(count);
String filterableString ;
for (int i = 0; i < count; i++) {
filterableString = list.get(i);
if (filterableString.toLowerCase().contains(filterString)) {
nlist.add(filterableString);
}
}
results.values = nlist;
results.count = nlist.size();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredData = (List<Item>) results.values;
notifyDataSetChanged();
}
}
}
I am trying to use filtered search on this list view, but while I type on the search, it returns nothing, but it should display the items that starts with or contains the letter I type in the listview. Listview does not update at all, and holds the items that are displayed in listview. What I am doing wrong and what should I do?
I have been trying to implement a Search-view in action bar using list-view. My
project contains a list-view with a custom adapter which is extends by
Array-adapter. I fetched data from dataHelper class. I have model class which is contain name and phone fields. How I filter list-view using name.
MainActivity
private ActionBar actionBar;
private ListView listView;
DatabaseHelper databaseHelper;
ArrayList<Personinfo> list;
ArrayAdapter<Personinfo> arrayAdapter;
AdapterFilter adapterfilter;
Personinfo personinfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setBackgroundDrawable(new ColorDrawable(Color
.parseColor("#03A9F4")));
actionBar.setTitle("Agarwal Association");
list = new ArrayList<Personinfo>();
databaseHelper = new DatabaseHelper(this);
csvToSqlite();
listView = (ListView) findViewById(R.id.listView);
getlistData();
adapterfilter = new AdapterFilter(this, R.layout.child_listview, list);
// adapter = new ListAdapter(MainActivity.this, list);
Log.i("List", "" + list.get(0).getPhoneno());
listView.setAdapter(adapterfilter);
listView.setTextFilterEnabled(true);
synchronized (listView) {
listView.notify();
// }
}
// final TextView txtviewnumber = (TextView)
// findViewById(R.id.phoneno);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(),
((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
}
public void getlistData() {
// TODO Auto-generated method stub
Cursor cursor = databaseHelper.getData();
cursor.moveToFirst();
do {
String name = cursor.getString(cursor.getColumnIndex("Name"));
String phoneNo = cursor.getString(cursor.getColumnIndex("PhoneNo"));
Personinfo personinfo = new Personinfo(name, phoneNo);
list.add(personinfo);
} while (cursor.moveToNext());
cursor.close();
}
public void csvToSqlite() {
try {
String reader = "";
boolean skipheader = true;
InputStream inputStream = getResources().openRawResource(
R.raw.agrawalsurnamedata);
BufferedReader in = new BufferedReader(new InputStreamReader(
inputStream));
while ((reader = in.readLine()) != null) {
// skip header column name from csv
if (skipheader) {
skipheader = false;
continue;
}
String[] RowData = reader.split(",");
if (databaseHelper.insertContact(RowData) == true) {
Log.i("inside csvToSqlite()", " data inserted successfully");
} else {
Log.i("inside csvToSqlite()",
" data is not inserted into db");
}
}
in.close();
} catch (Exception e) {
e.getMessage();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search)
.getActionView();
searchView.setSearchableInfo(searchManager
.getSearchableInfo(getComponentName()));
SearchView.OnQueryTextListener textChangeListener = new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextChange(String newText) {
// this is your adapter that will be filtered
adapterfilter.getFilter().filter(newText);
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
adapterfilter.getFilter().filter(query);
return true;
}
};
searchView.setOnQueryTextListener(textChangeListener);
return super.onCreateOptionsMenu(menu);
}
}
AdapterFilter
public class AdapterFilter extends ArrayAdapter<Personinfo> {
ArrayList<Personinfo> list = new ArrayList<Personinfo>();
Context context;
LayoutInflater inflater;
public AdapterFilter(Context context, int resource,
ArrayList<Personinfo> list) {
super(context, resource);
this.list = list;
this.context = context;
inflater = LayoutInflater.from(this.context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Personinfo getItem(int position) {
// TODO Auto-generated method stub
return list.get(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
ViewHolder viewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.child_listview, parent,
false);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
final Personinfo personinfo = (Personinfo) getItem(position);
viewHolder.txtName.setText(personinfo.getName());
viewHolder.txtPhone.setText(personinfo.getPhoneno());
viewHolder.imageButtonCalling.setOnClickListener(new OnClickListener() {
// Calling on selected number
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "number button Clicked",
Toast.LENGTH_SHORT).show();
String selectedChildPhone = personinfo.getPhoneno();
String phoneNo = "tel:" + selectedChildPhone.trim();
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(phoneNo));
context.startActivity(intent);
}
});
viewHolder.imageButtonMessage.setOnClickListener(new OnClickListener() {
// Sending sms to whatsapp
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "meesaage button Clicked",
Toast.LENGTH_SHORT).show();
String selectedChildPhone = personinfo.getPhoneno();
Uri mUri = Uri.parse("smsto:" + selectedChildPhone);
Intent smsIntent = new Intent(
android.content.Intent.ACTION_SEND);
smsIntent.setType("text/plain");
smsIntent.putExtra("address", mUri);
smsIntent.putExtra("sms_body", "your desired message");
context.startActivity(smsIntent);
}
});
return convertView;
}
private class ViewHolder {
TextView txtName, txtPhone;
ImageButton imageButtonCalling, imageButtonMessage;
public ViewHolder(View item) {
txtName = (TextView) item.findViewById(R.id.person_name);
txtPhone = (TextView) item.findViewById(R.id.phoneno);
imageButtonCalling = (ImageButton) item
.findViewById(R.id.imageButtonCalling);
imageButtonMessage = (ImageButton) item
.findViewById(R.id.imageButtonMessage);
}
}
}
Personinfo.java
public class Personinfo {
private String name;
private String phoneno;
public Personinfo(String name, String phoneno) {
super();
this.name = name;
this.phoneno = phoneno;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoneno() {
return phoneno;
}
public void setPhoneno(String phoneno) {
this.phoneno = phoneno;
}
}
I am trying like that but listview not filtering by name. Where is my mistake please suggest me!!!
Thanks
Implement getFilter() method in your custom adapter which filter your listview according to search query. You have to implement Filterable interface for your searching functionality
public class AdapterFilter extends ArrayAdapter<Personinfo> implements Filterable{
ArrayList<Personinfo> list = new ArrayList<Personinfo>();
Context context;
LayoutInflater inflater;
public ArrayList<Personinfo> orig;
public AdapterFilter(Context context, int resource,
ArrayList<Personinfo> list) {
super(context, resource);
this.list = list;
this.context = context;
inflater = LayoutInflater.from(this.context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Personinfo getItem(int position) {
// TODO Auto-generated method stub
return list.get(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
ViewHolder viewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.child_listview, parent,
false);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
final Personinfo personinfo = (Personinfo) getItem(position);
viewHolder.txtName.setText(personinfo.getName());
viewHolder.txtPhone.setText(personinfo.getPhoneno());
viewHolder.imageButtonCalling.setOnClickListener(new OnClickListener() {
// Calling on selected number
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "number button Clicked",
Toast.LENGTH_SHORT).show();
String selectedChildPhone = personinfo.getPhoneno();
String phoneNo = "tel:" + selectedChildPhone.trim();
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(phoneNo));
context.startActivity(intent);
}
});
viewHolder.imageButtonMessage.setOnClickListener(new OnClickListener() {
// Sending sms to whatsapp
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "meesaage button Clicked",
Toast.LENGTH_SHORT).show();
String selectedChildPhone = personinfo.getPhoneno();
Uri mUri = Uri.parse("smsto:" + selectedChildPhone);
Intent smsIntent = new Intent(
android.content.Intent.ACTION_SEND);
smsIntent.setType("text/plain");
smsIntent.putExtra("address", mUri);
smsIntent.putExtra("sms_body", "your desired message");
context.startActivity(smsIntent);
}
});
return convertView;
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
final FilterResults oReturn = new FilterResults();
final ArrayList<Personinfo> results = new ArrayList<Personinfo>();
if (orig == null) {
orig = list;
}
if (constraint != null) {
if (orig != null && orig.size() > 0) {
for (final Personinfo g : orig) {
if (g.getName().toLowerCase(Locale.getDefault()).contains(constraint.toString())) {
results.add(g);
}
}
}
oReturn.values = results;
} else {
oReturn.values = list;
}
return oReturn;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
list = (ArrayList<Personinfo>) results.values;
notifyDataSetChanged();
}
};
}
private class ViewHolder {
TextView txtName, txtPhone;
ImageButton imageButtonCalling, imageButtonMessage;
public ViewHolder(View item) {
txtName = (TextView) item.findViewById(R.id.person_name);
txtPhone = (TextView) item.findViewById(R.id.phoneno);
imageButtonCalling = (ImageButton) item
.findViewById(R.id.imageButtonCalling);
imageButtonMessage = (ImageButton) item
.findViewById(R.id.imageButtonMessage);
}
}
}
I hope it helps!
Here my sample code, hope this help
public class MainActivity extends Activity implements
SearchView.OnQueryTextListener, SearchView.OnCloseListener {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) findViewById(R.id.searchView);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(true);
searchView.setOnQueryTextListener(this);
searchView.setOnCloseListener(this);
}
#Override
public boolean onClose() {
if (listAdapter != null) {
listAdapter.filterData("");
}
return false;
}
#Override
public boolean onQueryTextSubmit(String query) {
if (listAdapter != null) {
listAdapter.filterData(query);
}
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
if (listAdapter != null) {
listAdapter.filterData(newText);
}
return false;
}
}
public void filterData(String query) {
query = query.toLowerCase();
mList.clear();
if (query.isEmpty()) {
mList.addAll(mList_original);
} else {
for (String header : mList_original) {
if (header.toLowerCase().contains(query)) {
mList.add(header);
}
}
}
notifyDataSetChanged();
}
public class Setting extends Activity implements OnClickListener {
ListView listView1;
ImageView backbutton;
String Url = "http://182.71.212.110:8083/api/values/userdetails";
String Id;
String Designation;
String EmployeeName;
JSONArray _jarray;
DataModel datamodel = new DataModel();
ArrayList<DataModel> list = new ArrayList<DataModel>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.setting);
listView1 = (ListView) findViewById(R.id.listView1);
backbutton = (ImageView) findViewById(R.id.backbutton);
backbutton.setOnClickListener(this);
new GetUserdetail().execute();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.backbutton) {
finish();
}
}
class GetUserdetail extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
String json = HttpHitter.ExecuteData(Url);
_jarray = new JSONArray(json);
System.out.println("_jarray" + _jarray);
for (int i = 0; i <= _jarray.length(); i++) {
JSONObject _obj = _jarray.getJSONObject(i);
if (Id != null) {
datamodel.setId(_obj.getString("Id"));
}
if (Designation != null) {
datamodel.setDesignation(_obj.getString("Designation"));
}
if (EmployeeName != null) {
datamodel.setEmployeeName(_obj
.getString("EmployeeName"));
}
list.add(datamodel);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
CustomList adapter = new CustomList(Setting.this, list);
listView1.setAdapter(adapter);
}
}
}
public class DataModel implements Parcelable {
private String Id = "";
private String Designation = "";
private String EmployeeName = "";
public String getId() {
return Id;
}
public void setId(String id) {
this.Id = id;
}
public String getDesignation() {
return Designation;
}
public void setDesignation(String designation) {
this.Designation = designation;
}
public String getEmployeeName() {
return EmployeeName;
}
public void setEmployeeName(String employeeName) {
this.EmployeeName = employeeName;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
public DataModel() {
// TODO Auto-generated constructor stub
}
public DataModel(Parcel in) {
Id = in.readString();
EmployeeName = in.readString();
Designation = in.readString();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
dest.writeString(Id);
dest.writeString(EmployeeName);
dest.writeString(Designation);
}
}
public class CustomList extends BaseAdapter {
Context context;
private ArrayList<DataModel> arrModel;
public CustomList(Context context, ArrayList<DataModel> arrModel) {
this.context = context;
this.arrModel = arrModel;
}
/* private view holder class */
private class ViewHolder {
TextView txtTitle;
TextView txtDesc;
ImageView locationimage;
ImageView roleimageview;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.settingrowitem, null);
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView
.findViewById(R.id.rowcontact_txtName);
holder.txtTitle = (TextView) convertView
.findViewById(R.id.rowcontact_txtrole);
holder.locationimage = (ImageView) convertView
.findViewById(R.id.imageView1);
holder.roleimageview = (ImageView) convertView
.findViewById(R.id.imageView2);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtDesc.setText(arrModel.get(position).getEmployeeName());
holder.txtTitle.setText(arrModel.get(position).getDesignation());
if (position % 2 == 0) {
convertView.setBackgroundColor(Color.parseColor("#ffffff"));
}
else {
convertView.setBackgroundColor(Color.parseColor("#f5f6f1"));
}
return convertView;
}
#Override
public int getCount() {
return arrModel.size();
}
#Override
public Object getItem(int position) {
return arrModel.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
}
There are three class which I have use to parse data from from web service and and trying to print in Listview .I am able to do Json parsing and getting data from server insetting.javaclass:
list.add(datamodel);
and bind this in list in onpostexcute method:
CustomList adapter = new CustomList(Setting.this, list);
listView1.setAdapter(adapter);
Using this i am trying to print data in listview item but I am getting blank value in each item while Number Json is 49 and i am getting that 49 but getDesignation and getEmploye I am getting blank value please check and tell me where I am doing mistake I have tried much unable to get Print that value please check suggest me
Where are you inistailizind the Id,Designation and EmployeeName, it will be null itself. so doInBackground wont add any datamodel. remove the check
class GetUserdetail extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
String json = HttpHitter.ExecuteData(Url);
_jarray = new JSONArray(json);
System.out.println("_jarray" + _jarray);
for (int i = 0; i <= _jarray.length(); i++) {
DataModel datamodel = new DataModel();
JSONObject _obj = _jarray.getJSONObject(i);
datamodel.setId(_obj.getString("Id"));
datamodel.setDesignation(_obj.getString("Designation"));
datamodel.setEmployeeName(_obj.getString("EmployeeName"));
list.add(datamodel);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
CustomList adapter = new CustomList(Setting.this, list);
listView1.setAdapter(adapter);
}
}
Initialise the model inside the for loop and try once.
To identify changes in your list item you should call
adapter.notifyDataSetChanged();
call it before setting adapter to list view.
I am new to android and try to make a contact application with search on top of my listview. When I search for a contact it filters correct and shows me only the contact that I searched but when I try to edit/delete that contact it throws me database/CursorIndexOutOfBoundsException and also the textview that I use as phone hyperling does not work too...when I do not search at all everything works correct(edit, delete, phone call from text view etc.).I am posting the class with the search filter if you need more code let me know.I assume the adapter does not show the correct listview or something like that.
Sorry for big post thanks in advance.
public class Promitheutis extends Activity implements SearchView.OnQueryTextListener {
Button add_btn;
ListView Contact_listview;
ArrayList<Contact> contact_data = new ArrayList<Contact>();
Contact_Adapter cAdapter;
DatabaseHandler db;
String Toast_msg;
SearchView search_view;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
Contact_listview = (ListView) findViewById(R.id.list);
Contact_listview.setItemsCanFocus(false);
add_btn = (Button) findViewById(R.id.add_btn);
search_view = (SearchView) findViewById(R.id.search_view);
Set_Referash_Data();
search_view.setOnQueryTextListener(this);
} catch (Exception e) {
// TODO: handle exception
Log.e("some error", "" + e);
}
add_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent add_user = new Intent(Promitheutis.this,
Add_Update_User.class);
add_user.putExtra("called", "add");
add_user.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(add_user);
finish();
}
});
}
public void Set_Referash_Data() {
contact_data.clear();
db = new DatabaseHandler(this);
ArrayList<Contact> contact_array_from_db = db.Get_Contacts();
for (int i = 0; i < contact_array_from_db.size(); i++) {
int tidno = contact_array_from_db.get(i).getID();
//String name = contact_array_from_db.get(i).getName();
String epitheto = contact_array_from_db.get(i).getEpitheto();
String mobile = contact_array_from_db.get(i).getPhoneNumber();
// String email = contact_array_from_db.get(i).getEmail();
String eidos = contact_array_from_db.get(i).getEidos();
Contact cnt = new Contact();
cnt.setID(tidno);
//cnt.setName(name);
cnt.setEpitheto(epitheto);
//cnt.setEmail(email);
cnt.setEidos(eidos);
cnt.setPhoneNumber(mobile);
contact_data.add(cnt);
}
db.close();
cAdapter = new Contact_Adapter(Promitheutis.this, R.layout.listview_row,
contact_data);
Contact_listview.setAdapter(cAdapter);
cAdapter.notifyDataSetChanged();
}
public void Show_Toast(String msg) {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
Set_Referash_Data();
}
public class Contact_Adapter extends ArrayAdapter<Contact> implements Filterable {
ValueFilter valueFilter;
Context context;
Activity activity;
int layoutResourceId;
Contact user;
ArrayList<Contact> data;
ArrayList<Contact> filterdata;
public Contact_Adapter(Activity act, int layoutResourceId,
ArrayList<Contact> data) {
super(act, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.activity = act;
this.data = data;
filterdata = data;
notifyDataSetChanged();
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
#Override
public Contact getItem(int position) {
// TODO Auto-generated method stub
return data.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return data.indexOf(getItem(position));
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
UserHolder holder = null;
if (row == null) {
LayoutInflater inflater = LayoutInflater.from(activity);
row = inflater.inflate(layoutResourceId, parent, false);
holder = new UserHolder();
//holder.name = (TextView) row.findViewById(R.id.user_epitheto_txt);
holder.epitheto = (TextView) row.findViewById(R.id.user_epitheto_txt);
//holder.email = (TextView) row.findViewById(R.id.user_email_txt);
holder.eidos = (TextView) row.findViewById(R.id.user_eidos_txt);
holder.number = (TextView) row.findViewById(R.id.user_mobile_txt);
holder.edit = (Button) row.findViewById(R.id.btn_update);
holder.delete = (Button) row.findViewById(R.id.btn_delete);
row.setTag(holder);
} else {
holder = (UserHolder) row.getTag();
}
user = data.get(position);
holder.edit.setTag(user.getID());
holder.delete.setTag(user.getID());
//holder.name.setText(user.getName());
holder.epitheto.setText(user.getEpitheto());
//holder.email.setText(user.getEmail());
holder.eidos.setText(user.getEidos());
holder.number.setText(user.getPhoneNumber());
// String url = holder.number.getText().toString();
//final Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(url));
final String phone_no= holder.number.getText().toString().replaceAll("-", "");
holder.number.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:"+phone_no));
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(callIntent);
}
});
holder.edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("Edit Button Clicked", "**********");
Intent update_user = new Intent(activity,
Update_User.class);
update_user.putExtra("called", "update");
update_user.putExtra("USER_ID", v.getTag().toString());
activity.startActivity(update_user);
}
});
holder.delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(final View v) {
// TODO Auto-generated method stub
// show a message while loader is loading
AlertDialog.Builder adb = new AlertDialog.Builder(activity);
adb.setTitle("Διαγραφή;");
adb.setMessage("Είστε σίγουρος για τη διαγραφή; ");
final int user_id = Integer.parseInt(v.getTag().toString());
adb.setNegativeButton("Άκυρο", null);
adb.setPositiveButton("Ok",
new AlertDialog.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// MyDataObject.remove(positionToRemove);
DatabaseHandler dBHandler = new DatabaseHandler(
activity.getApplicationContext());
dBHandler.Delete_Contact(user_id);
Promitheutis.this.onResume();
}
});
adb.show();
}
});
return row;
}
#Override
public Filter getFilter() {
if (valueFilter == null) {
valueFilter = new ValueFilter();
}
return valueFilter;
}
private class ValueFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
// TODO Auto-generated method stub
FilterResults results = new FilterResults();
if (constraint != null && constraint.length() > 0) {
ArrayList<Contact> filterList = new ArrayList<Contact>();
for (int i = 0; i < filterdata.size(); i++) {
if ( (filterdata.get(i).getEpitheto().toUpperCase() )
.contains(constraint.toString().toUpperCase())) {
Contact cnt = new Contact(filterdata.get(i)
.getEpitheto() , filterdata.get(i)
.getPhoneNumber() , filterdata.get(i)
.getEidos());
filterList.add(cnt);
}
}
results.count = filterList.size();
results.values = filterList;
} else {
results.count = filterdata.size();
results.values = filterdata;
}
return results;
}
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
// TODO Auto-generated method stub
data = (ArrayList<Contact>) results.values;
notifyDataSetChanged();
}
}
class UserHolder {
TextView name;
TextView epitheto;
TextView email;
TextView number;
TextView stathero;
TextView eidos;
TextView eponimia_user;
TextView afm;
TextView eidos2;
TextView eidos3;
Button edit;
Button delete;
}
}
#Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
// TODO Auto-generated method stub
cAdapter.getFilter().filter(newText);
return false;
}
}
Read This. It Contain What you want and have source code also.
I'm a noob to android development and I'm trying to implement the search bar so that i can search a listview. I have no issues getting the searchview to appear. However, when I enter text into the searchview the app crashes saying that there is an "illegalstateexception: I cannot call onTextChanged with a non filterable adapter. I don't understand why i am getting this error because my adapter class implements Filterable. Any help is greatly appreciated.
Main Activity
public class StoresActivity extends SherlockActivity implements OnQueryTextListener {
ArrayList<HashMap<String, String>> storeList;
ListView list;
LazyAdapter adapter;
EditText inputSearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stores);
storeList = new ArrayList<HashMap<String, String>>();
list=(ListView)findViewById(R.id.list);
SharedPreferences preferences = getSharedPreferences("Oleref", 2);
String employee = preferences.getString("employee", null);
ActionBar bar = getSupportActionBar();
bar.setDisplayHomeAsUpEnabled(true);
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(new String[] { "http://www.bigmoney.com="+ employee});
try {
storeList = task.get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
adapter=new LazyAdapter(this, storeList);
list.setAdapter(adapter);
list.setItemsCanFocus(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//Create the search view
SearchView searchView = new SearchView(getSupportActionBar().getThemedContext());
//list = getListView();
list.setTextFilterEnabled(true);
setupSearchView(searchView);
menu.add(0, 1, 1, "Search Text")
.setIcon(R.drawable.ic_launcher)
.setActionView(searchView)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
return super.onCreateOptionsMenu(menu);
}
private void setupSearchView(SearchView mSearchView) {
mSearchView.setIconifiedByDefault(false);
mSearchView.setSubmitButtonEnabled(false);
mSearchView.setOnQueryTextListener(StoresActivity.this);
mSearchView.setQueryHint("Search Text");
}
#Override
public boolean onQueryTextChange(String newText) {
if (TextUtils.isEmpty(newText)) {
list.clearTextFilter();
} else {
list.setFilterText(newText);
}
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId())
{
case android.R.id.home:
Intent chart = new Intent();
chart.setClass(StoresActivity.this, StoresActivity.class);
chart.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
StoresActivity.this.startActivity(chart);
return true;
case 2:
Intent chart2 = new Intent();
chart2.setClass(StoresActivity.this, WalkInActivity.class);
chart2.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
StoresActivity.this.startActivity(chart2);
return true;
}
return true;
}
}
Adapter Class
public class LazyAdapter extends BaseAdapter implements Filterable {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public String sn;
StoresActivity storesActivity;
HashMap<String, String> stores;
HashMap<String, String> storedata;
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#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
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.store_row, null);
TextView store = (TextView)vi.findViewById(R.id.storeText); // title
TextView store_num = (TextView)vi.findViewById(R.id.store_num); // artist name
TextView street = (TextView)vi.findViewById(R.id.address);
TextView city = (TextView)vi.findViewById(R.id.city);
Button newbutton=(Button)vi.findViewById(R.id.newser);
Button historybutton=(Button)vi.findViewById(R.id.history);
storedata = new HashMap<String, String>();
storedata = data.get(position);
newbutton.setTag(position);
newbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent chart = new Intent();
chart.setClass(v.getContext(), SectionActivity.class);
storedata = data.get((Integer)v.getTag());
sn = storedata.get("Store_Num");
String store = storedata.get("Store");
chart.putExtra("sn", sn);
chart.putExtra("store", store);
chart.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
v.getContext().startActivity(chart);
}
});
historybutton.setTag(position);
historybutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent chart = new Intent();
chart.setClass(v.getContext(), HistoryList.class);
storedata = data.get((Integer)v.getTag());
sn = storedata.get("Store_Num");
String store = storedata.get("Store");
chart.putExtra("sn", sn);
chart.putExtra("store", store);
chart.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
v.getContext().startActivity(chart);
}
});
// Setting all values in listview
store.setText(storedata.get("Store"));
store_num.setText(storedata.get("Store_Num"));
street.setText(storedata.get("Address"));
city.setText(storedata.get("City") + " " + storedata.get("State") + " " + storedata.get("Zip"));
return vi;
}
public boolean onLoadClass(Class arg0) {
// TODO Auto-generated method stub
return false;
}
//Added for search BJR 5-16-2013
#Override
public android.widget.Filter getFilter() {
// TODO Auto-generated method stub
return null;
}
}
Since you are using ActionBarSherlock, I assume that your min SDK is below 11 but SearchView widget requires Android 3.0 (API Level 11) and higher. You might want to look at search dialog. Please check documentation http://developer.android.com/guide/topics/search/search-dialog.html