how to put progress bar in starting of a new activity - android

i Have two activities A and B. i used intent to jump from A to B. now in B.
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.list_main);
LoadData();
}
now in LoadData(), i have to load a lot of data, wo i want that when it B starts, it show a Progress bar and after loading the data, it jumps back to my activity B. how can I do this???
here is my load function
public void LoadData(Context context)
{
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '"
+ ("1") + "'";
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC";
ContentResolver cr = getContentResolver();
// ContactsContract.Contacts.
// Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
// null, null, ContactsContract.Contacts.DISPLAY_NAME);
// Find the ListView resource.
Cursor cur;
cur = context.getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI,
null,
selection + " AND "
+ ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1",
null, sortOrder);
mainListView = (ListView) findViewById(R.id.mainListView);
// When item is tapped, toggle checked properties of CheckBox and
// Planet.
mainListView
.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View item,
int position, long id)
{
ContactsList planet = listAdapter.getItem(position);
planet.toggleChecked();
PlanetViewHolder viewHolder = (PlanetViewHolder) item
.getTag();
viewHolder.getCheckBox().setChecked(planet.isChecked());
}
});
// Create and populate planets.
planets = (ContactsList[]) getLastNonConfigurationInstance();
// planets = new Planet[10];
// planets.Add("asdf");
ArrayList<ContactsList> planetList = new ArrayList<ContactsList>();
String phoneNumber = null;
String phoneType = null;
count = cur.getCount();
contacts = new ContactsList[count];
if (planets == null)
{
if (cur.getCount() > 0)
{
planets = new ContactsList[cur.getCount()];
int i = 0;
//
while (cur.moveToNext())
{
String id = cur.getString(cur
.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur
.getString(cur
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer
.parseInt(cur.getString(cur
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
// Query phone here. Covered next
Cursor pCur = cr
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[]
{ id }, null);
// WHILE WE HAVE CURSOR GET THE PHONE NUMERS
while (pCur.moveToNext())
{
// Do something with phones
phoneNumber = pCur
.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA));
phoneType = pCur
.getString(pCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
Log.i("Pratik", name + "'s PHONE :" + phoneNumber);
Log.i("Pratik", "PHONE TYPE :" + phoneType);
}
pCur.close();
}
if (phoneNumber != null
&& !planetList.contains(new ContactsList(name,
phoneNumber)))
{
planets = new ContactsList[]
{ new ContactsList(name, phoneNumber) };
contacts[i] = planets[0];
planetList.addAll(Arrays.asList(planets));
}
phoneNumber = null;
i++;
}
}
// for (int i = 0; i < count; i++)
// {
// Log.d("New Selected Names : ", contacts[i].getName());
// }
}
// Set our custom array adapter as the ListView's adapter.
listAdapter = new PlanetArrayAdapter(this, planetList);
mainListView.setAdapter(listAdapter);
Adapter adptr;
adptr = mainListView.getAdapter();
}

Please try this
//////////////////////////////////////////////////////////////////
Edit Check It
public class LoadData extends AsyncTask<Void, Void, Void> {
ProgressDialog progressDialog;
//declare other objects as per your need
#Override
protected void onPreExecute()
{
progressDialog= new ProgressDialog(YourActivity.this);
progressDialog.setTitle("Please Wait..");
progressDialog.setMessage("Loading");
progressDialog.setCancelable(false);
progressDialog.show();
//do initialization of required objects objects here
};
#Override
protected Void doInBackground(Void... params)
{
LoadData();
//do loading operation here
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
progressDialog.dismiss();
};
}
You can call this using
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.list_main);
LoadData task = new LoadData();
task.execute();
}
for more help read android document
http://developer.android.com/reference/android/os/AsyncTask.html

I am agree with Kanaiya's answer because upto the API level-10 it is fine to call long running tasks on UI thread. But from API-11, any task that takes longer time (nearly more than 5 sec) to complete must be done on background thread. The reason behind this is any task that takes 5 seconds or more on UI thread then ANR(Application Not Responding) i.e. force close happens. To do that we have create some background thread or simply make use of AsyncTask.

