Android Search function using a string from an EditText - android

The Search function in my Android app works. I'm using onSearchRequested(); to invoke the Search function. Now what I'd like to do is not use onSearchRequested(); and pass a string from an EditText to the search method and display the results in a List. Here's my search as it's working when onSearchRequested is called:
SearchPage Activity:
DBHelper = new DBAdapter(this);
DBHelper.open();
Intent intent = getIntent();
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
showResults(query);
}
//--- END onSearchRequested
private void showResults(String query) {
Cursor cursor = DBHelper.searchDB(query);
startManagingCursor(cursor);
String[] searchFrom = new String[] { DBAdapter.KEY_YEAR,
DBAdapter.KEY_MAKE, DBAdapter.KEY_MODEL };
int[] displayHere = new int[] { R.id.rYearTV, R.id.rMakeTV,
R.id.rModelTV };
final SimpleCursorAdapter records = new SimpleCursorAdapter(this,
R.layout.record_2, cursor, searchFrom, displayHere);
setListAdapter(records);
DBAdapter Activity:
//--- GET RECORDS FOR SEARCH
public Cursor searchDB(String query) {
String[] parts = query.split(" ");
String queryString = "";
for(int i = 0; i < parts.length; i++) {
queryString += KEY_YEAR + " LIKE '%" + parts[i] + "%' OR ";
queryString += KEY_MAKE + " LIKE '%" + parts[i] + "%' OR ";
queryString += KEY_MODEL + " LIKE '%" + parts[i] + "%'";
if(i != (parts.length - 1)) {
queryString += " OR ";
}
}
return db.query(true, DB_TABLE,
new String[] { KEY_ROWID, KEY_SDATE, KEY_YEAR, KEY_MAKE, KEY_MODEL },
queryString, null, null, null, null, null);
}
//--- END Get Records for Search
I'd like to pass a String into the search function String searchData = searchEditText.getText().toString(); and have the search function go to work on the passed string by pressing a "Search" button. Can someone help get me started?

You should have EditText like that in your layout:
<EditText
android:id="#+id/search_query"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="search"
android:imeOptions="actionSearch"
android:inputType="text" />
And in your Activity's onCreate:
EditText searchQuery = (EditText) findViewById(R.id.search_query);
searchQuery.setOnEditorActionListener(new OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
String searchData = searchQuery.getText().toString();
showResults(searchData); //passing string to search in your database to your method
return true;
}
return false;
}
});
setOnEditorActionListener is used to perform search when user presses search button on keayboard. You can read more about imeActions here.
According to your code call showResults(searchData); to make search and display results in a list.
EDIT:
According to your code call it in SearchPage Activity:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView and other your features
DBHelper = new DBAdapter(this);
DBHelper.open();
EditText searchQuery = (EditText) findViewById(R.id.search_query);
Button yourButton = (Button) findViewById(R.id.yourButtonId);
yourButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String searchData = searchQuery.getText().toString();
showResults(searchQuery);
}
});
}
private void showResults(String query) {
Cursor cursor = DBHelper.searchDB(query);
startManagingCursor(cursor);
String[] searchFrom = new String[] { DBAdapter.KEY_YEAR,
DBAdapter.KEY_MAKE, DBAdapter.KEY_MODEL };
int[] displayHere = new int[] { R.id.rYearTV, R.id.rMakeTV,
R.id.rModelTV };
final SimpleCursorAdapter records = new SimpleCursorAdapter(this,
R.layout.record_2, cursor, searchFrom, displayHere);
setListAdapter(records);
}

Related

How to search the data in listview by more than one thing?

