List with search and mark - android

I am trying to implement a contact list with a search and marking feature; everything except search is working properly. The code I am using is given below. Could someone please help me to sort this out?
public class MainActivity extends ListActivity implements Runnable {
Cursor phoneCursor;
public static Button done;
ListView lv;
/* OpenHelper db_obj;*/
final int PROGRESS_DIALOG = 0;
ProgressDialog progressDialog;
ArrayAdapter<ContactModel> adapter;
ArrayList<HashMap<String, String>> CONTACT_DATA = new ArrayList<HashMap<String, String>>();
#Override
public void onCreate(Bundle saveinst) {
super.onCreate(saveinst);
progressDialog=ProgressDialog.show(MainActivity.this, "LoadContacts", "Please wait...", true, false);
Thread loadContact = new Thread(this);
loadContact.start();
}
public void run() {
List<ContactModel>contactList = new ArrayList<ContactModel>();
try {
Looper.prepare();
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
null, Phone.DISPLAY_NAME + " ASC");
while (phones.moveToNext()) {
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber11 = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contactList.add(get(name,phoneNumber11));
}
adapter = new MyContactListAdapter(MainActivity.this, contactList);
handler.sendEmptyMessage(0);
} catch(Exception exce) {
exce.printStackTrace();
}
private final Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
progressDialog.dismiss();
setListAdapter(adapter);
setContentView(R.layout.activity_main);
EditText editText;
/* db_obj = new OpenHelper(getApplicationContext());*/
lv = getListView();
editText = (EditText)findViewById(R.id.editText1);
editText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
MainActivity.this.adapter.getFilter().filter(cs);
setListAdapter(adapter);
}
#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
}
});
done = (Button)findViewById(R.id.button1done);
done.setVisibility(View.INVISIBLE);
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
MainActivity.this.finish();
Intent in = new Intent();
in.setClass(getApplicationContext(), MainActivity.class);
startActivity(in);
}
});
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
System.out.println("Entered List Activity");
}
});
}
};
public ContactModel get(String name,String number)
{
return new ContactModel(name,number);
}

Instead of an EditText try an AutoCompleteTextView. It works similar to what you have here except the searching is handled by Android without have to use filters in the onTextChanged.
myACTV.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
myACTV.showDropDown();
myACTV.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3)
//Do something here
}
});
return false;
}
});
For a better Idea of how this works check out http://developer.android.com/reference/android/widget/AutoCompleteTextView.html

Related

I want to search name from database using edittext

public class SearchActivity extends Activity {
private EditText Search_By_Name;
private ArrayList<Personal_loan> array;
private ArrayAdapter<Personal_loan> adapter;
private ListView listView;
SQLiteDatabase db;
Cursor cursor ;
private DBHelper dbHelper;
Personal_loan p = new Personal_loan();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
Search_By_Name = (EditText)findViewById(R.id.SearchName);
array = new ArrayList<Personal_loan>();
listView = (ListView) findViewById(R.id.listView1);
adapter = new ArrayAdapter<Personal_loan>(this, android.R.layout.simple_list_item_1, array);
listView.setAdapter(adapter);
getData();
}
private void getData() {
DBHelper helper = new DBHelper(this);
db = helper.getReadableDatabase();
String columns[] = new String[] {ID,Name,START_DATE,END_DATE,LOAN_AMOUNT,RATE_OF_INTEREST,FINAL_AMOUNT};
cursor = db.query( false, LOAN_TABLE, columns, null, null, null, null, null, null, null);
if (!cursor.isAfterLast()) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
p = new Personal_loan();
p.id = cursor.getInt(0);
p.name = cursor.getString(1);
p.sd = cursor.getString(2);
p.ed = cursor.getString(3);
p.la = cursor.getDouble(4);
p.roi = cursor.getFloat(5);
p.amt=cursor.getString(6);
array.add(p);
cursor.moveToNext();
Search_By_Name.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
s=Search_By_Name.getText();
p.name=s.toString();
adapter.getFilter().filter(s.toString());
}
});
}
cursor.close();
db.close();
adapter.notifyDataSetChanged();
}
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
Intent i=new Intent(SearchActivity.this,FirstActivity.class);
startActivity(i);
}
}
This is my updated code, it filtered the data but using the last field, not by name field... it took the last field for filtering, if any know the answer plz do share
Try this ...
Search_By_Name .addTextChangedListener(new TextWatcher() {
#Override public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = search.getText().toString().toLowerCase(Locale.getDefault()); //
Your_Activity.this.adapter.filter(text); }
#Override
public void beforeTextChanged(CharSequence arg0, int
arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
} });
Reference link

Android Listview with Search filter