You just need to call your LoadData() method in another thread.
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.list_main);
mDailog = ProgressDialog.show(ActivityA.this, "",
"Loading data....!!!", true);
mDailog.show();
new Thread() {
#Override
public void run() {
try {
LoadData();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}.start();
}
Inside your LoadData(), at the end of the method use a handler to send a message to dismiss the progress bar dialog.
Hope this will help you to avoid the complex logic using AsyncTask.

Try this.
public class BActivtiy extends Activity implements Runnable{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.list_main);
mainListView = (ListView) findViewById(R.id.mainListView);
mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View item, int position, long id) {
ContactsList planet = listAdapter.getItem(position);
planet.toggleChecked();
PlanetViewHolder viewHolder = (PlanetViewHolder) item.getTag();
viewHolder.getCheckBox().setChecked(planet.isChecked());
}
});
pd = ProgressDialog.show(BActivity.this, "Title", "Description", true);
Thread t = new Thread(BActivity.this);
t.start();
}
public void LoadData() {
String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '" + ("1") + "'";
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
ContentResolver cr = getContentResolver();
Cursor cur;
cur = this.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, selection + " AND " + ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1", null, sortOrder);
// Create and populate planets.
planets = (ContactsList[]) getLastNonConfigurationInstance();
// planets = new Planet[10];
// planets.Add("asdf");
ArrayList<ContactsList> planetList = new ArrayList<ContactsList>();
String phoneNumber = null;
String phoneType = null;
count = cur.getCount();
contacts = new ContactsList[count];
if (planets == null) {
if (cur.getCount() > 0) {
planets = new ContactsList[cur.getCount()];
int i = 0;
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
// Query phone here. Covered next
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id }, null);
// WHILE WE HAVE CURSOR GET THE PHONE NUMERS
while (pCur.moveToNext()) {
// Do something with phones
phoneNumber = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA));
phoneType = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
Log.i("Pratik", name + "'s PHONE :" + phoneNumber);
Log.i("Pratik", "PHONE TYPE :" + phoneType);
}
pCur.close();
}
if (phoneNumber != null && !planetList.contains(new ContactsList(name, phoneNumber))) {
planets = new ContactsList[] { new ContactsList(name, phoneNumber) };
contacts[i] = planets[0];
planetList.addAll(Arrays.asList(planets));
}
phoneNumber = null;
i++;
}
}
// for (int i = 0; i < count; i++)
// {
// Log.d("New Selected Names : ", contacts[i].getName());
// }
}
}
#Override
public void run() {
LoadData();
mHandler.sendEmptyMessage(0);
}
public Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
pd.dismiss();
listAdapter = new PlanetArrayAdapter(BActivtiy.this, planetList);
mainListView.setAdapter(listAdapter);
Adapter adptr;
adptr = mainListView.getAdapter();
}
};
}

Related

select all checkboxes using button in android

i am creating listview with checkbox of contact list, i have one button to select all checkboxes of contact listview. and when i set the for (int i = 0; i < 5 ; i++ ) it will select 6 checkboxes and working fine ..but when set lv.getcount(); its showing error....i think its show only getview set value.....because i also use the getview in adapter....how can i solve this problem please suggest me....??
public class Contacts extends Activity implements CompoundButton.OnCheckedChangeListener{
String name, phoneNo;
List<ContactItem> contectItem;
ArrayList<String> valuesList = new ArrayList<String>();
ListView lv;
CompoundButton b1;
String[] sender = null;
boolean flag = true;
int i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
lv = (ListView) findViewById(R.id.contactList);
lv.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
method();
}
public void method() {
// ProgressDialog pd = new ProgressDialog(Contacts.this);
// pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//pd.setTitle("Please wait");
// pd.setMessage("Loading Contacts...");
// pd.show();
contectItem = new ArrayList<ContactItem>();
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, ContactsContract.Contacts.HAS_PHONE_NUMBER + "= 1", null, "UPPER(" + ContactsContract.Contacts.DISPLAY_NAME + ")ASC");
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query
(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? ",
new String[]{id}, null);
while (pCur.moveToNext()) {
int i = 0;
phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//Toast.makeText(Contacts.this, "Name: " + name + ", Phone No: " + phoneNo, Toast.LENGTH_LONG).show();
ContactItem item = new ContactItem(phoneNo, name);
contectItem.add(item);
}
pCur.close();
contactAdpter adpter = new contactAdpter(this, R.layout.contact_list, contectItem);
lv.setAdapter(adpter);
}
}
}
// pd.dismiss();
}
public void back (View v) {
super.onBackPressed();
finish();
}
public void select_all (View v) {
if (lv.getCount() > 0) {
for (int i = 0; i <lv.getCount(); i++ ) {
View view = lv.getChildAt(i);
CheckBox chk = (CheckBox)view.findViewById(R.id.checkbox1);
chk.setChecked(true);
}
}
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int pos = lv.getPositionForView(buttonView);
if (pos != ListView.INVALID_POSITION) {
ContactItem p = contectItem.get(pos);
p.setSelected(isChecked);
if (isChecked) {
if (p.isSelected()) {
valuesList.add(p.getNumber());
}
} else {
valuesList.remove(p.getNumber());
}
}
}
Try to use "lv.getAdapter().getCount()" instade of "lv.getCount()" in select_all method for get count of listview items.
try this way
to get the child of listview
for (int i = 0; i < listView.getAdapter().getCount(); i++) {
View view = listView.getChildAt(i);
}

