Retrieving mobile contacts are displaying twice in the application - android

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

Related

not getting the result in after filter the listview

i just create an app in which i m getting back the same contact list as it is saved,data is not getting filter,i want to get the data that user enter in the autocompletetextview,it get match with with the listview and give the result,but in this code m getting back whole of the listview..how to compare it,and display only resultant data...?? please suggest me with some clue.
MainActivity
public class MainActivity extends Activity implements OnItemClickListener,
OnItemSelectedListener {
SearchView mSearchView;
AutoCompleteTextView searchText;
ArrayList<String> name1 = new ArrayList<String>();
ArrayList<String> phno1 = new ArrayList<String>();
ArrayList<String> phno0 = new ArrayList<String>();
MyAdapter ma;
String[] cellArray = null;
String contacts;
ListView lv;
String phoneNumber, name;
StringBuilder b = new StringBuilder();
List<String> arrayListNames;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getAllCallLogs(this.getContentResolver());
searchText = (AutoCompleteTextView) findViewById(R.id.autocomplete);
lv = (ListView) findViewById(R.id.lv);
ma = new MyAdapter();
searchText.setThreshold(1);
searchText.setAdapter(ma);
lv.setAdapter(ma);
lv.setOnItemClickListener(this);
lv.setItemsCanFocus(false);
lv.setTextFilterEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
getMenuInflater().inflate(R.menu.contact_main, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case android.R.id.home:
StringBuilder checkedcontacts = new StringBuilder();
System.out.println(".............." + ma.mCheckStates.size());
for (int i = 0; i < name1.size(); i++)
{
if (ma.mCheckStates.get(i) == true) {
// phno0.add(name1.get(i).toString());
phno0.add(phno1.get(i).toString());
checkedcontacts.append(name1.get(i).toString());
checkedcontacts.append("\n");
} else {
System.out.println("..Not Checked......"
+ name1.get(i).toString());
}
}
Intent returnIntent = new Intent();
returnIntent.putStringArrayListExtra("name", phno0);
setResult(RESULT_OK, returnIntent);
finish();
break;
case R.id.action_search:
searchText.setVisibility(View.VISIBLE);
//String text_To_search= searchText.getText().toString().trim();
searchText.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub
//System.out.println(".............." + ma.mCheckStates.size());
for(int i=0;i<name1.size();i++){
if(searchText.getText().toString().trim().equals(name1.get(i).toString()))
ma.getFilter().filter(s);
/* //Toast.makeText(getApplication(), name1.get(i), Toast.LENGTH_LONG).show();
phno2.add(name1.get(i) + phno1.get(i));*/
}
//lv.setAdapter(ma);
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
// TODO Auto-generated method stub
}
});
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view,
int position, long id) {
// TODO Auto-generated method stub
ma.toggle(position);
//
}
public void getAllCallLogs(ContentResolver cr) {
mPeopleList.clear();
Cursor phones = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
+ " ASC");
while (phones.moveToNext()) {
phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
name = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
System.out.println(phoneNumber);
name1.add(name);
phno1.add(phoneNumber);
}
phones.close();
}
class MyAdapter extends BaseAdapter implements Filterable,
CompoundButton.OnCheckedChangeListener {
public SparseBooleanArray mCheckStates;
// public ListFilter listFilter;
LayoutInflater mInflater;
TextView tv1, tv;
CheckBox cb;
MyAdapter() {
mCheckStates = new SparseBooleanArray(name1.size());
mInflater = (LayoutInflater) MainActivity.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#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(name1.get(position));
tv1.setText(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);
}
#Override
public Filter getFilter() {
// TODO Auto-generated method stub
Filter filter = new Filter() {
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
arrayListNames = (List<String>) results.values;
notifyDataSetChanged();
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
ArrayList<String> FilteredArrayNames = new ArrayList<String>();
// perform your search here using the searchConstraint String.
constraint = searchText.getText().toString().toLowerCase();
for (int i = 0; i < name1.size(); i++) {
String dataNames = name1.get(i);
if (dataNames.toLowerCase().startsWith(constraint.toString())) {
FilteredArrayNames.add(dataNames);
}
}
results.count = FilteredArrayNames.size();
results.values = FilteredArrayNames;
//Log.e("VALUES", results.values.toString());
return results;
}
};
return filter;
}
}
}
You can do that in two steps:
Build a filterable list - How to make a nice looking ListView filter on Android
And create a search interface.

Update listview when run onResume() in Android

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.

Java.net.socket exception:address family not supported when i tried on physical device,but it is working fine with emulator