I am trying to make a listView search for Android.I am using SimpleCursorAdapter on onTextChanged
i have found a error adapter cannot be resolved or is not a field.how can resolve this error .I am using SimpleCursorAdapter .I am not able to use adapter.getFilter().filter(cs);
ListView lv;
Cursor cursur1;
EditText search ;
int textlength=0;
ArrayAdapter<String> adapter1;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
search = (EditText) findViewById(R.id.inputSearch);
final String [] from={ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,ContactsContract.CommonDataKinds.Phone.NUMBER,ContactsContract.CommonDataKinds.Phone._ID};
int [] m={android.R.id.text1,android.R.id.text2};
lv=getListView();
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
cursur1=getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
startManagingCursor(cursur1);
#SuppressWarnings("deprecation")
SimpleCursorAdapter adapter=new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, cursur1, from,m);
setListAdapter(adapter);
search.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
MainActivity.this.adapter.getFilters().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
}
});
}
#Override
public long getSelectedItemId() {
// TODO Auto-generated method stub
return super.getSelectedItemId();
}
#Override
public int getSelectedItemPosition() {
// TODO Auto-generated method stub
return super.getSelectedItemPosition();
}
}
Try this.. inside add Text change listener
YourAdapterOrWhateverAdapter adapter = (YourAdapterOrWhateverAdapter) listView.getAdapter();
adapter.getFilter().filter(s);
adapter.notifyDataSetChanged()
you can use AutoCompleteTextView, e.g -
private static final String[] DATE_RANGE = new String[] { "1 Day",
"2 Days", "3 Days", "6 Months", "1 Year", "Blank" };
AutoCompleteTextView dateRangeTV = (AutoCompleteTextView)findViewById(R.id.tv_date_range);
dateRangeTV.setThreshold(0);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.default_date_range_list, DATE_RANGE);
dateRangeTV.setAdapter(adapter);
In Touch event, you could see the dropdownlist :
dateRangeTV.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
dateRangeTV.showDropDown();
return false;
}
});
Type any text, It'll show your matching text from the list.
For more see the tutorial of the AutoCompleteTextView

Using edittext to search listview

I have this Listview:
#Override
public void onComplete(List<Profile> friends) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mSpinner.setVisibility(View.GONE);
mSpinner.clearAnimation();
}
});
// populate list
List<String> values = new ArrayList<String>();
for (Profile profile : friends) {
//profile.getInstalled();
values.add(profile.getName());
}
listView = (ListView) findViewById(R.id.list);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> av, final View view, final int i, long i2) {
Animation pushLeftIn = AnimationUtils.loadAnimation(CallActivity.this, R.anim.jump_no_fade);
view.startAnimation(pushLeftIn);
}
});
ArrayAdapter<String> friendsListAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.list_items2, values);
friendsListAdapter.sort(new Comparator<String>() {
#Override
public int compare(String lhs, String rhs) {
return lhs.compareTo(rhs);
}
});
mFriendsList.setAdapter(friendsListAdapter);
}
};
I am trying to make the edittext filter the listview, this is what i have tried:
mySearchView.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
CallActivity.this.friendsListAdapter.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
}
});
I get no errors in the code but when i try to search in the edittext it doesn't work at all, what is the problem or how should i do instead?
Try do it in afterTextChanged(Editable arg0).
And did you implement your getFilter().filter(cs). Can you show implementation?

ListView custom filter gives wrong item selected when filtered [Android]

I am new to Android programming and I have a ListView when filtered always return me the first item in the list, so how do I fix this?
For instance, my list contains A.A, A.B, A.C, B.C, B.D.
When I want to search the list for things starting with B, I will get B.C, B.D but when I click B.C, it returns me A.A and B.D, it returns me A.B
public class PatientList extends Activity{
PatientDB patientDB;
Context myContext;
ListView lv_patients;
EditText et_patients;
ArrayAdapter<String> adapter;
ArrayList<HashMap<String, String>> patientList;
static String value;
String[] patientarray = new String[]{"initials"};
ArrayList<String> patientArrayList = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_patient_list);
myContext = this;
patientDB = new PatientDB(myContext);
patientDB.open();
Cursor patientCursor;
patientCursor = patientDB.retrieveAllEntriesCursor();
if(patientCursor!=null && patientCursor.getCount()>0)
{
String patientInitials;
patientCursor.moveToFirst();
do
{
patientCursor.getString(patientDB.COLUMN_KEY_ID); // + " " +
patientInitials = patientCursor.getString(patientDB.COLUMN_INITIALS_ID);
Log.i("FromCursor", patientInitials);
patientArrayList.add(patientInitials);
} while (patientCursor.moveToNext());
}
lv_patients = (ListView) findViewById(R.id.lv_patients);
et_patients = (EditText) findViewById(R.id.et_patients);
lv_patients.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
String a = patientArrayList.get(position);
Toast.makeText(PatientList.this, a + " selected", Toast.LENGTH_SHORT).show();
Intent returnIntent = new Intent(PatientList.this, PatientInfo.class);
returnIntent.putExtra("value", a);
setResult(RESULT_OK, returnIntent);
finish();
}
});
//Adding items to listview
adapter = new ArrayAdapter<String>(this, R.layout.list_patients, R.id.patient_name, patientArrayList);
lv_patients.setAdapter(adapter);
//Enabling search filter
et_patients.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
PatientList.this.adapter.getFilter().filter(cs);
}
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
}
Because you filter your adapter to have B.C in position 0 and B.D in position 1. But in your implementation of your onClickListener, you use the listview's position to get directly from the source ArrayList.
String a = patientArrayList.get(position);
Instead to get it from the filtered adapter:
String a = parent.getAdapter().getItem(position);
or
String a = parent.getItemAtPosition(position);