how to remove duplicate contacts from arraylist

I have created an app in which I am getting the contacts from a device.
But I want to remove the duplicate contacts from the results.
How could I do it?
MainActivity
public class MainActivity extends Activity implements OnItemClickListener {
EditText searchText;
ArrayList<String> phno0 = new ArrayList<String>();
List<String> arrayListNames;
public List<ProfileBean> list;
public SearchableAdapter adapter;
//ProfileBean bean;
String[] cellArray = null;
String contacts;
ListView lv;
String phoneNumber, name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = getActionBar();
lv = (ListView) findViewById(R.id.listview);
list = new ArrayList<ProfileBean>();
getAllCallLogs(this.getContentResolver());
adapter = new SearchableAdapter(getApplication(), list);
lv.setAdapter(adapter);
lv.setItemsCanFocus(false);
lv.setOnItemClickListener(this);
lv.setTextFilterEnabled(true);
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
}
public void getAllCallLogs(ContentResolver cr) {
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));
list.add(new ProfileBean(name, phoneNumber));
}
phones.close();
}
}
If you want to get rid of duplicates, consider using a HashSet instead.
If you can't/don't want to use it, simply check before adding whether the contact is already there.
if (!myList.contains(newContact))
myList.add(newContact);
Add the following checking in the place of list.add(new ProfileBean(name, phoneNumber)); before adding into list:
int flag = 0
if(list.size() == 0){
list.add(new ProfileBean(name, phoneNumber));
}
for(int i=0;i<list.size();i++){
if(!list.get(i).getProfileName().trim().equals(name)){
flag = 1;
}else{
flag =0;
break;
}
}
if(flag == 1){
list.add(new ProfileBean(name, phoneNumber));
}
The following function can be used for removing duplicates from String ArrayList Change it according to your requirement
public ArrayList<String> listWithoutDuplicates(ArrayList<String> duplicateList) {
// Converting ArrayList to HashSet to remove duplicates
LinkedHashSet<String> listToSet = new LinkedHashSet<String>(duplicateList);
// Creating Arraylist without duplicate values
ArrayList<String> listWithoutDuplicates = new ArrayList<String>(listToSet);
return listWithoutDuplicates;
}
use below code list=removeDuplicates(list);
public List<ProfileBean> removeDuplicates(List<ProfileBean> list) {
// Set set1 = new LinkedHashSet(list);
Set set = new TreeSet(new Comparator() {
#Override
public int compare(Object o1, Object o2) {
if (((ProfileBean) o1).getName().equalsIgnoreCase(((ProfileBean) o2).getName()) &&
((ProfileBean)o1).getPhoneNumber().equalsIgnoreCase(((ProfileBean)o2).getPhoneNumber())) {
return 0;
}
return 1;
}
});
set.addAll(list);
final List newList = new ArrayList(set);
return newList;
}
Try to get ContactsContract.Contacts.NAME_RAW_CONTACT_ID) its unique id and its used for update contacts compare your contacts with raw id is same or not as below
private void getAllContactsBackground() {
ContentResolver contentResolver = getActivity().getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
if (cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
Cursor cursorInfo = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
InputStream inputStream = ContactsContract.Contacts.openContactPhotoInputStream(getActivity().getContentResolver(),
ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(id)));
Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, new Long(id));
Uri pURI = Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
Bitmap photo = null;
if (inputStream != null) {
photo = BitmapFactory.decodeStream(inputStream);
}
while (cursorInfo.moveToNext()) {
ContactsModel info = new ContactsModel();
info.contacts_id = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts._ID));
info.contacts_raw_id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.NAME_RAW_CONTACT_ID));
info.contacts_name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
info.contacts_mobile = cursorInfo.getString(cursorInfo.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)).replaceFirst("[^0-9]" + "91", "");
info.contacts_photo = photo;
info.contacts_photoURI = String.valueOf(pURI);
Cursor emailCur = contentResolver.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
while (emailCur.moveToNext()) {
info.contacts_email = emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
Log.e("email==>", "" + info.contacts_email);
}
emailCur.close();
int flag = 0;
if (arrayListAllContacts.size() == 0) {
arrayListAllContacts.add(info);
}
for (int i = 0; i < arrayListAllContacts.size(); i++) {
if (!arrayListAllContacts.get(i).getContacts_raw_id().trim().equals(info.contacts_raw_id)) {
flag = 1;
} else {
flag = 0;
break;
}
}
if (flag == 1) {
arrayListAllContacts.add(info);
}
}
cursorInfo.close();
}
}
cursor.close();
}
}