When i tried working on emulator it display all contacts of emulator in listview..when i tried on physicaldevice..it shows address family not supported by protocol
public class MainActivity extends Activity {
ListView listView;
CustomAdapter customAdapter;
ArrayList<String> nameList = new ArrayList<String>();
ArrayList<String> numberList = new ArrayList<String>();
//ArrayList<String> selectedNameList = new ArrayList<String>();
//ArrayList<String> selectedNumberList = new ArrayList<String>();
private LinkedHashMap<String, Contact> allContacts = new LinkedHashMap<String, Contact>();
private static ArrayList<Contact> contacts = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView =(ListView) findViewById(R.id.listview);
customAdapter = new CustomAdapter();
new ContactsBackground().execute();
}
private class ContactsBackground extends AsyncTask<String ,Integer,Void>{
ProgressDialog dialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
dialog = ProgressDialog.show(MainActivity.this, "", "Loading . . .", true);
}
#Override
protected Void doInBackground(String... params) {
System.out.println("=======one========");
contacts = new ArrayList<Contact>();
// Obtain contacts
getContacts();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
dialog.dismiss();
customAdapter = new CustomAdapter();
listView.setAdapter(customAdapter);
customAdapter.notifyDataSetChanged();
}
}
#SuppressLint("InlinedApi")
private void getContacts() {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(Data.CONTENT_URI, new String[] { Data.CONTACT_ID, Data.MIMETYPE, Email.ADDRESS,
Contacts.DISPLAY_NAME, Phone.NUMBER,Contacts.Photo.PHOTO }, null, null, Contacts.DISPLAY_NAME);
Contact contact;
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
System.out.println("workout"+cur.getCount());
String id = cur.getString(cur.getColumnIndex(Data.CONTACT_ID));
System.out.println("idddddddddd"+id);
String mimeType = cur.getString(cur.getColumnIndex(Data.MIMETYPE));
if (allContacts.containsKey(id)) {
// update contact
contact = allContacts.get(id);
} else {
contact = new Contact();
allContacts.put(id, contact);
// set photoUri
//contact.setContactPhotoUri(getContactPhotoUri(Long.parseLong(id)));
}
if (mimeType.equals(StructuredName.CONTENT_ITEM_TYPE))
// set name
contact.setContactName(cur.getString(cur.getColumnIndex(Contacts.DISPLAY_NAME)));
if (mimeType.equals(Phone.CONTENT_ITEM_TYPE))
// set phone munber
contact.setContactNumber(cur.getString(cur.getColumnIndex(Phone.NUMBER)));
}
}
cur.close();
// get contacts from hashmap
contacts.clear();
contacts.addAll(allContacts.values());
// remove slef contact
for (Contact _contact : contacts) {
if (!(_contact.getContactNumber() == null))
{
nameList.add(_contact.getContactName());
numberList.add(_contact.getContactNumber());
}
}
}
static class ViewHolder{
protected TextView userNameText;
protected TextView numberText;
//protected CheckBox check;
}
public class CustomAdapter extends BaseAdapter{
#Override
public int getCount() {
// TODO Auto-generated method stub
return nameList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return nameList.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
ViewHolder holder;
holder=new ViewHolder();
LayoutInflater inflater = MainActivity.this.getLayoutInflater();
convertView =inflater.inflate(R.layout.contact_list, null);
holder.userNameText = (TextView) convertView.findViewById(R.id.nameID);
holder.numberText = (TextView) convertView.findViewById(R.id.numberID);
// holder.check = (CheckBox) convertView.findViewById(R.id.checkboxID);
holder.userNameText.setText(" "+nameList.get(position).toString());
holder.numberText.setText(" "+numberList.get(position).toString());
/* for(int i=0;i<selectedNumberList.size();i++){
if(numberList.get(position).toString().equals(selectedNumberList.get(i).toString())){
holder.check.setChecked(true);
}
}*/
// holder.check.setOnCheckedChangeListener(new CheckedChangeListner());
convertView.setTag(holder);
// holder.check.setTag(position);
return convertView;
}
}
/* class CheckedChangeListner implements OnCheckedChangeListener{
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
int pos = (Integer) buttonView.getTag();
if(isChecked){
selectedNumberList.add(numberList.get(pos).toString());
selectedNameList.add(nameList.get(pos).toString());
System.out.println("======"+nameList.get(pos).toString()+" added");
}
else
{
selectedNumberList.remove(numberList.get(pos).toString());
selectedNameList.remove(nameList.get(pos).toString());
System.out.println("======"+nameList.get(pos).toString()+" removed");
}
}
}*/
}

android match contact from contactlist

I have try this code..it is working fine..
public class Test extends Activity implements OnItemClickListener{
List<String> name1 = new ArrayList<String>();
List<String> name2 = new ArrayList<String>();
List<String> phno1 = new ArrayList<String>();
List<String> matchedList;
MyAdapter ma ;
Button select;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name2.add("Abc");
name2.add("Xyz");
name2.add("Pqr");
name2.add("aaa");
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);
}
#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, null);
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println(".................."+phoneNumber);
name1.add(name);
phno1.add(phoneNumber);
}
phones.close();
}
class MyAdapter extends BaseAdapter
{
LayoutInflater mInflater;
TextView tv1,tv;
MyAdapter()
{
// mCheckStates = new SparseBooleanArray(name1.size());
mInflater = (LayoutInflater)Test.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_list, null);
TextView tv= (TextView) vi.findViewById(R.id.txt_name);
tv1= (TextView) vi.findViewById(R.id.txt_phoneNo);
tv.setText("Name :"+ name1.get(position));
// tv1.setText("Phone No :"+ phno1.get(position));
return vi;
}
}
}
Now in ArrayList name1 I am having list of all name of my device..
and in name2 i am having Arraylist of some selcected person..Now i want to match both of this array list and display name in list that is present....
I am working on this since last week..stuck here .. Please help me...
Thanks ...:)
Don't panic, just match both list and take one temp arraylist and when any name match then add in that temp arraylist and then show that list view according to that temp arraylist. :)
Here I give you code and hint:
ArrayList<String> matchname = new ArrayList<String>();
for(int k =0;k<name1;k++)
{
for(int l =0;l<name2.size();l++)
{
String keyname = name1[k];
if((keyname.trim().equals(name2[l].trim())))
{
matchname.add(keyname);
}
}
}

selecting multiple contacts using checkbox

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

Categories

Resources