Right now, my app filters the data in a listview when somethings is entered into the editText, but it can only filter by one thing at a time. I want it to be able to filter by more than value. For example, if someone types in "chicken" it should filter the recipes by the word 'chicken'. But, if someone then types in "dinner", I want it to filter the recipes by both "chicken" and "dinner." Eventually, I want to make it so those values appear as checkboxes above the listview so they can be easily removed.
I can't figure out how to do this. I played around with loops at first but didn't really get anywhere.
public class SearchActivity extends NavDrawerActivity {
private DBHandler dbHelper;
private SimpleCursorAdapter dataAdapter;
ArrayList<String> filters = new ArrayList<String>();
//String[] filters;
FrameLayout frameLayout;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main_activity3);
frameLayout = (FrameLayout) findViewById(R.id.activity_frame);
// inflate the custom activity layout
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View activityView = layoutInflater.inflate(R.layout.activity_main_activity3, null, false);
// add the custom layout of this activity to frame layout.
frameLayout.addView(activityView);
dbHelper = new DBHandler(this, null, null, 1);
//dbHelper.open();
//Clean all data
dbHelper.deleteAllRecipes();
//Add some data
dbHelper.insertSomeRecipes();
//Generate ListView from SQLite Database
displayListView();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
private void displayListView() {
final Cursor cursor = dbHelper.fetchAllRecipes();
// The desired columns to be bound
String[] columns = new String[]{
//DBHandler.COLUMN_CODE,
DBHandler.COLUMN_NAME,
DBHandler.COLUMN_TYPE,
DBHandler.COLUMN_INGRED
};
// the XML defined views which the data will be bound to
int[] to = new int[]{
//R.id.code,
R.id.name,
R.id.type,
R.id.ingredient,
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.recipeinfo,
cursor,
columns,
to,
0);
ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
// Get the cursor, positioned to the corresponding row in the result set
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
String recipeName = cursor.getString(cursor.getColumnIndexOrThrow("name"));
Intent n = new Intent(getApplicationContext(), RecipeActivity.class);
//n.putExtra("position", position);
n.putExtra("recipeName", recipeName);
startActivity(n);
}
});
//final GridView gridView = (GridView)findViewById(R.id.gridView);
final TextView tv = (TextView)findViewById(R.id.textView14);
final EditText myFilter = (EditText) findViewById(R.id.myFilter);
myFilter.setImeActionLabel("Filter",1);
myFilter.setPrivateImeOptions("actionUnspecified");
myFilter.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
if (id == 1 || id == EditorInfo.IME_NULL) {
String filter = textView.getText().toString();
dataAdapter.getFilter().filter(filter);
filters.add(filter);
tv.append(filter);
myFilter.setText("");
}
return false;
}
});
dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return dbHelper.fetchRecipesByName(constraint.toString());
}
});
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Then you start a new Activity via Intent
Intent intent = new Intent();
intent.setClass(this, RecipeActivity.class);
intent.putExtra("position", position);
// Or / And
intent.putExtra("id", id);
startActivity(intent);
}
}
fetchRecipesByName in DBHandler
public Cursor fetchRecipesByName(String inputText) throws SQLException {
SQLiteDatabase mDb = this.getWritableDatabase();
Log.w(TAG, inputText);
Cursor mCursor = null;
if (inputText == null || inputText.length () == 0) {
mCursor = mDb.query(SQLITE_TABLE, new String[] {COLUMN_ROWID,
COLUMN_NAME, COLUMN_TYPE, COLUMN_INGRED, COLUMN_IMGPATH},
null, null, null, null, null);
}
else {
mCursor = mDb.query(true, SQLITE_TABLE, new String[] {COLUMN_ROWID,
COLUMN_NAME, COLUMN_TYPE, COLUMN_INGRED, COLUMN_IMGPATH},
COLUMN_NAME + " like '%" + inputText + "%'" + " or " +
COLUMN_TYPE + " like '%" + inputText + "%'" + " or " +
COLUMN_INGRED + " like '%" + inputText + "%'",
null, null, null, null, null);
}
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
What is the implementation of dbHelper.fetchReccipesByName()? I think, as of now, it queries the table only by one thing. You should change its logic and implement your complex need in this method (obviously, it should be an SQL query execution).
As a best practice, you should call listView.setFilterText() instead of dataAdapter.getFilter().filter(), because this method is supposed to run in secondary thread for the reason that DB queries are time consuming. If you call listView.setFilterText(), the framework will take care of threading and calls filter.filter() in secondary thread.
And finally, since you are searching by more than one keyword, but setFilterText() accepts only one CharSequence param, you should encode somehow many keywords into single String (say comma separated). And while querying you could decode the constraint to get the keywords.

Adapter is not displaying data, only after search

Thanks for your time in advance. I'm new to android and I'd like to learn more. I have a code that is displaying data from sql only after search is clicked and I don't know how can I make it display all the data from sql with let's say alfabetical order at first and later on if search is used it will display data matching to search request.
public class EmployeeList extends ListActivity {
protected EditText searchText;
protected SQLiteDatabase db;
protected Cursor cursor;
protected ListAdapter adapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
searchText = (EditText) findViewById(R.id.searchText);
db = (new DatabaseHelper(this)).getWritableDatabase();
}
public void onListItemClick(ListView parent, View view, int position, long id) {
Intent intent = new Intent(this, EmployeeDetails.class);
Cursor cursor = (Cursor) adapter.getItem(position);
intent.putExtra("EMPLOYEE_ID", cursor.getInt(cursor.getColumnIndex("_id")));
startActivity(intent);
}
public void search(View view) {
// || is the concatenation operation in SQLite
cursor = db.rawQuery("SELECT _id, firstName, lastName, title FROM employee WHERE firstName || ' ' || lastName LIKE ?",
new String[]{"%" + searchText.getText().toString() + "%"});
adapter = new SimpleCursorAdapter(
this,
R.layout.employee_list_item,
cursor,
new String[] {"firstName", "lastName", "title"},
new int[] {R.id.firstName, R.id.lastName, R.id.title});
setListAdapter(adapter);
}
}
Thanks.
i see you are using onClick in XML layout , right?
any ways, no problem.
add new method populateList() as following
public void populateList(boolean useWhere) {
// || is the concatenation operation in SQLite
if(useWhere){
cursor = db.rawQuery("SELECT _id, firstName, lastName, title FROM employee WHERE firstName || ' ' || lastName LIKE ?", new String[]{"%" + searchText.getText().toString() + "%"});
}else{
cursor = db.rawQuery("SELECT _id, firstName, lastName, title FROM employee");
}
adapter = new SimpleCursorAdapter(
this,
R.layout.employee_list_item,
cursor,
new String[] {"firstName", "lastName", "title"},
new int[] {R.id.firstName, R.id.lastName, R.id.title});
setListAdapter(adapter);
}
change search() as following:
public void search(View view){
populateList(true);
}
add a call populateList(false); to onCreate() of the activity.
so oncreate activity, will call search to execuste without WHERE and when c alled from button click, it will execute the WHERE sql
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
searchText = (EditText) findViewById(R.id.searchText);
db = (new DatabaseHelper(this)).getWritableDatabase();
populateList(false);
}