get details of contact selected from list view

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

Show Contacts on ListView Android

I want to get conctacts on a listView and I want too reutilitzate one code of SocialAuth.
In this code i can get ContactList on the LogCat but not in the listView and I don't know how to do this. This listView is on other XML.
I'm goggling and more but I don't Know how to adapt the code
public void Events(String provider) {
setContentView(R.layout.contact_list);
List < Contact > contactsList = adapter.getContactList();
if (contactsList != null && contactsList.size() > 0) {
for (Contact p: contactsList) {
if (TextUtils.isEmpty(p.getFirstName()) && TextUtils.isEmpty(p.getLastName())) {
p.setFirstName(p.getDisplayName());
}
Log.d("Custom-UI", "Display Name = " + p.getDisplayName());
String ContactNAme = p.getDisplayName();
//ContactName = new String[] {p.getDisplayName()};
//mapTo = new int[] {android.R.id.text1};
Log.d("Custom-UI", "First Name = " + p.getFirstName());
String ContactFisrtName = p.getFirstName();
Log.d("Custom-UI", "Last Name = " + p.getLastName());
String ContactLastName = p.getLastName();
Log.d("Custom-UI", "Contact ID = " + p.getId());
String ContactId = p.getId();
Log.d("Custom-UI", "Profile URL = " + p.getProfileUrl());
String ContactProfileUrl = p.getProfileUrl();
}
// Log.d("ContactList",mAdapter.toString());
}
Toast.makeText(CustomUI.this, "View Logcat for Contacts Information", Toast.LENGTH_SHORT).show();
}
I think that the problem is the cursor because I don't have anyone, I have this function that I think that works likes cursor
public List<Contact> getContactList()
{
try
{
contactsList = new contactTask().execute().get();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
catch (ExecutionException e)
{
e.printStackTrace();
}
return contactsList;
}
So if someone can help me please, Thanks so much.
Please have a look at the below link
http://developer.android.com/tools/samples/index.html
This is having the sample example in Android SDK. where you can get the desired result.
You need to write a custom adapter for you list view.
here is a good example
http://android.vexedlogic.com/2011/04/02/android-lists-listactivity-and-listview-ii-%E2%80%93-custom-adapter-and-list-item-view/
// Call contact thread
contact_thread = new Contact_thread();
contact_thread.start();
private Cursor getContacts() {
// Run query
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String[] projection = new String[] { ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME };
String[] selectionArgs = null;
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC";
return managedQuery(uri, projection, null, selectionArgs, sortOrder);
}
class Contact_thread extends Thread {
#Override
public void run() {
// TODO Auto-generated method stub
// Build adapter with contact entries
Cursor cursor = getContacts();
cursor.moveToFirst();
contactName = new String[cursor.getCount()];
contactNo = new String[cursor.getCount()];
checkedPosition = new boolean[cursor.getCount()];
ContentResolver contect_resolver = getContentResolver();
int i = 0;
if (cursor.getCount() > 0) {
do {
String id = cursor
.getString(cursor
.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
Cursor phoneCur = contect_resolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[] { id }, null);
if (phoneCur.moveToFirst()) {
contactName[i] = phoneCur
.getString(phoneCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
contactNo[i] = phoneCur
.getString(phoneCur
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (contactName[i] == null) {
contactName[i] = "Unknown";
}
} else {
contactName[i] = "Unknown";
contactNo[i] = "";
}
db.AddContact(contactName[i], contactNo[i]);
i++;
phoneCur.close();
} while (cursor.moveToNext());
}
cursor.close();
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
// mContactList.setAdapter(cursorAdapter);
mContactList.setAdapter(new ContactAdapter(
ContactManager.this, R.layout.contact_entry));
}
});
}
}
private class ContactAdapter extends ArrayAdapter<String> implements
Filterable {
public ContactAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
// TODO Auto-generated constructor stub
}
public int getCount() {
return contactName.length;
}
public String getItem(int position) {
return contactName[position];
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v;
if (convertView == null) {
LayoutInflater li = getLayoutInflater();
v = li.inflate(R.layout.contact_entry, null);
} else {
v = convertView;
}
CheckedTextView text = (CheckedTextView) v.findViewById(R.id.text1);
text.setText(contactName[position] + " (" + contactNo[position]
+ ") ");
text.setChecked(checkedPosition[position]);
return v;
}
}
contact_entry.xml
<?xml version="1.0" encoding="utf-8"?>
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/text1"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:background="#AA0114"
android:checkMark="?android:attr/listChoiceIndicatorMultiple"
android:gravity="center_vertical"
android:paddingLeft="6dip"
android:paddingRight="6dip"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textStyle="bold" />