Search in list view where datas are stored in db

I have a listview of different data which are stored in DB and when i click particular data it will show the details of that and also i have used adapter class through position of the listview, it gets the detail of the data to display.
I need to add search for the listview and from the result listview, if i click the data it should show the details. please, can any one provide the code for this.
public class CustomerAdapter extends BaseAdapter{
public CustomerAdapter(Context context) {
this.context = context;
this.layoutInflater = LayoutInflater.from(context);
reload(0, TAKE);
}
private void reload(int skip, int take)
{
totalSize = customers.size();
System.out.println("Total Size: "+totalSize);
loadedCustomer = loadCustomers(skip, take);
}
private ArrayList<HashMap<String, Object>> loadCustomers(int skip, int take)
{
ArrayList<HashMap<String, Object>> arrayList = new ArrayList<HashMap<String,Object>>();
Query query = new Query();
query.select("x.fname, x.lname, x.surrogateKey, x.id");
query.from("Customer", "x");
query.orderBy("id", SortOrder.ASCENDING);
query.setTake(take);
query.setSkip(skip);
lowIndex = skip;
highIndex = lowIndex;
QueryResultSet rs = SUP101.SUP101DB.executeQuery(query);
while(rs.next())
{
String fname = rs.getString(1);
String lname = rs.getString(2);
long sk = rs.getLong(3);
HashMap<String, Object> tempHashMap = new HashMap<String, Object>();
tempHashMap.put(NAME, " " + fname + " " + lname);
tempHashMap.put("sk", sk);
arrayList.add(tempHashMap);
highIndex++;
}
return arrayList;
}
public int getCount() {
return totalSize;
}
public Object getItem(int position) {
reloadIfNeeded(position);
return loadedCustomer.get(position - lowIndex);
}
#SuppressWarnings("unchecked")
public String getSK(int position)
{
HashMap<String, Object> map = (HashMap<String, Object>)getItem(position);
return map.get("sk").toString();
}
private void reloadIfNeeded(int newPosition)
{
if(newPosition < lowIndex || newPosition >= highIndex)
{
int lowIndex = (newPosition);
reload(lowIndex, TAKE);
}
}
public void refreshUI(boolean force)
{
if(force)
{
reload(lowIndex, TAKE);
((Activity)context).runOnUiThread(
new Runnable()
{
public void run()
{
CustomerAdapter.this.notifyDataSetChanged();
}
}
);
}
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
TextView tv = null;
if(convertView==null){
convertView = layoutInflater.inflate(R.layout.customer, null);
}
tv = (TextView)convertView.findViewById(R.id.textView1);
reloadIfNeeded(position);
tv.setText(loadedCustomer.get(position - lowIndex).get(NAME).toString());
return convertView;
}
// mainmenu class
Mainmenu.this.runOnUiThread(new Runnable()
{
public void run()
{
adapter1 = new CustomerAdapter(Mainmenu.this);
listView.setAdapter(adapter1);
array_sort = new ArrayList<String>();
adapter1 = new CustomerAdapter(Mainmenu.this);
listView.setAdapter(adapter1);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
Mainmenu.this.adapter1.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
}
});
listView.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> a, View v, int position, long id)
{
Intent intent = new Intent(Mainmenu.this, Detailview.class);
intent.putExtra("sk", adapter1.getSK(position));
Mainmenu.this.startActivityForResult(intent, REQUEST_DETAIL);
}
});
}
});
}
}).start();
You can make use of FilterQueryAdapter interface as below:
DataBaseHelper myDbHelper = new DataBaseHelper(this);
FilterQueryProvider fqp = new myFilterQueryProvider(myDbHelper);
<YourCursorAdapter>.setFilterQueryProvider(fqp);
<YourListView>.setTextFilterEnabled(true);
<YourEditTextSearchbox>.addTextChangedListener(new TextWatcher()
{
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
this.adaptr.getFilter().filter(s);
}
});
public class myFilterQueryProvider implements FilterQueryProvider {
DataBaseHelper myDbHelper;
public myFilterQueryProvider(DataBaseHelper mdb) {
myDbHelper = mdb;
}
public Cursor runQuery(CharSequence constraint)
{
try {
myDbHelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
sql =""; //Your DB Query here
Cursor cursor = myDbHelper.getLobbyView(sql);
return cursor;
}
}
If you are working with a DB
simply get one Edittext textwatcher.
Every textchanged call db "LIKE" query to show your results

Categories

Resources