I need to select contact numbers/emails from phone book in android.
I have seen selecting one contact and getting the result back in onActivityResult from this link.
But I need multiple contacts to be selected from the phone book. How to achieve this?
I don't want to make my custom list, is there a way to use androids built in functionality?
I am sharing code for select multiple contact from Phone Book. you have change little bit and you can achieve your goal. thanks
getAllContacts(this.getContentResolver());
ListView lv = (ListView) findViewById(R.id.lv);
ma = new MyAdapter();
lv.setAdapter(ma);
lv.setOnItemClickListener(this);
lv.setItemsCanFocus(false);
lv.setTextFilterEnabled(true);
// adding
select = (Button) findViewById(R.id.button1);
select.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
StringBuilder checkedcontacts = new StringBuilder();
for (int i = 0; i < name1.size(); i++)
{
if (ma.mCheckStates.get(i) == true) {
checkedcontacts.append(name1.get(i).toString());
checkedcontacts.append("\n");
} else {
}
}
Toast.makeText(Display.this, checkedcontacts, 1000).show();
}
});
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
ma.toggle(arg2);
}
public void getAllContacts(ContentResolver cr) {
Cursor phones = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
null, null);
while (phones.moveToNext()) {
String name = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
name1.add(name);
phno1.add(phoneNumber);
}
phones.close();
}
class MyAdapter extends BaseAdapter implements
CompoundButton.OnCheckedChangeListener {
private SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView tv1, tv;
CheckBox cb;
MyAdapter() {
mCheckStates = new SparseBooleanArray(name1.size());
mInflater = (LayoutInflater) Display.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return name1.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
View vi = convertView;
if (convertView == null)
vi = mInflater.inflate(R.layout.row, null);
tv = (TextView) vi.findViewById(R.id.textView1);
tv1 = (TextView) vi.findViewById(R.id.textView2);
cb = (CheckBox) vi.findViewById(R.id.checkBox1);
tv.setText("Name :" + name1.get(position));
tv1.setText("Phone No :" + phno1.get(position));
cb.setTag(position);
cb.setChecked(mCheckStates.get(position, false));
cb.setOnCheckedChangeListener(this);
return vi;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
Looks like there's no such 'official' way. Your question is basically the same as this one How to select multiple contacts with Android SDK which has reference to custom implementation.
If You check AOSP Contacts application, there's no such possibility neither in documentation. The only thing I've observed from the source of AOSP Contacts is the following mention (in com.android.contacts.activities.PeopleActivity):
// TODO fix or remove multipicker code
// else if (resultCode == RESULT_CANCELED && mMode == MODE_PICK_MULTIPLE_PHONES) {
From MMS app source code You can observe the following (in ComposeMessageActivity):
private void launchMultiplePhonePicker() {
Intent intent = new Intent(Intents.ACTION_GET_MULTIPLE_PHONES);
intent.addCategory("android.intent.category.DEFAULT");
intent.setType(Phone.CONTENT_TYPE);
// We have to wait for the constructing complete.
ContactList contacts = mRecipientsEditor.constructContactsFromInput(true);
int urisCount = 0;
Uri[] uris = new Uri[contacts.size()];
urisCount = 0;
for (Contact contact : contacts) {
if (Contact.CONTACT_METHOD_TYPE_PHONE == contact.getContactMethodType()) {
uris[urisCount++] = contact.getPhoneUri();
}
}
if (urisCount > 0) {
intent.putExtra(Intents.EXTRA_PHONE_URIS, uris);
}
startActivityForResult(intent, REQUEST_CODE_PICK);
}
Field Intents.ACTION_GET_MULTIPLE_PHONES is available in ContactsContract.java but I wasn't able to find any usage of it across AOSP. So, I think it's some dead code or that action get handled in some closed code.
I've tried the same way to launch contacts selection from my test application and got only exception about no application to handle the action.
Of course, vendors Contacts applications provide such abilities (e.g. then selecting messages recipient), but it's better not to rely on them.
Though below code giving me multiple contacts
final int REQUEST_CODE_PICK_CONTACT = 57;
private void MultiplePhonePicker() {
Intent intent = new Intent("intent.action.INTERACTION_TOPMENU");
intent.putExtra("additional", "phone-multi");
startActivityForResult(intent, REQUEST_CODE_PICK_CONTACT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
switch (requestCode) {
case REQUEST_CODE_PICK_CONTACT:
switch (resultCode) {
case RESULT_OK:
Bundle bundle = intent.getExtras();
ArrayList<String> contacts = bundle.getStringArrayList("result");
break;
}
break;
}
}
Related
i am retriving mobile contact data to my app using ListView but data display two time in the List. help me how to Control of displaying contact two times.
I Refered and many solution through web , yet i am not able to sove.
i attached code below:
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private static final int PERMISSIONS_REQUEST_READ_CONTACTS = 100;
List<String> name1 = new ArrayList<String>();
List<String> phno1 = new ArrayList<String>();
MyAdapter ma ;
Button select;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, PERMISSIONS_REQUEST_READ_CONTACTS);
getAllContacts(this.getContentResolver());
ListView lv = (ListView) findViewById(R.id.lv);
ma = new MyAdapter();
lv.setAdapter(ma);
lv.setOnItemClickListener(this);
lv.setItemsCanFocus(false);
lv.setTextFilterEnabled(true);
}else {
getAllContacts(this.getContentResolver());
ListView lv = (ListView) findViewById(R.id.lv);
ma = new MyAdapter();
lv.setAdapter(ma);
lv.setOnItemClickListener(this);
lv.setItemsCanFocus(false);
lv.setTextFilterEnabled(true);
}
select = (Button) findViewById(R.id.button1);
select.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
StringBuilder checkedcontacts= new StringBuilder();
System.out.println(".............."+ma.mCheckStates.size());
for(int i = 0; i < name1.size(); i++)
{
if(ma.mCheckStates.get(i)==true)
{
checkedcontacts.append(name1.get(i).toString());
checkedcontacts.append("\n");
}
else
{
System.out.println("Not Checked......"+name1.get(i).toString());
}
}
Toast.makeText(MainActivity.this, checkedcontacts,Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
ma.toggle(arg2);
}
public void getAllContacts(ContentResolver cr) {
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.SORT_KEY_PRIMARY);
while (phones.moveToNext())
{
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println(".................."+phoneNumber +" >> "+ name);
name1.add(name);
phno1.add(phoneNumber);
}
phones.close();
}
class MyAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener
{ private SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView tv1,tv;
CheckBox cb;
MyAdapter()
{
mCheckStates = new SparseBooleanArray(name1.size());
mInflater = (LayoutInflater)MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return name1.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
vi = mInflater.inflate(R.layout.row, null);
TextView tv= (TextView) vi.findViewById(R.id.textView1);
tv1= (TextView) vi.findViewById(R.id.textView2);
cb = (CheckBox) vi.findViewById(R.id.checkBox1);
tv.setText("Name :"+ name1.get(position));
tv1.setText("Phone No :"+ phno1.get(position));
cb.setTag(position);
cb.setChecked(mCheckStates.get(position, false));
cb.setOnCheckedChangeListener(this);
return vi;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
System.out.println("hello...........");
notifyDataSetChanged();
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}}
my output :
It is because storage is returning the contacts twice ,they'll be duplicated because of google contacts,so when you retrieve just put a condition to exclude contacts which are already in.
public void getAllContacts(ContentResolver cr) {
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.SORT_KEY_PRIMARY);
while (phones.moveToNext())
{
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if(!phno1.contains(phoneNumber)) { // check wether contact already exists
name1.add(name);
phno1.add(phoneNumber);
}
}
phones.close();
}
Its been a week since I'm stuck with this problem.
I developed an application with a listView and editText to make a search. When I make a search the new list is showed very well but when I click on the item it redirect me to the item of the inicial list.
I don't know what to do please help me. These are my codes.
-For the ReaderListAdapter :
public class ReaderListAdapter extends BaseAdapter {
ArrayList<Reader> listReader = new ArrayList<Reader>();
ArrayList<Reader> arrayList;
LayoutInflater layoutInflater;
Context context;
int lastPosition = -1;
// constructeur
public ReaderListAdapter(Context context, ArrayList<Reader> listReader) {
this.listReader = listReader;
this.context = context;
arrayList = new ArrayList<Reader> ();;
layoutInflater = LayoutInflater.from(this.context);
arrayList.addAll(listReader);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return listReader.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return listReader.get(position);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
static class ViewHolder {
TextView nomView;
TextView priceView;
ImageView pictureView;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.reader_row, null);
holder = new ViewHolder();
// initialisation des vues
holder.nomView = (TextView) convertView.findViewById(R.id.name);
holder.priceView = (TextView) convertView.findViewById(R.id.price);
holder.pictureView = (ImageView) convertView.findViewById(R.id.picture);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// affchier les données convenablement dans leurs positions
holder.nomView.setText(listReader.get(position).getName());
holder.priceView.setText(String.valueOf(listReader.get(position).getPrice()));
holder.pictureView.setBackgroundDrawable(listReader.get(position).getPicture());
// changer R.anim.ton_effet
Animation animation = AnimationUtils.loadAnimation(context,(position > lastPosition)
? R.anim.up_from_bottom: R.anim.up_from_bottom);
convertView.startAnimation(animation);
position=lastPosition;
return convertView;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
listReader.clear();
if(charText.length()==0){
listReader.addAll(arrayList);
}
else{
for (Reader c : arrayList) {
if (c.getName().toLowerCase(Locale.getDefault())
.contains(charText)) {
listReader.add(c);
}
}
}
notifyDataSetChanged();
}
}
-For the MainActivity:
public class MainActivity extends Activity {
String[] listNames = { "kooora","yahoo", "hespress"};
int[] listPrices = { 1, 2, 3 };
ArrayList<Reader> listReader = new ArrayList<Reader>();;
ArrayList<Reader> listReaderNew;
ListView lv;
EditText search;
ReaderListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listReader);
search = (EditText) findViewById(R.id.search);
Drawable[] listPictures = {getResources().getDrawable(R.drawable.a1),getResources().getDrawable(R.drawable.a2),getResources().getDrawable(R.drawable.a3)};
for (int i = 0; i < listPictures.length; i++) {
listReader.add(new Reader(i + 1, listNames[i], listPictures[i], listPrices[i]));
}
adapter=new ReaderListAdapter(getApplicationContext(), listReader);
lv.setAdapter(adapter);
//lv.setAdapter(new ReaderListAdapter(getApplicationContext(), listReader));
search.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
#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
String text = search.getText().toString().toLowerCase(Locale.getDefault());
MainActivity.this.adapter.filter(text);
}});
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Intent intent=new Intent(MainActivity.this,WebActivity.class);
switch (position) {
case 0:
intent.setData(Uri.parse("http://www.kooora.com")) ;break;
case 1:
intent.setData(Uri.parse("http://www.yahoo.com")) ;break;
case 2:
intent.setData(Uri.parse("http://www.hespress.com")) ;break; }if (intent != null) {
startActivity(intent);
}}});}}
Please help me. Thanks in advance!
I think the code in onItemClick is causing this.
The problem:
searchTerm = "yahoo"
You filter yahoo and show the listitem for yahoo. Lets says its position in the list is 0. When the user clicks it, the onItemClick will be called and case 0: will be executed.
The correct logic should be,
Reader reader = parent.getAdapter().getItem(position);
String searchTerm = reader.getName(); // or whichever is the id for that listitem
if(searchTerm.contains("yahoo")) {
intent.setData(Uri.parse("http://www.yahoo.com"))
} // and so on
I create a listview get all contact from address book of Android. I try to update listview by onResume() but It's not working.
Here is my code:
public class Display extends Activity implements OnItemClickListener{
List<String> name1 = new ArrayList<String>();
List<String> phno1 = new ArrayList<String>();
List<String> email1 = new ArrayList<String>();
MyAdapter ma ;
ListView lv;
int countContact;
TextView textViewManyCount;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
getAllContacts(this.getContentResolver());
lv= (ListView) findViewById(R.id.lv);
ma = new MyAdapter();
lv.setAdapter(ma);
lv.setOnItemClickListener(this);
lv.setItemsCanFocus(false);
lv.setTextFilterEnabled(true);
textViewManyCount = (TextView) findViewById(R.id.textViewManyCount);
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
}
public void getAllContacts(ContentResolver cr) {
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
countContact = phones.getCount();
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String email = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
System.out.println(".................."+phoneNumber);
name1.add(name);
phno1.add(phoneNumber);
email1.add(email);
}
phones.close();
}
class MyAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener
{ private SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView textViewName,textViewPhone,textViewEmail;
MyAdapter()
{
mCheckStates = new SparseBooleanArray(name1.size());
mInflater = (LayoutInflater)Display.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return name1.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
vi = mInflater.inflate(R.layout.list_user, null);
textViewName = (TextView) vi.findViewById(R.id.textViewName);
textViewPhone = (TextView) vi.findViewById(R.id.textViewPhone);
textViewEmail = (TextView) vi.findViewById(R.id.textViewEmail);
textViewName.setText("Name :"+ name1.get(position));
textViewPhone.setText("Phone No :"+ phno1.get(position));
textViewEmail.setText("Email :"+ email1.get(position));
textViewManyCount.setText("Contacts: "+countContact);
return vi;
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
}
}
When I running app, It's load all contact but when I click button Home and change some information in Address book then click icon app to open app again. And onResume() method not working.
Here my onResume()
#Override
protected void onResume()
{
super.onResume();
if (lv != null)
{
updateData();
}
}
private void updateData()
{
getAllContacts(this.getContentResolver());
ma = new MyAdapter();
lv.setAdapter(ma);
ma.notifyDataSetChanged();
}
So some body help me! Plz!
Try by Replacing your updateData():
private void updateData()
{
getAllContacts(this.getContentResolver());
ma.notifyDataSetChanged();
}
You may be referencing an old ListView (lv) that is not the new ListView you see when you resume your Activity. Try getting the reference to lv again using Activity.findViewById(R.id.xxxx) in onResume().
You could also try reusing the old adapter instead of creating a brand new one (by clearing it and updating it's content). If you're reusing the old adapter, just make sure you give the old adapter to the new ListView using ListView.setAdapter(ma).
You should also have MyAdapter.getItemId(int position) return position instead of 0.
I am trying to create a application for android. in which at one point i need to open a activity i need to display all the contacts on user's phone in a listview with checkbox, so that multiple contacts can be selected. I have written a code which currently shows the list of all the contacts but without checkbox as you can see in the image attached. Next, when the user selects the required contacts using checkbox and clicks on DONE button the result should be derived in main activity and all the contacts which the user selected should be displayed in the EditText like this Frank <+911234567890>, John <+913456789012>, Ashley <+911237890456>,. How can i achieve what i want? And also the dashes(-) which are currently getting displayed should also disappear.
Use the following to add checkboxes on all the items:
listView.setChoiceMode(CHOICE_MODE_MULTIPLE);
Not only will this add checkboxes to all the items, but it will handle all the check states for you. You have several methods you can use to get the state of the items:
getCheckedItemCount()
getCheckedItemIds()
getCheckedItemPositions()
And you can use setItemChecked() to set any item's checked state programmatically. Take a look at this tutorial for a guide how to make a multiple selection list.
split the string on each '-' using function split("-") and then concatenate it.
use the code snippet below to retrieve all contacts from the phonebook,append them in a ListView containing checkboxes to enable multiple selection,,it is clear and straight to the point.
public class Display extends Activity implements OnItemClickListener{
List<String> name1 = new ArrayList<String>();
List<String> phno1 = new ArrayList<String>();
MyAdapter ma ;
Button select;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
getAllContacts(this.getContentResolver());
ListView lv= (ListView) findViewById(R.id.lv);
ma = new MyAdapter();
lv.setAdapter(ma);
lv.setOnItemClickListener(this);
lv.setItemsCanFocus(false);
lv.setTextFilterEnabled(true);
// adding
select = (Button) findViewById(R.id.button1);
select.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
StringBuilder checkedcontacts= new StringBuilder();
for(int i = 0; i < name1.size(); i++)
{
if(ma.mCheckStates.get(i)==true)
{
checkedcontacts.append(name1.get(i).toString());
checkedcontacts.append("\n");
}
else
{
}
}
Toast.makeText(Display.this, checkedcontacts,1000).show();
}
});
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
ma.toggle(arg2);
}
public void getAllContacts(ContentResolver cr) {
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
name1.add(name);
phno1.add(phoneNumber);
}
phones.close();
}
class MyAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener
{ private SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView tv1,tv;
CheckBox cb;
MyAdapter()
{
mCheckStates = new SparseBooleanArray(name1.size());
mInflater = (LayoutInflater)Display.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return name1.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
vi = mInflater.inflate(R.layout.row, null);
tv= (TextView) vi.findViewById(R.id.textView1);
tv1= (TextView) vi.findViewById(R.id.textView2);
cb = (CheckBox) vi.findViewById(R.id.checkBox1);
tv.setText("Name :"+ name1.get(position));
tv1.setText("Phone No :"+ phno1.get(position));
cb.setTag(position);
cb.setChecked(mCheckStates.get(position, false));
cb.setOnCheckedChangeListener(this);
return vi;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
}
I have an application with three textviews and one checkbox in each row of a listview.what I want that on a click of a button I will be able to get the state of each checkbox and the row corresponding to (isChecked) checkboxes get deleted.one more thing my checkboxes are hardcoded in an xml file.I have searched a lot but couldn't find anything specific.thanks in advance.HERE IS MY CODE...
public class recentcalllistultimate extends ListActivity implements OnClickListener {
CheckBox cb;
Button edit,done;
ImageButton contacts;
ListView lv;
ListView lvultimate;
listviewadapterultimate lvar;
int[] uniqueid;
String[] names;
String[] types;
;
RelativeLayout rl;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
LayoutParams params=newRelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
LinearLayout mainLayout = new LinearLayout(this);
mainLayout.setOrientation(LinearLayout.VERTICAL);
LayoutInflater layoutInflater = getLayoutInflater();
mainLayout.addView(layoutInflater.inflate(R.layout.listviewonly, null));
mainLayout.addView(layoutInflater.inflate(R.layout.allbuttons, null));
this.addContentView(mainLayout, params);
cb = (CheckBox) findViewById(R.id.checkboxdelete);
getContacts();
lv = (ListView) findViewById(android.R.id.list);
lvar = new listviewadapterultimate(this, names, types,uniqueid);
lv.setAdapter(lvar);
contacts = (ImageButton) findViewById(R.id.button_keypad);
contacts.setOnClickListener(this);
edit = (Button) findViewById(R.id.editbutton);
done=(Button)findViewById(R.id.donebutton);
done.setOnClickListener(new View.OnClickListener() {
------>>> public void onClick(View v) {
// TODO Auto-generated method stub
cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, booleanisChecked) {
// TODO Auto-generated method stub
//WHAT TO DO HERE....
}
}
});
}
------>>> });
edit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
AddDialog ada=new AddDialog(recentcalllistultimate.this);
ada.show();
}
});
}// on create
public void getContacts() {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(android.provider.CallLog.Calls.CONTENT_URI, null,
null, null, null);
if (cur.getCount() > 0) {
int i = 0;
int foo = 0;
names = new String[cur.getCount()];
types = new String[cur.getCount()];
duration = new long[cur.getCount()];
uniqueid = new int[cur.getCount()];
int n = cur.getColumnIndex(CallLog.Calls._ID);
int k = cur.getColumnIndex(CallLog.Calls.CACHED_NAME);
int y = cur.getColumnIndex(CallLog.Calls.NUMBER);
int z = cur.getColumnIndex(CallLog.Calls.CACHED_NUMBER_TYPE);
while (cur.moveToNext()) {
uniqueid[foo] = cur.getInt(n);
String str = cur.getString(k);
if (str == null) {
names[foo] = cur.getString(y);
}// if
else {
names[foo] = str;
}
int temp = cur.getInt(z);
switch (temp) {
case 0:
types[foo] = "unknown";
break;
case 1:
types[foo] = "home";
break;
case 2:
types[foo] = "mobile";
break;
case 3:
types[foo] = "work";
break;
}// switch
long doo = cur.getInt(d);
duration[foo] = doo;
foo++;
} // while
}// if
}//getcontacts
public void onClick(View v) {
// TODO Auto-generated method stub
if(v==contacts){
Intent intent = new Intent();
intent.setClassName("com.a.Activities",
"com.a.Activities.DialPad");
startActivity(intent);
finish();
}
}
}// class
.................................
public class listviewadapterultimate extends BaseAdapter {
viewHolder holder;
Activity context;
String[] names;
String[] types;
String[] duration;
int[] uniqueid;
public listviewadapterultimate(Activity context, String[] names,
String[] types, int[] uniqueid2 ) {
this.context = context;
this.names = names;
this.types = types;
uniqueid=uniqueid2;
}
public int getCount() {
// TODO Auto-generated method stub
return names.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public class viewHolder {
TextView top;
TextView bottom;
TextView down;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView == null) {
holder = new viewHolder();
LayoutInflater inflator = context.getLayoutInflater();
convertView = inflator.inflate(R.layout.recenttextviewonlyultimate, null);
holder.top = (TextView) convertView.findViewById(R.id.toptext_u);
holder.bottom = (TextView) convertView
.findViewById(R.id.bottomtext_u);
holder.down = (TextView) convertView.findViewById(R.id.recentuniqueid_u);
convertView.setTag(holder);
} else {
holder = (viewHolder) convertView.getTag();
//holder.cb.setVisibility(View.VISIBLE);
}
holder.top.setText(names[position]);
holder.bottom.setText(types[position]);
holder.down.setText("" + uniqueid[position]);
return convertView;
}
}
................
Try this:
Inside your getView(...) method...
final CheckBox lChk = ((CheckBox) pConvertView.findViewById(R.id.myChkBoxID));
private List<lisInfo> m_lisInfo = new ArrayList<lisInfo>();
lChk.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// Populate the listInfo with check box status
m_lisInfo.get(lPosition).setChkBoxStatus((isChecked));
}
});
public class lisInfo{
private boolean chkBoxStatus;
public boolean isChkBoxStatus() {
return chkBoxStatus;
}
public void setChkBoxStatus(boolean chkBoxStatus) {
this.chkBoxStatus = chkBoxStatus;
}
}
Now iterate the listInfo wherever required to get the check boxes statuses in the list view
maintain an array of boolean inside adapter . set listener on ckeckbox in getview which will swipe values of array on check/uncheck .
now make this array accesible in activity where on button
click()
{
for(int i=0;i<array.size;i++)
{
if(array[i])
adapter.deelet(item i);
//modify syntax
}
}