I want to select a number from the contact book in Android

This Code shows the List of Contact Numbers, but i want to select cell number from selected contact display name--->
Cursor cursor= managedQuery(intent.getData(), null, null, null, null);
while(cursor.moveToNext()) {
String contactId=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
System.out.println("---------ContactId---------"+contactId);
String name=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
System.out.println("---------NAME---------"+name);
String hasPhone=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
System.out.println("---------HAS Phone---------"+hasPhone);
ArrayList one= new ArrayList();
ArrayList two= new ArrayList();
// if(Boolean.parseBoolean(hasPhone)) {
Cursor phones=getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID+" = "+ contactId, null, null);
while(phones.moveToNext()) {
phoneNumber= phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println("---------Number---------"+phoneNumber);
one.add(phoneNumber);
System.out.println("---------email Address---------"+one);
} phones.close();
// }
Display Names
public class ContentProviderActivity extends Activity {
ListView lv;
Map<String, List<String>> mymap;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv = (ListView)findViewById(R.id.listContact);
mymap = new HashMap<String, List<String>>();
Uri allContacts = Uri.parse("content://contacts/people/");
Cursor mCursor = managedQuery(allContacts, null, null, null, ContactsContract.Contacts._ID + " ASC");
final String[] contacts = new String[]{ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts._ID};
int [] view = new int[]{R.id.txtName,R.id.txtID};
final SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.main, mCursor, contacts, view);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
// TODO Auto-generated method stub
//displayContacts(position+1);
int id1 = (int) adapter.getItemId(position);
Intent i = new Intent(getApplicationContext(),ShowContactNo.class);
i.putExtra("ID", id1);
startActivity(i);
}
});
}
}
ShowContactNo: TO display associated contact numbers
public class ShowContactNo extends ListActivity{
Map<String, List<String>> mymap;
String name;
List<String> Phone_No;
String select_Number;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
mymap = new HashMap<String, List<String>>();
ListView listView = getListView();
listView.setChoiceMode(ListView.CHOICE_MODE_NONE);
Intent i = getIntent();
int position = i.getIntExtra("ID", 0);
displayContacts(position);
Phone_No = new ArrayList<String>();
Phone_No = mymap.get(name);
System.out.println(Phone_No);
if(Phone_No!=null)
{
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_checked, Phone_No));
}
final String [] items = new String [] {"Make Call", "Send Text SMS"};
ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, android.R.layout.select_dialog_item,items);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Option");
builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialog, int item ) {
if (item == 0) {
Intent i = new
Intent(android.content.Intent.ACTION_CALL,
Uri.parse("tel:"+select_Number));
startActivity(i);
dialog.cancel();
} else {
Intent i = new
Intent(android.content.Intent.ACTION_SENDTO,
Uri.parse("smsto:"+select_Number));
i.putExtra("sms_body", "Krishnakant Dalal");
startActivity(i);
}
}
} );
final AlertDialog dialog = builder.create();
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
select_Number = String.valueOf(Phone_No.get(arg2));
dialog.show();
}
});
}
private void displayContacts(int position) {
if(position!=0)
{
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, ContactsContract.Contacts._ID +" = ?",
new String[]{String.valueOf(position)}, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(
cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id}, null);
List<String> numberlist = new ArrayList<String>();
while (pCur.moveToNext()) {
String phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
// Toast.makeText(this, "Name: " + name + ", Phone No: " + phoneNo, Toast.LENGTH_SHORT).show();
numberlist.add(phoneNo);
}
pCur.close();
mymap.put(name, numberlist);
}
}
}
}
}
}
Dont forget to add Permissions:
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.CALL_PHONE" />
Try this,
public void getPhoneNumber(String conatctname)
{
try
{
ContentResolver cr =getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext())
{
FirstName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
if(FirstName!=null)
{
try
{
String[] splitval=FirstName.split(" ");
if(splitval.length>=1)
{
FirstName=splitval[0];
if(FirstName.equals(conatctname))
{
if(Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",new String[]{id}, null);
while (pCur.moveToNext())
{
PhoneNumber = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
PhoneNumberArray.add(PhoneNumber);
}
pCur.close();
}
}
}
catch(Exception error)
{
Log.d("SplitError", error.getMessage());
}
}
cursor.close();
}
catch (NumberFormatException e)
{
e.printStackTrace();
}
}

Categories

Resources