get details of contact selected from list view

i am designing application in which i want to allow user to select multiple contact to send messages to. I have successfully retrieved the list of user in the listview with checkbox using the following code. now i want that when the user clicks on the "DONE" button, the PHONE NUMBER of the all selected contact should be retrieved in EDITTEXT in format like John <+919898xxxxxx>, Rick <+919988xxxxxx> and also that all the phone numbers containing just 10 digits i.e "9898xxxxxx" should be stored in a string seperated by comma (9898xxxxxx, 9988xxxxxx) automatically. how can i accomplish the requirement.
public class ContactsActivity extends ListActivity {
protected static final String TAG = null;
public String[] Contacts = {};
public int[] to = {};
public ListView myListView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
final Button done_Button = (Button) findViewById(R.id.done_Button);
final Button clear_Button =(Button) findViewById(R.id.clear_Button);
Cursor mCursor = getContacts();
startManagingCursor(mCursor);
ListAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_multiple_choice, mCursor,
Contacts = new String[] {ContactsContract.Contacts.DISPLAY_NAME },
to = new int[] { android.R.id.text1 });
setListAdapter(adapter);
myListView = getListView();
myListView.setItemsCanFocus(false);
myListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
clear_Button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"Selections Cleared", Toast.LENGTH_SHORT).show();
ClearSelections();
}
});
/** When 'Done' Button Pushed: **/
done_Button.setOnClickListener(new View.OnClickListener() {
public void onClick (View v){
Log.i(TAG,":Done Button Selected:");
SparseBooleanArray selectedPositions = myListView.getCheckedItemPositions();
Log.i(TAG,"Number of Checked Positions: " + selectedPositions.size());
for (int i=0; i<selectedPositions.size(); i++) {
if (selectedPositions.get(selectedPositions.keyAt(i)) == true) {
//do stuff
}
}
}
});
}
private void ClearSelections() {
int count = this.myListView.getAdapter().getCount();
for (int i = 0; i < count; i++) {
this.myListView.setItemChecked(i, false);
}
}
private Cursor getContacts() {
// Run query
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME};
String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER + " = '"
+ ("1") + "'";
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC";
return managedQuery(uri, projection, selection, selectionArgs,
sortOrder);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_contacts, menu);
return true;
}
}
configured it finally
done_Button.setOnClickListener(new View.OnClickListener() {
public void onClick (View v){
String name = null;
String number = null;
long [] ids = myListView.getCheckedItemIds();
for(long id : ids) {
Cursor contact = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id + "" }, null);
while(contact.moveToNext()){
name = contact.getString(contact.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
//name+=name;
number = contact.getString(contact.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//number+=number;
}
Toast.makeText(getApplicationContext(), "Name: " +name + "\n" + "Number: " + number , Toast.LENGTH_LONG).show();
}
}
});
String numberListString = "";
for (int i=0; i<selectedPositions.size(); i++) {
if (selectedPositions.get(selectedPositions.keyAt(i)) == true) {
//do stuff
numberListString = numberListString + "," + numberAtCurrentSelectedPostion;
}
}
mEditText.setText(numberListString);
Try this on your done button press:-
done_Button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
name.clear();
number.clear();
Log.i(TAG, ":Done Button Selected:");
SparseBooleanArray selectedPositions = myListView
.getCheckedItemPositions();
Log.i(TAG,
"Number of Checked Positions: "
+ selectedPositions.size());
Cursor cur = getContacts();
for (int i = 0; i < selectedPositions.size(); i++) {
if (selectedPositions.get(selectedPositions.keyAt(i)) == true) {
// do stuff
cur.moveToPosition(selectedPositions.keyAt(i));
name.add(cur.getString(1));
}
}
for (int i = 0; i < name.size(); i++) {
Cursor lCursor = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, "DISPLAY_NAME = ? ",
new String[] { name.get(i) }, null);
lCursor.moveToFirst();
number.add(lCursor.getString(lCursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
lCursor.close();
}
}
});
where name and number are array list of type String. You will get all selected name and there numbers. Now you can show them in Edit Text as you like.
I think this will help you.

