android match contact from contactlist - android

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

Related

Retrieving mobile contacts are displaying twice in the application

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

How to get the value of clicked list item

I just want to get the value of clicked list item,
i.e if list contains apple,ball,cat, then clicked on apple then it gives value as apple, ,In the below code I am using inner class base adapter to display the data.
public class RecordsActivity extends Activity implements
OnItemClickListener
{
ListView listProduct;
ListAdapter adapter;
TextView UserName,Date;
ArrayList<String> billDate = new ArrayList<String>();
ArrayList<String> billNo = new ArrayList<String>();
ArrayList<String >partyName=new ArrayList<String>();
ArrayList<String> billAmount = new ArrayList<String>();
ArrayList<String >receipt=new ArrayList<String>();
ArrayList<String >balance=new ArrayList<String>();
ArrayList<String> week = new ArrayList<String>();
ArrayList<String> amount = new ArrayList<String>();
String get_name,get_date,Name;
String GetAmnt;
Dialog dialog;
AlertDialog alertDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_records);
UserName=(TextView) findViewById(R.id.txt_disuser);
Intent usr=getIntent();
get_name=usr.getStringExtra("user");
UserName.setText(get_name);
Date=(TextView) findViewById(R.id.txt_disdate);
Intent dt=getIntent();
get_date=dt.getStringExtra("date");
Date.setText(get_date);
Intent id =getIntent();
Name=id.getStringExtra("name");
listProduct=(ListView) findViewById(R.id.ListViewFilledRecrd);
listProduct.setAdapter(adapter);
/*listProduct.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3)
{
listProduct.setClickable(true);
String data = (String)listProduct.getItemAtPosition(arg2);
Toast.makeText(getApplicationContext(),data,
Toast.LENGTH_SHORT).show();
}
});*/
}
protected void onResume()
{
getAllProduct();
super.onResume();
}
public void getAllProduct(){
SQLiteDatabase db = this.getDB();
Cursor c;
//c=db.rawQuery("SELECT * FROM RECORDS", null);
c=db.rawQuery("SELECT * FROM RECORDS WHERE PARTY_NAME = '" + Name +
"' ", null);
String
BILL_DATE,BILL_NO,PARTY_NAME,BILL_AMOUNT,RECEIPT,BALANCE,WEEK,AMOUNT;
if(c.moveToFirst())
{
do
{
BILL_DATE = c.getString(1);
BILL_NO=c.getString(2);
PARTY_NAME=c.getString(3);
BILL_AMOUNT=c.getString(4);
RECEIPT=c.getString(5);
BALANCE=c.getString(6);
WEEK=c.getString(7);
AMOUNT=c.getString(8);
billDate.add(BILL_DATE);
billNo.add(BILL_NO);
partyName.add(PARTY_NAME);
billAmount.add(BILL_AMOUNT);
receipt.add("RECEIPT");
balance.add(BALANCE);
week.add(WEEK);
amount.add(AMOUNT);
} while (c.moveToNext());
}
DisplyRecords dsptProd=new
DisplyRecords(RecordsActivity.this,billDate,billNo,partyName,
billAmount,receipt,balance,week,amount);
listProduct.setAdapter(dsptProd);
listProduct.setOnItemClickListener(this);
c.close();
db.close();
}
private SQLiteDatabase getDB()
{
String DB_NAME = "odsr.db";
return openOrCreateDatabase(DB_NAME, SQLiteDatabase.OPEN_READWRITE,
null);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
}
}
class DisplyRecords extends BaseAdapter
{
Context c;
ArrayList<String > BILLDATE;
ArrayList<String>BILLNO;
ArrayList<String> PARTYNAME;
ArrayList<String>BILLAMOUNT;
ArrayList<String>RECEIPT;
ArrayList<String> BALANCE;
ArrayList<String>WEEK;
ArrayList<String>AMOUNT;
public DisplyRecords(RecordsActivity recordsactivity,ArrayList<String>
billDate, ArrayList<String> billNo, ArrayList<String>
partyName,ArrayList<String> billAmount, ArrayList<String> receipt,
ArrayList<String> balance, ArrayList<String> week,ArrayList<String> amount)
{
this.c=recordsactivity;
this.BILLDATE=billDate;
this.BILLNO=billNo;
this.PARTYNAME=partyName;
this.BILLAMOUNT=billAmount;
this.RECEIPT=receipt;
this.BALANCE=balance;
this.WEEK=week;
this.AMOUNT=amount;
//TODO Auto-generated constructor stub
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return BILLDATE.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int pos, View row, ViewGroup parent)
{
View child=row;
LayoutInflater layoutinflater;
if(child==null)
{
layoutinflater=(LayoutInflater)
c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutinflater.inflate(R.layout.list_product,null);
}
TextView txt_billdate=(TextView) child.findViewById(R.id.txt_bill_date);
TextView txt_billno=(TextView) child.findViewById(R.id.txt_bill_no);
TextView txt_partyname=(TextView)
child.findViewById(R.id.txt_party_name);
TextView txt_billamt=(TextView)
child.findViewById(R.id.txt_bill_amount);
TextView txt_receipt=(TextView) child.findViewById(R.id.txt_receipt);
TextView txt_balance=(TextView) child.findViewById(R.id.txt_balance);
TextView txt_wk=(TextView) child.findViewById(R.id.txt_week);
TextView txt_amount=(TextView) child.findViewById(R.id.txt_amount);
txt_billdate.setText(BILLDATE.get(pos));
txt_billno.setText(BILLNO.get(pos));
txt_partyname.setText(PARTYNAME.get(pos));
txt_billamt.setText(BILLAMOUNT.get(pos));
txt_receipt.setText(RECEIPT.get(pos));
txt_balance.setText(BALANCE.get(pos));
txt_wk.setText(WEEK.get(pos));
txt_amount.setText(AMOUNT.get(pos));
// TODO Auto-generated method stub
return child;
}
}
A few assumptions here, your actual fields do not need to be ArrayList's since each query returns a single row item from the db, i create a master object with Strings to represent the data...
So here is how i would do it, you need to re structure your data
First i would change your data to a :
public class ParentObject {
public String BILLDATE ;
public String BILLNO ;
public String PARTYNAME ;
public String BILLAMOUNT ;
public String RECEIPT ;
public String BALANCE ;
public String WEEK ;
public String AMOUNT ;
}
UPDATE
then i would change my Activity to:
public class RecordsActivity extends Activity implements OnItemClickListener{
ListView listProduct;
ListAdapter adapter;
TextView UserName,Date;
// your new parent object ArrayList, much cleaner
List<ParentObject> parentObjects;
String get_name,get_date,Name;
String GetAmnt;
Dialog dialog;
AlertDialog alertDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_records);
UserName=(TextView) findViewById(R.id.txt_disuser);
Intent usr=getIntent();
get_name=usr.getStringExtra("user");
UserName.setText(get_name);
Date=(TextView) findViewById(R.id.txt_disdate);
Intent dt=getIntent();
get_date=dt.getStringExtra("date");
Date.setText(get_date);
Intent id =getIntent();
Name=id.getStringExtra("name");
listProduct=(ListView) findViewById(R.id.ListViewFilledRecrd);
listProduct.setAdapter(adapter);
listProduct.setOnItemClickListener(this);
}
protected void onResume(){
getAllProduct();
super.onResume();
}
public void getAllProduct(){
SQLiteDatabase db = this.getDB();
Cursor c;
//c=db.rawQuery("SELECT * FROM RECORDS", null);
c=db.rawQuery("SELECT * FROM RECORDS WHERE PARTY_NAME = '" + Name + "' ", null);
String BILL_DATE,BILL_NO,PARTY_NAME,BILL_AMOUNT,RECEIPT,BALANCE,WEEK,AMOUNT;
if(c.moveToFirst()){
// initialize the parent arrayList
parentObjects = new ArrayList<ParentObject>();
do{
// initialize a single object
ParentObject parentObject = new ParentObject();
// fill in its data
parentObject.BILL_DATE = c.getString(1);
parentObject.BILL_NO=c.getString(2);
parentObject.PARTY_NAME=c.getString(3);
parentObject.BILL_AMOUNT=c.getString(4);
parentObject.RECEIPT=c.getString(5);
parentObject.BALANCE=c.getString(6);
parentObject.WEEK=c.getString(7);
parentObject.AMOUNT=c.getString(8);
// add it to your list
parentObjects.add(parentObject);
} while (c.moveToNext());
}
// pass the List<ParentObject> into your adapter
DisplyRecords dsptProd= new DisplyRecords(RecordsActivity.this, (ArrayList<ParentObject>)parentObjects);
listProduct.setAdapter(dsptProd);
listProduct.setOnItemClickListener(this);
c.close();
db.close();
}
private SQLiteDatabase getDB(){
String DB_NAME = "odsr.db";
return openOrCreateDatabase(DB_NAME, SQLiteDatabase.OPEN_READWRITE,
null);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
// access to all your data through the parentObject
ParentObject data = (ParentObject) listProduct.getItemAtPosition(position);
// access all fields for this parent
Toast.makeText(RecordsActivity.this, "data: "+ data.BILL_DATE, + " ," + data.BILL_NO, " , etc", Toast.LENGTH_LONG).show();
}
}
and then update your Adapter to handle the List
class DisplyRecords extends BaseAdapter {
Context c;
List<ParentObject> parentObjects;
public DisplyRecords(Context context, ArrayList<ParentObject> parentObjects){
this.c=context;
this.parentObjects = parentObjects;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return parentObjects.size();
}
#Override
public Object getItem(int position) {
return parentObjects.get(position); // always return this parent
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int pos, View row, ViewGroup parent){
// You should implement the ViewHolder pattern, this is not doing that...
View child=row;
LayoutInflater layoutinflater;
if(child==null){
layoutinflater=(LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutinflater.inflate(R.layout.list_product,null);
}
TextView txt_billdate=(TextView) child.findViewById(R.id.txt_bill_date);
TextView txt_billno=(TextView) child.findViewById(R.id.txt_bill_no);
TextView txt_partyname=(TextView) child.findViewById(R.id.txt_party_name);
TextView txt_billamt=(TextView) child.findViewById(R.id.txt_bill_amount);
TextView txt_receipt=(TextView) child.findViewById(R.id.txt_receipt);
TextView txt_balance=(TextView) child.findViewById(R.id.txt_balance);
TextView txt_wk=(TextView) child.findViewById(R.id.txt_week);
TextView txt_amount=(TextView) child.findViewById(R.id.txt_amount);
ParentObject parentObject = parentObjects.get(pos);
txt_billdate.setText(parentObject.BILLDATE);
txt_billno.setText(parentObject.BILLNO.);
txt_partyname.setText(parentObject.PARTYNAME);
txt_billamt.setText(parentObject.BILLAMOUNT);
txt_receipt.setText(parentObject.RECEIPT);
txt_balance.setText(parentObject.BALANCE);
txt_wk.setText(parentObject.WEEK);
txt_amount.setText(parentObject.AMOUNT);
// TODO Auto-generated method stub
return child;
}
}

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.

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

ListView adapter with HashMap

I have a listview with textview and checkbox. The text values are stored in a HashMap. Data is retrieved from a DB. Map key is the ID and Map value is a Location. When I pass the HashMap to the adapter, it starts printing from position 0 (zero). Because of this I get a null text(with no value) and miss one value(the last one) in the HashMap. Can't I use a HashMap as the data source?
EDIT: Here is the code
public class LocationActivity extends Activity{
myAdapter myA;
Map<Integer,String> locLables;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.locationmain);
ListView listview = (ListView) findViewById(R.id.listView1);
String selectQuery = "SELECT * FROM " + DatabaseHandler.TABLE_LOCATIONLABLES;
SQLiteDatabase db = new DatabaseHandler(this).getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
locLables = new HashMap<Integer, String>();
if(cursor != null){
if (cursor.moveToFirst()) {
do {
locLables.put(new Integer(cursor.getString(0)),cursor.getString(1));
System.out.println(cursor.getString(0)+" "+ cursor.getString(1));
} while (cursor.moveToNext());
}
}
cursor.close();db.close();
//System.out.println(locLables);
myA = new myAdapter(this, locLables, listview);
listview.setAdapter(myA);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
if(arg2 == 0 )
arg2 = arg2+1;
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), locLables.get(arg2), Toast.LENGTH_SHORT).show();
}
});
}
Here is the Adapter class
class myAdapter extends BaseAdapter{
ListView listView;
Activity cntx;
Map<Integer,String> locations;
List<Integer> locids = new LinkedList<Integer>();
public myAdapter(Activity context,Map<Integer,String> locLables, ListView lv){
cntx = context;
locations = locLables;
listView = lv;
System.out.println(locations);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return locations.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View row=null;
final int posi = position;
LayoutInflater inflater=cntx.getLayoutInflater();
row=inflater.inflate(R.layout.locationmain_entry, null);
TextView tv = (TextView)row.findViewById(R.id.textView12);
final CheckBox cb = (CheckBox)row.findViewById(R.id.checkBox12);
if(locids.contains(posi))
cb.setChecked(true);
//here I get a null value as the first element and misses the last value..
tv.setText(locations.get(position));
cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked){
System.out.println("Chedked" + posi+ locations.get(posi));
//cb.setChecked(true);
if(!locids.contains(posi))
locids.add(posi);
//System.out.println(locids.get(posi));
}else if(!isChecked){
//cb.setChecked(false);
if(locids.contains(posi))
locids.remove(new Integer(posi));
System.out.println("NOt checked" +posi + locations.get(posi));
}
}
});
return row;
}
It runs for the number of elements in the Map. As it is using a 0 (by position variable) it misses the last value as well.
What you can do is
ArrayList<Hashmap<Integer,String>> myList = new ArrayList<Hashmap<Integer,String>>();
if(cursor != null){
if (cursor.moveToFirst()) {
do {
locLables = new HashMap<Integer, String>();
locLables.put(new Integer(cursor.getString(0)),cursor.getString(1));
myList.add(locLables);
} while (cursor.moveToNext());
}
}
cursor.close();db.close();
myA = new myAdapter(this, myList, listview);
listview.setAdapter(myA);
You will have to change your "myAdapter" Adapter's constructor to hold "ArrayList> myList" instead of "Map locLables"..
This will help... Let me know if the problem still persists..

Categories

Resources