I'm just begining on Android and Java in general and Im trying to write an app that allows you to select your some of your contacts, grabbing their Name and main number and putting them into seperate list arrays. I'm not sure how to go about doing that so I've only added it in manually where you must type each persons name and number.
List<String> phnnumbers = new ArrayList<String>();
List<String> names = new ArrayList<String>();
TextView quantityTextView = (TextView) findViewById(R.id.numbersview);
// Defines the box where we will grab the numbers
EditText addnumberfieldbox = (EditText) findViewById(R.id.addnumberfield);
EditText nameboxtext = (EditText) findViewById(R.id.namebox);
// Grabs the box's contents and puts it into useable data
Editable numberfieldEditable = addnumberfieldbox.getText();
Editable nameboxEditable = nameboxtext.getText();
// Finally uses the data from the box, and puts it in
String numberfieldString = numberfieldEditable.toString();
String nameboxString = nameboxEditable.toString();
names.add(nameboxString);
phnnumbers.add(numberfieldString);
That's the method I'm using to get the text and put it into arrays.
To access the contact list of your phone you need to follow these steps :
Step 1 : Add permission to access contacts in your manifest.xml file
<uses-permission android:name="android.permission.READ_CONTACTS"/>
Step 2 : Use the following code to fetch name and phone number and then store them to ArrayList.
ArrayList<JSONObject> contacts = new ArrayList<>();
public void addContacts(){
//to store name-number pair
JSONObject obj = new JSONObject();
try {
Cursor phones = getContentResolver().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));
obj.put(name, phoneNumber);
contacts.add(obj);
Log.e("Contact list with name & numbers", " "+contacts);
}
phones.close();
}
catch (Exception e){
e.printStackTrace();
}
}
You can use the ArrayList contacts in your application code.
1 - Put the permissions on your AndroidManifest.xml:
<uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission>
<uses-permission android:name="android.permission.WRITE_CONTACTS"></uses-permission>
<application
android:theme="#style/AppTheme" > ...
2 - import ContactsContract
import android.provider.ContactsContract;
3 - Populate a cursor with phone contacts:
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
4 - Populate ArrayLists
List<String> phnnumbers = new ArrayList<String>();
List<String> names = new ArrayList<String>();
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
String phoneNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
names.add(name);
phnnumbers.add(phoneNumber);
}
}
Related
i have a huge problem with duplicated contacts.
After sorting array with:
Collections.sort(mAllContacts);
I'm reading contacts with :
ContentResolver cr = mContext.getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if ((cur != null ? cur.getCount() : 0) > 0) {
while (cur != null && cur.moveToNext()) {
String id = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
if (cur.getInt(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()) {
String phoneNo = pCur.getString(pCur.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
contacts = new AllContacts(name, phoneNo);
mAllContacts.add(contacts);
}
pCur.close();
}
}
}
if (cur != null) {
cur.close();
}
With this way, all contact are retrieved to a list (Local storage, Sim, Gmail etc).
I have no problem to remove duplicated contact by name like this:
for (int i = 0; i < mAllContacts.size() - 1; i++) {
if (mAllContacts.get(i).getmContactName().equals(mAllContacts.get(i + 1).getmContactName())) {
Log.d("duplicatedArray", "setAdapter: " + mAllContacts.get(i).getmContactName());
mAllContacts.remove(i+1);
}
}
but it's not a good practice because some times different contacts may have same name,
so i can remove duplicated contact with same method but use:
mAllContacts.get(i + 1).getmPhoneNumber()
And here is the problems comes:
For some reason , the phone number have different format while reading from gmail, local storage , sim.
For ex.
Gmail phone number : +972-54-333-55-88
Local storage phone number : +972-543335588
Sim : +972543335588
How can i solve my problem to remove duplicated values.
And yes , i need to read contact from all places where they appear (gmail, local storage , sim)
Apply regex to change the same phone numbers to a common format e.g.
class Main {
public static void main(String args[]) {
String p1 = "+972-54-333-55-88";
String p2 = "+972-543335588";
String p3 = "+972543335588";
String p4 = "+97(2543)335588";
String p5 = "+97 2543 335588";
String regex = "[^0-9+]";
System.out.println(p1.replaceAll(regex, ""));
System.out.println(p2.replaceAll(regex, ""));
System.out.println(p3.replaceAll(regex, ""));
System.out.println(p4.replaceAll(regex, ""));
System.out.println(p5.replaceAll(regex, ""));
}
}
Output:
+972543335588
+972543335588
+972543335588
+972543335588
+972543335588
Normalize
I think you should normalize these phone numbers before you store them.
So for example all of these:
Gmail phone number : +972-54-333-55-88
Local storage phone number : +972-543335588
Sim : +97254335588
Could just be stored as 97254335588 You can parse these numbers by removing all space, hyphens, and plus signs.
HashSet
It would also be easier to store these in a HashSet so you don't even need to worry about removing duplicates.
Is there a way of determining the number of total messages in our device.
I've tried the following for finding the number of calls:
Uri allCalls = Uri.parse("content://call_log/calls");
Cursor c = managedQuery(allCalls, null, null, null, null);
count= c.getCount();
Log.i("TAG",Integer.toString(count));
But I'm not able to view any number when i tried this similar to messages in my logcat.
Try this code to get all Messages
public List<String> getSMS(){
List<String> sms = new ArrayList<String>();
Uri uriSMSURI = Uri.parse("content://sms/inbox");
Cursor cur = getContentResolver().query(uriSMSURI, null, null, null, null);
while (cur != null && cur.moveToNext()) {
String address = cur.getString(cur.getColumnIndex("address"));
String body = cur.getString(cur.getColumnIndexOrThrow("body"));
sms.add("Number: " + address + " .Message: " + body);
}
if (cur != null) {
cur.close();
}
return sms;
}
Just Call the method and you will receive an ArrayList of all messages
Get List of Messages in Inbox Like Below:
First Add Permission in Manifest.xml to read sms:
<uses-permission android:name="android.permission.READ_SMS"></uses-permission>
public ArrayList<String> fetchInbox()
{
ArrayList<String> sms = new ArrayList();
//Read Draft message only by "content://sms/draft"
//Read Sent message only by "content://sms/sent"
Uri uriSms = Uri.parse("content://sms/inbox");
Cursor cursor = getContentResolver().query(uriSms, new String[]{"_id", "address", "date", "body"},null,null,null);
cursor.moveToFirst();
while (cursor.moveToNext())
{
String address = cursor.getString(1);
String body = cursor.getString(3);
sms.add(body);
}
return sms;
}
And You can get SMS count by sms.size();
I am trying to access all of the WeChat contacts in my Android app and open Chat page with the contact on WeChat if the user taps on it. I read the official documentation from Here but it didn't help. I couldn't find any helpful answers anywhere else either. In my code, I am filtering contacts by MIME Type but I am getting an empty string every time. Please help me solve it...
//MIMETYPE of WeCha
String mimeString = "vnd.android.cursor.item/vnd.com.tencent.mm.chatting.voip.video";
String displayName = null;
String phone = null;
Long _id;
ContentResolver resolver = getApplicationContext().getContentResolver();
//Sorting contacts Alphabetically
Cursor cursor = resolver.query(ContactsContract.Data.CONTENT_URI, null, null, null, ContactsContract.Contacts.DISPLAY_NAME);
while (cursor.moveToNext()) {
_id = cursor.getLong(cursor.getColumnIndex(ContactsContract.Data._ID));
phone = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
//Getting the MimeType of user
String mimeType = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.MIMETYPE));
If(mimeType==mimeString)
{
//Logs for debugging
Log.d("Look here", _id.toString());
Log.d("Look here", displayName);
Log.d("Look here", mimeType);
}
}
cursor.close();
I created a small activity that displays all contacts with phone numbers in my phone. However, there are duplicates for contacts that have whatsapp installed. For example, if John is in my contact list and he has a whatsapp account as well, the list would look like this:
...
Jake
John
John
JP
...
This is my code for assigning the cursor to the the adapter which links to a listview.
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String sortOrder = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC";
final Cursor cursor = getContentResolver().query(uri, null, null, null, sortOrder);
String[] from = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone._ID};
int[] to = {android.R.id.text1};
adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_multiple_choice, cursor, from, to, 0);
EDIT
With this code, I confirmed that the duplicates have 0 value for the ContactsContract.CommonDataKinds.Phone.TYPE which means it is a custom contact (Whatsapp). The rest are 2 which means it is a normal contact.
I need to figure out a query where it doesn't use any contacts where ContactsContract.CommonDataKinds.Phone.TYPE == 0
I know it might be a bit late. However I was having the same issue.
ContactsContract.CommonDataKinds.Phone.TYPE as per the android documentation refers not to whether it is a custom contact but to what type of contact it is i.e. Mobile(2), Home(1) or Work(3). Whatsapp contacts will be a 2 - mobile.
I used the following function to remove the duplicates (not sure if there is a better way):
private boolean checkDuplicate(String position) {
LinkedHashMap<String, Integer> map;
Integer testNull;
map=new LinkedHashMap<>();
testNull=map.get(position);
if(testNull==null) {
testNull=1;
map.put(position, testNull);
return false;
}
else {
testNull=testNull+1;
if(testNull==2) {
return true;
}
else {
map.put(position, testNull);
return false;
}
}
}
I have an activity that has a listview which displays all contacts with multi-selection enabled. I have also a filter to filter the display result.
After struggling with this problem for 3 days, I finally could produce a list of all display names selected by the user.
My question now is how to get the corresponding email and phone number for each display name in my list?
Update:
I found a solution..
public String getNumber(String name,Context context){
String number="";
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String[] projection = new String[] {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER};
Cursor people = context.getContentResolver().query(uri, projection, null, null, null);
int indexName = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int indexNumber = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
people.moveToFirst();
do {
String Name = people.getString(indexName);
String Number = people.getString(indexNumber);
if(Name.equalsIgnoreCase(name)){return Number.replace("-", "");}
// Do work...
} while (people.moveToNext());
if(!number.equalsIgnoreCase("")){return number.replace("-", "");}
else return number;
}
public String getEmail(String name,Context context){
String email="";
Uri uri = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
String[] projection = new String[] {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Email.DATA};
Cursor people = context.getContentResolver().query(uri, projection, null, null, null);
int indexName = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int indexNumber = people.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA);
people.moveToFirst();
do {
String Name = people.getString(indexName);
String mail = people.getString(indexNumber);
if(Name.equalsIgnoreCase(name)){return mail;}
// Do work...
} while (people.moveToNext());
if(!email.equalsIgnoreCase("")){return email;}
else return email;
}
Got it from there:
Android get contact number using name