Edittext only adding first item to arraylist<string>

I'm at a lose with this one. Trying to take edittext from a list view and put them into an arraylist to use on another activity.
public class editpage extends ListActivity {
public static String editString;
private dbadapter mydbhelper;
public static ArrayList<String> editTextList = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_list);
mydbhelper = new dbadapter(this);
mydbhelper.open();
fillData();
}
public void fillData() {
Cursor e = mydbhelper.getUserWord();
startManagingCursor(e);
String[] from = new String[] {dbadapter.KEY_USERWORD,};
int[] to = new int[] {R.id.textType,};
SimpleCursorAdapter editadapter =
new SimpleCursorAdapter(this, R.layout.edit_row, e, from, to);
ListView list = getListView();
View footer = getLayoutInflater().inflate(R.layout.footer_layout, list, false);
list.addFooterView(footer);
setListAdapter(editadapter);
}
public void onClick(View footer){
final MediaPlayer editClickSound = MediaPlayer.create(this, R.raw.button50);
final EditText editText = (EditText) findViewById(R.id.editText);
for (int i = 0; i < getCount(); i++){
editTextList.add(editText.getText().toString());
}
editClickSound.start();
startActivity(new Intent("wanted.pro.madlibs.OUTPUT"));
};
//can't get my getcount to work dynamically. I want it to be based off how many items are shown in next code showing my cursor but can't get to work atm unless I set statically to prevent errors and move to next activity
private int getCount() {
// TODO Auto-generated method stub
return 10;
}
Cursor to filter data pulled from database
public Cursor getUserWord()
{
return myDataBase.query(USER_WORD_TABLE, new String[] {
KEY_ID,
KEY_CATEGORY,
KEY_SOURCE, KEY_TITLE, KEY_USERWORD
},
KEY_CATEGORY+ "=" + categories.categoryClick + " AND " + KEY_SOURCE+ "="
+source.sourceClick + " AND " + KEY_TITLE+ "=" + title.titleClick,
null, null, null, KEY_ID);
Cursor to filter data from database to show in listview
public Cursor getUserWord()
{
return myDataBase.query(USER_WORD_TABLE, new String[] {
KEY_ID,
KEY_CATEGORY,
KEY_SOURCE, KEY_TITLE, KEY_USERWORD
},
KEY_CATEGORY+ "=" + categories.categoryClick + " AND " + KEY_SOURCE+ "="
+source.sourceClick + " AND " + KEY_TITLE+ "=" + title.titleClick,
null, null, null, KEY_ID);
}
My next activity will be showing the edittext merged with a string from my database. I take this string and replace edit01, edit02 etc with the users input from edittext fields on previous activity
public class output extends ListActivity {
private dbadapter mydbhelper;
#Override
public void onCreate(Bundle savedInstantState){
super.onCreate(savedInstantState);
setContentView(R.layout.outview);
mydbhelper = new dbadapter(this);
mydbhelper.open();
fillData();
}
private final Runnable mTask = new Runnable(){
public void run(){
TextView textView = (TextView)findViewById(R.id.outputText);
String story = textView.getText().toString();
CharSequence modifitedText1 = Replacer.replace(story,
"edit01", Html.fromHtml("<font color=\"red\">"+ editpage.editTextList.get(0) +"</font>"));
CharSequence modifitedText2 = Replacer.replace(modifitedText1,
"edit02", Html.fromHtml("<font color=\"red\">"+ editpage.editTextList.get(1) +"</font>"));
textView.setText(modifitedText2);
}
};
private final Handler mHandler = new Handler();
private void fillData() {
Cursor st = mydbhelper.getStory();
startManagingCursor(st);
String[] from = new String[] {dbadapter.KEY_TITLESTORY};
int[] to = new int[] {R.id.outputText};
SimpleCursorAdapter adapter =
new SimpleCursorAdapter(this, R.layout.out_row, st, from, to);
setListAdapter(adapter);
}
#Override
protected void onResume() {
mydbhelper.open();
mHandler.postDelayed(mTask, 10);
super.onResume();
}
#Override
protected void onPause() {
mydbhelper.close();
super.onPause();
}
}
The furthest I can get this to work is with one item. I will be having anywhere from 4-10 edittexts on the first activity I show here. But no matter what I've tried it will only display the text entered into the first edittext field. In it's current state it will fill edit01 & edit02 in the string from database with what was put in first edittext in previous activity.
Well was finally able to get this to work without changing to much. I had to fight with it and try a bunch of things. Figured I would share the answer in case someone tries something like this. It came down to changing (R.id.editText) to have its own unique id.
private void editId(){
if(findViewById(R.id.editText) == null){
}else{
for(int editI= 0; editI<getCount(); editI++){
EditText editText = (EditText) findViewById(R.id.editText);
editText.setId(editI);
m_edit.add(editI, editText);
}}
}
and calling editId() in my onclick for my footer button
I had to change my runnable to work dynamically but that is another issue.

Multiple Contact Picker List [getCheckedItemPositions()]

Below is a my Contact_Picker class. I am going to be using this class to create a list of contacts with checkboxes, giving the user the option to select multiple contacts from their phonebook. I have a layout xml that I am using that has 2 buttons at the bottom: Clear All and Done.
When 'Done' is pressed, I need it to get all of the names that are checked, and save them in a list/preferences file. Right now, I can find what POSITIONS are checked, but I don't know how to retrieve the corresponding information associated with them (the name/phone number of the selected contact). I have searched for days on a method that will work, and have not come up with anything. Any code/pseudo code/ideas are greatly appreciated.
Contact_Picker Class:
public class Contact_Picker extends ListActivity {
protected static final String TAG = null;
public String[] Contacts = {};
public int[] to = {};
public ListView myListView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contacts_list);
final Button done_Button = (Button) findViewById(R.id.done_Button);
final Button clear_Button =(Button) findViewById(R.id.clear_Button);
Cursor mCursor = getContacts();
startManagingCursor(mCursor);
ListAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_multiple_choice, mCursor,
Contacts = new String[] {ContactsContract.Contacts.DISPLAY_NAME },
to = new int[] { android.R.id.text1 });
setListAdapter(adapter);
myListView = getListView();
myListView.setItemsCanFocus(false);
myListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
clear_Button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"Selections Cleared", Toast.LENGTH_SHORT).show();
ClearSelections();
}
});
/** When 'Done' Button Pushed: **/
done_Button.setOnClickListener(new View.OnClickListener() {
public void onClick (View v){
Log.i(TAG,":Done Button Selected:");
SparseBooleanArray checkedPositions = myListView.getCheckedItemPositions();
Log.i(TAG,"Number of Checked Positions: " + checkedPositions.size());
if (checkedPositions != null)
{
int count = myListView.getCount();
for ( int i=0;i<count;i++)
{
Log.i(TAG,"Selected items: " + checkedPositions.get(i));
}
}
}
}); //<-- End of Done_Button
} //<-- end of onCreate();
private void ClearSelections() {
int count = this.myListView.getAdapter().getCount();
for (int i = 0; i < count; i++) {
this.myListView.setItemChecked(i, false);
}
}
private Cursor getContacts() {
// Run query
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME };
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '"
+ ("1") + "'";
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC";
return managedQuery(uri, projection, selection, selectionArgs,
sortOrder);
} //<-- end of getContacts();
}
Will Create Output Such As:
Sele02-12 01:25:09.733: INFO/(219): :Done Button Selected:
02-12 01:25:09.743: INFO/(219): Number of Checked Positions: 2
02-12 01:25:09.743: INFO/(219): Selected items: true
02-12 01:25:09.743: INFO/(219): Selected items: false
02-12 01:25:09.743: INFO/(219): Selected items: true
02-12 01:25:09.752: INFO/(219): Selected items: false
see this
public String[] getlistcontacts() {
// TODO Auto-generated method stub
int i=0;
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null,null, null, null);
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null , null);
int a= cur.getCount();
String[] cttlist=new String[a+1];
cur.moveToFirst();
pCur.moveToFirst();
for (int j=0; j<a;j++){
int nm=cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
//int nb=pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
String name=cur.getString(nm);
int nb=pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
String number=pCur.getString(nb);
cttlist[i]=name.concat("<;>").concat(number);
//Toast.makeText(PizzastimeActivity.this, "alkamkljziha"+name+":"+number, Toast.LENGTH_LONG).show();
i++;
cur.moveToNext();
pCur.moveToNext();
}
return cttlist;
}
in this code i tried to get list of contact in a table of string then u can use it easily
Here is a correct approach:
SparseBooleanArray selectedPositions = listView.getCheckedItemPositions();
for (int i=0; i<selectedPositions.size(); i++) {
if (selectedPositions.get(selectedPositions.keyAt(i)) == true) {
//do stuff
}
}
maybe you can manually keep track of your contacts:
Vector<String> names=new Vector<String>();
private Cursor getContacts() {...
Cursor cur = managedQuery(uri, projection, selection, selectionArgs,
sortOrder);
int col = cur.getColumnIndex("display_name");
while(cur.moveToNext())
names.add(cur.getString(col));
cur.moveToFirst();
return cur;
}
and then output them synchronously:
for ( int i=0;i<count;i++)
{
Log.i(TAG,"Selected items: " + checkedPositions.get(i));
Log.i(TAG,"Selected name: " + names.get(i));
}
I forgot about this post until Team Pannous left an answer. I'm sure that their method would work, but I ended up using this instead:
SparseBooleanArray checked = myListView.getCheckedItemPositions();
for (int i = 0; i < ContactsList.length; i++) {
Log.v(TAG, ContactsList[i] + ": " + checked.get(i)); //<-- Will print every contact with 'true'
if (checked.get(i) == true) {
Object o = getListAdapter().getItem(i);
String name = o.toString();
WriteSettings(self, name);
}
}
Just in case anyone else is having a problem with a multiple-choice listview.

Categories

Resources