Why Is ActionBarSherlock SearchView Not Working? - android

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

Related

How to filter data from list using seachview and action bar

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

Search Filter adapter not working properly

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.

How to make search from search view in Android

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..

notifyDataSetChanged is not working

I fetched data in JSON from web service and then i put data into a custom ListView.
On clicking an item of ListView , I open a new Activity. Now I click on "Submit" Button of this activity I go back to the same ListView ,
When I get back to the ListView, I want to change the text of listitem in which I clicked before
I just want to refresh or re-call the activity when it again comes to listticket.java
Right now data is static . I used web services.
listticket.java
public class listticket extends Activity {
static ListView listView;
ArrayList<String> aryTicket = new ArrayList<String>();
private String[] listArr = { "A", "B" };
private String[] listStatus = { "Alert", "Alert" };
private String[] listTicketid = { "1", "2" };
ArrayList<String> ary_ticket_code = new ArrayList<String>();
ArrayList<String> ary_address = new ArrayList<String>();
ArrayList<String> ary_ticketid = new ArrayList<String>();
public static ArrayList<String> ary_status = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.listticket);
listView = (ListView) findViewById(R.id.itemList);
// filllistdata();
listArr = new String[ary_ticket_code.size()];
listArr = ary_ticket_code.toArray(listArr);
listStatus = new String[ary_status.size()];
listStatus = ary_status.toArray(listStatus);
listTicketid = new String[ary_ticketid.size()];
listTicketid = ary_ticketid.toArray(listTicketid);
MyArrayAdapter adapter = new MyArrayAdapter(this, listArr);
listView.setAdapter(adapter);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
ary_status.set(0, "Work Done");
((MyArrayAdapter) listView.getAdapter()).notifyDataSetChanged();
}
public class MyArrayAdapter extends ArrayAdapter<String> {
Activity context;
String[] listArr;
private TextView btnchkout;
// private final integer[] image;
public MyArrayAdapter(Activity context, String[] objects) {
super(context, R.layout.ticket, objects);
// TODO Auto-generated constructor stub
this.context = context;
listArr = objects;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.ticket, null, true);
TextView textView = (TextView) view.findViewById(R.id.txtTicketNo);
textView.setText(listArr[position]);
final TextView txtAlert = (TextView) view
.findViewById(R.id.txtAlert1);
// Toast.makeText(getApplicationContext(), listStatus[position],
// Toast.LENGTH_LONG).show();
String statusCheck = listStatus[position].toString().trim();
if (statusCheck.equals("Alert") == true) {
txtAlert.setText(statusCheck);
txtAlert.setTextColor(getResources().getColor(R.color.red));
} else if (statusCheck.equals("In Progress") == true) {
txtAlert.setText(statusCheck);
txtAlert.setTextColor(getResources().getColor(R.color.view));
} else if (statusCheck.equals("Work Complete Pending paperwork") == true) {
txtAlert.setText("Work Done");
txtAlert.setTextColor(getResources().getColor(R.color.green));
} else {
txtAlert.setText(statusCheck);
// txtAlert.setTextColor(getResources().getColor(R.color.defaulttextcolor));
}
final TextView btntextView = (TextView) view
.findViewById(R.id.btnCheckin);
if (statusCheck.equals("In Progress")) {
Drawable d = getResources().getDrawable(R.drawable.btncheckin);
btntextView.setBackgroundDrawable(d);
}
btnchkout = (TextView) view.findViewById(R.id.btnCheckout);
btnchkout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(listticket.this,
ticket_detail.class);
startActivity(intent);
}
});
return view;
}
}
}
Another layout in when click on ListItem
ticketdetail.java
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.ticket_detail);
btnSubmit = (TextView) findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new AsyncAction().execute(null,null,null);
//onBackPressed();
}
});
}
private class AsyncAction extends AsyncTask<String, Void, String>
{
public boolean status=false;
private ProgressDialog pd;
#Override
protected String doInBackground(String... arg0)
{
// TODO Auto-generated method stub
try
{
}
catch (Exception e)
{
// TODO: handle exception
}
return null;
}
#Override
protected void onPostExecute(String result)
{
pd.dismiss();
Intent intent = new Intent(ticket_detail.this,listticket.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
//finish();
}
protected void onPreExecute()
{
// TODO Auto-generated method stub
super.onPreExecute();
pd = new ProgressDialog(ticket_detail.this);
pd.setMessage("Please Wait ...");
pd.setIndeterminate(true);
pd.setCancelable(false);
pd.show();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Intent a = new Intent(ticket_detail.this,listticket.class);
a.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(a);
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
Make adapter object globally and initialize once within onCreate and inside onResume() notify to your adapter like below:
Delcaration
MyArrayAdapter adapter;
onCreate
adapter = new MyArrayAdapter(this, listArr);
listView.setAdapter(adapter);
onResume()
adapter.notifyDataSetChanged();
Try this, add, clear and remove calls notifyDataSetChanged itself and you dont have to change your adapter everytime you refresh your information, its expensive.
adapter.clear()
for (Object o : object)
adapter.add(o)

save editbox values in the custom listview

am having a two editbox. the values enter in that has to placed in the custom listview its working fine for this...
but i want to save this values in the list view permanently.so that if the phones switches off and again run the app then the values have to be saved ..like phone contact number and name have to be saved..
here am ataching the code
public class Editcard extends Activity{
EditText cardname,cardDescription ;
MyApplication app;
#SuppressWarnings({ "unchecked", "rawtypes" })
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.editcredit);
app = ((MyApplication) getApplicationContext());
cardname =(EditText)findViewById(R.id.cardash);
cardDescription =(EditText)findViewById(R.id.editdescription);
Button save =(Button)findViewById(R.id.save);
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
app.carddata =cardname.getText().toString();
System.out.println("Gotcardname"+app.carddata);
app.descriptiondata =cardDescription.getText().toString();
System.out.println("gotDescription"+app.descriptiondata);
app.arryList.add(app.carddata);
app.arryList1.add(app.descriptiondata);
Intent saveIntent =new Intent(Editcard.this,Newcard.class);
startActivity(saveIntent);
}
});
}
}
public class MyApplication extends Application{
ArrayList<String> arryList = new ArrayList<String>();
ArrayList<String> arryList1 = new ArrayList<String>();
String carddata,descriptiondata,=null;
}
public class Newcard extends Activity {
MyAdapter adapter;
ListView listView;
LayoutInflater lay;
MyApplication app;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.newcard);
app = ((MyApplication) getApplicationContext());
TextView newcard =(TextView)findViewById(R.id.newcard);
newcard.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent card = new Intent(Newcard.this,Editcreditcard.class);
startActivity(card);
}
});
listView = (ListView) findViewById(R.id.cardlist);
adapter =new MyAdapter(this, app.arryList,app.arryList1);
listView.setAdapter(adapter);
}
public class MyAdapter extends BaseAdapter {
Context context = null;
ArrayList<String> items= null;
ArrayList<String> items1= null;
public MyAdapter(Newcard newcard, ArrayList<String> items,
ArrayList<String> items1) {
// TODO Auto-generated constructor stub
this.items = items;
this.items1 = items1;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return items;
//return items.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View layout = null;
TextView produ = null;
TextView desc = null;
if (convertView == null) {
lay = LayoutInflater.from(getApplicationContext());
layout = lay.inflate(R.layout.customlist, null);
} else {
layout = convertView;
}
produ = (TextView) layout.findViewById(R.id.card);
produ.setText("" +app.arryList.get(position));
desc= (TextView) layout.findViewById(R.id.descrip);
desc.setText("" +app.arryList1.get(position));
return layout;
}
}
}
use can use SharedPreferences, that will save your values permanently, untill they are changed(by changing values in editbox) or user reinstall (clear data) application. Shared Preferences works like this
// save string in sharedPreferences
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = settings.edit();
editor.putString("some_key", string); // here string is the value you want to save
editor.commit();
// restore string in sharedPreferences
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
string = settings.getString("some_key", "");

Categories

Resources