PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label contacts. Show all posts
Showing posts with label contacts. Show all posts

Sunday, November 6, 2022

[FIXED] How to add Array value to JSON Key in Swift

 November 06, 2022     contacts, json, parameters, swift, uitableview     No comments   

Issue

How to add request.httpBody = getPostData(params: ["contactsList": ["1212121212, "5555555544"]]) in place of let parameters = getPostString(params: ["contactsList":[phNumArray]])

below is working code but how to add phNumArray in palce of individual of individual numberes to contactsList

Postman output for API:

enter image description here enter image description here

working code: anyone can copy paste to see output

import UIKit
class TestViewController: UIViewController {
    var phNumArray = ["1111111111", "5555555544"]
    override func viewDidLoad() {
        super.viewDidLoad()

        callPostApi()
    }

    func getPostString(params: [String: Any]) -> String {
        var data = [String]()
        for (key, value) in params {
            data.append(key + "=\(value)")
        }
        print(data.map { String($0) }.joined(separator: "&"))
        return data.map { String($0) }.joined(separator: "&")
    }

    func callPostApi() {
        let url = URL(string: "http://itaag-env-1.ap-south-1.elasticbeanstalk.com/filter/taggedusers/")
        guard let requestUrl = url else { fatalError() }
        var request = URLRequest(url: requestUrl)
        request.httpMethod = "POST"

        request.setValue("EC3746E9-4DB4-42C7-9D8C-1542B18C2AC", forHTTPHeaderField: "deviceid")
        request.setValue("5fe42fb3b54543a0bab5667cf96526f8", forHTTPHeaderField: "key")
        request.setValue("personal", forHTTPHeaderField: "userType")

        let parameters = getPostString(params: ["contactsList": ["5555555544", "11111111111"]])

        print("json parameter phone numbers \(parameters)")

        request.httpBody = parameters.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            let httpResponse = response as? HTTPURLResponse
            // Check for Error
            if let error = error {
                print("Error took place \(error)")
                return
            }
            if let data = data, let dataString = String(data: data, encoding: .utf8) {
                print("Response data string:\n \(dataString)")

                do {
                    let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String: Any]
                    print("fetching json \(json)")
                    let fetchStatus = json["userName"] as? String
                    print("fetching json userName \(String(describing: fetchStatus))")

                    let user = json["5555555544"] as? [String: Any]
                    let name = user?["userName"] as? String
                    print("first username \(name)")
                } catch {}
            }
        }
        task.resume()
    }
}

please help me to solve the issue with contactsList value.


Solution

Update: All this time you were sending the request as JSON encoded instead of as form-data. I'm adding the code for that below, try it out:

class ViewController: UIViewController {

    var phNumArray  = ["1111111111", "5555555544"]

    override func viewDidLoad() {
        super.viewDidLoad()

        callPostApi()
    }

    func getPostData(params: [String:Any]) -> Data? {
        return try? JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
    }

    func callPostApi() {

        let url            = URL(string: "http://itaag-env-1.ap-south-1.elasticbeanstalk.com/filter/taggedusers/")!
        var request        = URLRequest(url: url)
        request.httpMethod = "POST"

        request.setValue("EC3746E9-4DB4-42C7-9D8C-1542B18C2AC", forHTTPHeaderField: "deviceid")
        request.setValue("5fe42fb3b54543a0bab5667cf96526f8", forHTTPHeaderField: "key")
        request.setValue("personal", forHTTPHeaderField: "userType")

        try? request.setMultipartFormData(["contactsList": "\(phNumArray)"], encoding: .utf8)

        URLSession.shared.dataTask(with: request) { data, _, _ in
            if let data = data, let json = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {

                let user = json["5555555544"] as? [String: Any]
                let name = user?["userName"] as? String
                print("first username \(name)")
            }
        }.resume()
    }
}

extension URLRequest {

    public mutating func setMultipartFormData(_ parameters: [String: String], encoding: String.Encoding) throws {

        let makeRandom = { UInt32.random(in: (.min)...(.max)) }
        let boundary = String(format: "------------------------%08X%08X", makeRandom(), makeRandom())

        let contentType: String = try {
            guard let charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(encoding.rawValue)) else {
                throw MultipartFormDataEncodingError.characterSetName
            }
            return "multipart/form-data; charset=\(charset); boundary=\(boundary)"
        }()
        addValue(contentType, forHTTPHeaderField: "Content-Type")

        httpBody = try {
            var body = Data()

            for (rawName, rawValue) in parameters {
                if !body.isEmpty {
                    body.append("\r\n".data(using: .utf8)!)
                }

                body.append("--\(boundary)\r\n".data(using: .utf8)!)

                guard
                    rawName.canBeConverted(to: encoding),
                    let disposition = "Content-Disposition: form-data; name=\"\(rawName)\"\r\n".data(using: encoding) else {
                    throw MultipartFormDataEncodingError.name(rawName)
                }
                body.append(disposition)

                body.append("\r\n".data(using: .utf8)!)

                guard let value = rawValue.data(using: encoding) else {
                    throw MultipartFormDataEncodingError.value(rawValue, name: rawName)
                }

                body.append(value)
            }

            body.append("\r\n--\(boundary)--\r\n".data(using: .utf8)!)

            return body
        }()
    }
}

public enum MultipartFormDataEncodingError: Error {
    case characterSetName
    case name(String)
    case value(String, name: String)
}

Instead of converting to JSON String and then converting it to Data, use JSONSerialization, here's an example:

func getPostData(params:[String:Any]) -> Data? {
    return try? JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
}

And then assign it directly to URLRequest's httpBody, like this:

let arrayOfNumbers = [String]()
arrayOfNumbers.append("5555555544")
arrayOfNumbers.append("11111111111")
request.httpBody = getPostData(params: ["contactsList": arrayOfNumbers])

Also, go through the Apple Documentation, you'll find valuable information there. If don't understand concepts there google more about JSONSerializing and POST request httpBody.



Answered By - Frankenstein
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to pass all phone contacts to JSON API in swift

 November 06, 2022     contacts, json, swift     No comments   

Issue

I am able to fetch all phone contacts in a table view.

I need to pass all phone contacts in JSON URL parameter called contactsList, but I am unable to pass all phone contacts to Json parameter contactsList

If I send individual phone number like below code, it's coming

but i need to send all my phone contacts to JSON API

code: here the api and given phone numbers all are working.. here with my code you can check JSON response as well.. but i need to send all phone contacts to API

import UIKit
import Contacts
class ContactsViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

@IBOutlet weak var joinersTableView: UITableView!
var contacts = [CNContact]()
var phNumArray  = ["5555555544", "1212121212"]
var taggedStatus: String?

override func viewDidLoad() {
    super.viewDidLoad()
    joinersTableView.register(UINib(nibName: "ContactsTableViewCell", bundle: nil), forCellReuseIdentifier: "ContactsTableViewCell")
    ContactsModel.shared.getLocalContacts {(contact) in
        self.contacts.append(contact!)
    }
    joinersTableView.reloadData()

    self.callPostApi()
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return contacts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
    let cell: ContactsTableViewCell = tableView.dequeueReusableCell(withIdentifier: "ContactsTableViewCell") as! ContactsTableViewCell
    cell.nameLbl.text    = contacts[indexPath.row].givenName + " " + contacts[indexPath.row].familyName
    cell.phNUmLbl.text = contacts[indexPath.row].phoneNumbers.first?.value.stringValue
   
    return cell
    
}

    func callPostApi() {

        let url            = URL(string: "http://itaag-env-1.ap-south-1.elasticbeanstalk.com/filter/taggedusers/")!
        var request        = URLRequest(url: url)
        request.httpMethod = "POST"

        request.setValue("F139424D-C749-42F6-B804-21BD17E28CE0", forHTTPHeaderField: "deviceid")
        request.setValue("c913136e897b419bab20746de7baab62", forHTTPHeaderField: "key")
        request.setValue("personal", forHTTPHeaderField: "userType")

        try? request.setMultipartFormData(["contactsList": "\(phNumArray)"], encoding: .utf8)
       
        URLSession.shared.dataTask(with: request) { data, _, _ in
            if let data = data, let jsonObj = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
           print("contacts JSON \(jsonObj)")
                let phnDict = jsonObj as? [String : Any]
                
                print("each phone number1111111 \(phnDict)")

            }
        }.resume()
    }
    }
 extension URLRequest {

public mutating func setMultipartFormData(_ parameters: [String: String], encoding: String.Encoding) throws {

    let makeRandom = { UInt32.random(in: (.min)...(.max)) }
    let boundary = String(format: "------------------------%08X%08X", makeRandom(), makeRandom())

    let contentType: String = try {
        guard let charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(encoding.rawValue)) else {
            throw MultipartFormDataEncodingError.characterSetName
        }
        return "multipart/form-data; charset=\(charset); boundary=\(boundary)"
    }()
    addValue(contentType, forHTTPHeaderField: "Content-Type")

    httpBody = try {
        var body = Data()

        for (rawName, rawValue) in parameters {
            if !body.isEmpty {
                body.append("\r\n".data(using: .utf8)!)
            }

            body.append("--\(boundary)\r\n".data(using: .utf8)!)

            guard
                rawName.canBeConverted(to: encoding),
                let disposition = "Content-Disposition: form-data; name=\"\(rawName)\"\r\n".data(using: encoding) else {
                throw MultipartFormDataEncodingError.name(rawName)
            }
            body.append(disposition)

            body.append("\r\n".data(using: .utf8)!)

            guard let value = rawValue.data(using: encoding) else {
                throw MultipartFormDataEncodingError.value(rawValue, name: rawName)
            }

            body.append(value)
        }

        body.append("\r\n--\(boundary)--\r\n".data(using: .utf8)!)

        return body
    }()
}
}

public enum MultipartFormDataEncodingError: Error {
case characterSetName
case name(String)
case value(String, name: String)
}

EDIT: OUT PUT: here how do i get each contact userName and tagged values

contacts JSON ["(408) 555-5270": {
oniTaag = 0;
profilePic = "<null>";
tagged = 0;
userId = "<null>";
userName = "<null>";
userType = personal;
}, "555-522-8243": {
oniTaag = 0;
profilePic = "<null>";
tagged = 0;
userId = "<null>";
userName = "<null>";
userType = personal;
}, "(408) 555-3514": {
oniTaag = 0;
profilePic = "<null>";
tagged = 0;
userId = "<null>";
userName = "<null>";
userType = personal;
}, "555-478-7672": {
oniTaag = 0;
profilePic = "<null>";
tagged = 0;
userId = "<null>";
userName = "<null>";
userType = personal;
.......

Solution

To convert the contact array as an array of string you can do this

let phNumArray = contacts.flatMap { $0.phoneNumbers }.map { $0.value.stringValue }

Then you can send phNumArray as it is now.

Answer for question in the comment.
To other properties of contact, you can do something like this

for contact in contacts {
    print(contact.givenName)
    print(contact.familyName)
}

Obviously you need to use proper keys in this case CNContactGivenNameKey, CNContactFamilyNameKey during contact fetch.

You can get the list of available properties here
Look here for available keys.



Answered By - Nazmul Islam
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to Fetch and Display Name and Image of Conversation's Contact?

 November 06, 2022     android, contacts, java, listview, sms     No comments   

Issue

I want to achieve something like in screenshot below, So far I am able to display a list of most recent message with message count, But when I'm trying to get the name of person through "address", I'm getting error " Column address not found". Please help me displaying "contact name with their image".

What I Want to Achieve

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                     Bundle savedInstanceState) {        
    View view = inflater.inflate(R.layout.MyChatFragment, container, false);
    
    // Inflate the layout for this fragment
    
    ListView lv = (ListView) view.findViewById(R.id.listView2);
     
    ArrayList<String> smsList;        
    smsList = new ArrayList<>();
    ArrayAdapter<String> lva = new ArrayAdapter<String>(getActivity(), 
    android.R.layout.simple_list_item_1, smsList);        
    lv.setAdapter(lva);

    Uri inboxUri = Uri.parse("content://sms/conversations/");
    ContentResolver contentResolver = getActivity().getContentResolver();
    Cursor cursor = contentResolver.query(inboxUri, null, null, null, null);

    if (cursor.moveToFirst()) {
            while (cursor.moveToNext()) {

        String number = cursor.getString(cursor.getColumnIndexOrThrow("address"));
        String message_count = cursor.getString(cursor.getColumnIndexOrThrow("msg_count"));
        String body = cursor.getString(cursor.getColumnIndexOrThrow("snippet"));
        smsList.add("Number: " + number + "\n" + "Message: " + body + "\n" + "Number Of Messages" + 
        message_count );

            }
        }
            return view;
     }

Solution

Conversations uri doesn't contain a column like "address". You can simply look all columns in specific uri via looping cursor.getColumnName(index) and print it to logcat. List of columns into specific uri you can also find in docs.
Basicly, Sms ContentProvider doesn't contain informations about contacts, so you need make a second query to ContactsContract uri, and find a specific contact via his phone number. Depending of data that you need, there are many uris. You can simply link a phone number from sms with a specific contact using ContactsContract.PhoneLookup.CONTENT_FILTER_URI. More detailed information about contacts are in sub-uris of ContactsContract ContentProvider. Description about all of them you will find in docs.
Below is simple example. Contact photos isn't stored like photos, but only like a uri to the photo, so you must fetch an image via uri. I didn't test that code too long, so I can't tell you, how it will work e.g. when you have a few contacts with same number.

if (cursor.moveToFirst()) {
        while (cursor.moveToNext()) {
            String number = cursor.getString(cursor.getColumnIndexOrThrow("address"));
            String thread_id = cursor.getString(cursor.getColumnIndexOrThrow("thread_id"));
            String body = cursor.getString(cursor.getColumnIndexOrThrow("body"));
            String name = "";
            String photoUri = "";

            if (number != null) {
                Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, number);
                String[] projection = new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup.PHOTO_URI};
                Cursor contactCursor = getContentResolver().query(uri, projection, null, null, null);
                if (contactCursor != null && contactCursor.getCount() > 0) {
                    if (contactCursor.moveToFirst()) {
                        do {
                            name = contactCursor.getString(contactCursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
                            photoUri = contactCursor.getString(contactCursor.getColumnIndex(ContactsContract.PhoneLookup.PHOTO_URI));
                        } while (contactCursor.moveToNext());
                    }
                    contactCursor.close();
                }
            }
        }
    }
    cursor.close();

Note that you need gain Manifest.permission.READ_CONTACTS permission to read informations about contacts.



Answered By - grabarz121
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to pass all phone contacts to JSON API in swift

 November 06, 2022     contacts, json, swift     No comments   

Issue

I am able to fetch all phone contacts in a table view.

I need to pass all phone contacts in JSON URL parameter called contactsList, but I am unable to pass all phone contacts to Json parameter contactsList

If I send individual phone number like below code, it's coming

but i need to send all my phone contacts to JSON API

code: here the api and given phone numbers all are working.. here with my code you can check JSON response as well.. but i need to send all phone contacts to API

import UIKit
import Contacts
class ContactsViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {

@IBOutlet weak var joinersTableView: UITableView!
var contacts = [CNContact]()
var phNumArray  = ["5555555544", "1212121212"]
var taggedStatus: String?

override func viewDidLoad() {
    super.viewDidLoad()
    joinersTableView.register(UINib(nibName: "ContactsTableViewCell", bundle: nil), forCellReuseIdentifier: "ContactsTableViewCell")
    ContactsModel.shared.getLocalContacts {(contact) in
        self.contacts.append(contact!)
    }
    joinersTableView.reloadData()

    self.callPostApi()
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return contacts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
    let cell: ContactsTableViewCell = tableView.dequeueReusableCell(withIdentifier: "ContactsTableViewCell") as! ContactsTableViewCell
    cell.nameLbl.text    = contacts[indexPath.row].givenName + " " + contacts[indexPath.row].familyName
    cell.phNUmLbl.text = contacts[indexPath.row].phoneNumbers.first?.value.stringValue
   
    return cell
    
}

    func callPostApi() {

        let url            = URL(string: "http://itaag-env-1.ap-south-1.elasticbeanstalk.com/filter/taggedusers/")!
        var request        = URLRequest(url: url)
        request.httpMethod = "POST"

        request.setValue("F139424D-C749-42F6-B804-21BD17E28CE0", forHTTPHeaderField: "deviceid")
        request.setValue("c913136e897b419bab20746de7baab62", forHTTPHeaderField: "key")
        request.setValue("personal", forHTTPHeaderField: "userType")

        try? request.setMultipartFormData(["contactsList": "\(phNumArray)"], encoding: .utf8)
       
        URLSession.shared.dataTask(with: request) { data, _, _ in
            if let data = data, let jsonObj = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
           print("contacts JSON \(jsonObj)")
                let phnDict = jsonObj as? [String : Any]
                
                print("each phone number1111111 \(phnDict)")

            }
        }.resume()
    }
    }
 extension URLRequest {

public mutating func setMultipartFormData(_ parameters: [String: String], encoding: String.Encoding) throws {

    let makeRandom = { UInt32.random(in: (.min)...(.max)) }
    let boundary = String(format: "------------------------%08X%08X", makeRandom(), makeRandom())

    let contentType: String = try {
        guard let charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(encoding.rawValue)) else {
            throw MultipartFormDataEncodingError.characterSetName
        }
        return "multipart/form-data; charset=\(charset); boundary=\(boundary)"
    }()
    addValue(contentType, forHTTPHeaderField: "Content-Type")

    httpBody = try {
        var body = Data()

        for (rawName, rawValue) in parameters {
            if !body.isEmpty {
                body.append("\r\n".data(using: .utf8)!)
            }

            body.append("--\(boundary)\r\n".data(using: .utf8)!)

            guard
                rawName.canBeConverted(to: encoding),
                let disposition = "Content-Disposition: form-data; name=\"\(rawName)\"\r\n".data(using: encoding) else {
                throw MultipartFormDataEncodingError.name(rawName)
            }
            body.append(disposition)

            body.append("\r\n".data(using: .utf8)!)

            guard let value = rawValue.data(using: encoding) else {
                throw MultipartFormDataEncodingError.value(rawValue, name: rawName)
            }

            body.append(value)
        }

        body.append("\r\n--\(boundary)--\r\n".data(using: .utf8)!)

        return body
    }()
}
}

public enum MultipartFormDataEncodingError: Error {
case characterSetName
case name(String)
case value(String, name: String)
}

EDIT: OUT PUT: here how do i get each contact userName and tagged values

contacts JSON ["(408) 555-5270": {
oniTaag = 0;
profilePic = "<null>";
tagged = 0;
userId = "<null>";
userName = "<null>";
userType = personal;
}, "555-522-8243": {
oniTaag = 0;
profilePic = "<null>";
tagged = 0;
userId = "<null>";
userName = "<null>";
userType = personal;
}, "(408) 555-3514": {
oniTaag = 0;
profilePic = "<null>";
tagged = 0;
userId = "<null>";
userName = "<null>";
userType = personal;
}, "555-478-7672": {
oniTaag = 0;
profilePic = "<null>";
tagged = 0;
userId = "<null>";
userName = "<null>";
userType = personal;
.......

Solution

To convert the contact array as an array of string you can do this

let phNumArray = contacts.flatMap { $0.phoneNumbers }.map { $0.value.stringValue }

Then you can send phNumArray as it is now.

Answer for question in the comment.
To other properties of contact, you can do something like this

for contact in contacts {
    print(contact.givenName)
    print(contact.familyName)
}

Obviously you need to use proper keys in this case CNContactGivenNameKey, CNContactFamilyNameKey during contact fetch.

You can get the list of available properties here
Look here for available keys.



Answered By - Nazmul Islam
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to open Edit Contact UI for existing contact in swift using Contact UI

 November 06, 2022     contacts, ios, swift     No comments   

Issue

I am working on iOS application in which I want to Add new contact in Phonebook using Contact UI. I know how to open Contact UI for New Contact but I am facing difficulty in opening the existing Contact in Contact UI for Edit.

I am opening New Contact UI as

    let contact = CNMutableContact()
    
    let localizedLabelString = CNLabeledValue<NSString>.localizedString(forLabel: CNLabelPhoneNumberMobile)
    let phoneNumber = CNPhoneNumber(stringValue: contacTNumber )
    let labeledPhoneNumber = CNLabeledValue(label: localizedLabelString, value: phoneNumber)
    contact.phoneNumbers.append(labeledPhoneNumber)
    
    let controller = CNContactViewController(forNewContact: contact)
    controller.delegate = self
    controller.displayedPropertyKeys = [CNContactPhoneNumbersKey, CNContactGivenNameKey]
    let nav = UINavigationController(rootViewController: controller)
    self.present(nav, animated: true, completion: nil)

Below is the Edit contact UI that I want to open.

enter image description here


Solution

There are different constructors for the view controller depending on whether the contact is new, existing or unknown.

init(for: CNContact)
Initializes a view controller for an existing contact.

init(forUnknownContact: CNContact)
Initializes a view controller for an unknown contact.

init(forNewContact: CNContact?)
Initializes a view controller for a new contact.

You code is using init(forNewContact:). Try using init(for:)



Answered By - Dale
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can I add a label to a contact while creating it with Google Apps Script?

 November 06, 2022     contacts, google-apps-script, google-contacts-api     No comments   

Issue

I can create a new Google contact on submission of a Form. I need to add a label to these contacts but I couldn't find any method to do that. Is it possible to add a label? Here is a snippet of my code for finding/creating a contact:

var contact = ContactsApp.getContact(email);
if(!contact){
  contact = ContactsApp.createContact(firstName, lastName, email);
}

Solution

To add label to a contact, add Contact to a ContactGroup. Here is a sample code:

  let labelName = 'myLabel';
  let firstName = 'John';
  let lastName = 'Doe';
  let email = 'john.doe@gmail.com';

  //find or create the Contact
  let contact = ContactsApp.getContact(email) || ContactsApp.createContact(firstName, lastName, email);
  }

  //find the Label
  let group = ContactsApp.getContactGroup(labelName);

  //add label to the contact
  group.addContact(contact);


Answered By - Aaryan Gupta
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] how to remove duplicate contact from contact list in android

 November 06, 2022     android, contacts     No comments   

Issue

please have a look :-

 public static ArrayList<ContactsEntityBean> getContactDetails(
            Context mContext) {
        ArrayList<ContactsEntityBean> contactList = new ArrayList<ContactsEntityBean>();
        ContentResolver cr = mContext.getContentResolver();
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
                null, null, null);
        if (cur.getCount() > 0) {
            while (cur.moveToNext()) {
                String id = cur.getString(cur
                        .getColumnIndex(ContactsContract.Contacts._ID));
                Cursor cur1 = cr.query(
                        ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                        null, ContactsContract.CommonDataKinds.Email.CONTACT_ID
                                + " = ?", new String[] {
                            id
                        }, null);
                while (cur1.moveToNext()) {
                    ContactsEntityBean contactsEntityBean = new ContactsEntityBean();
                    // to get the contact names
                    String name = cur1
                            .getString(cur1
                                    .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));

                    // Log.e("Name :", name);
                    String email = cur1
                            .getString(cur1
                                    .getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));

                    // Log.e("Email", email);
                    contactsEntityBean.setName(name);
                    contactsEntityBean.setEmail(email);
                    if (email != null) {
                        contactList.add(contactsEntityBean);
                    }
                }
                cur1.close();
            }
        }
        return contactList;
    }

this method is return multiple contact from same user suppose if i have stored abc@gmail.com,abc@gmail.com for same user so it is returning abc@gmail.com& abc@gmail.com but i want only one record abc@gmail.com

 public static ArrayList<SearchEntityBean> getContactEmailDetails(
            Context mContext) {
        ArrayList<SearchEntityBean> contactList = new ArrayList<SearchEntityBean>();


        try {
            ContentResolver cr = mContext.getContentResolver();
            Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
                    null, null, null);
            if (cur.getCount() > 0) {
                while (cur.moveToNext()) {
                    String email = "";
                    String id = cur.getString(cur
                            .getColumnIndex(ContactsContract.Contacts._ID));

                    Cursor cur1 = cr.query(
                            ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                            null,
                            ContactsContract.CommonDataKinds.Email.CONTACT_ID
                                    + " = ?", new String[] {
                                id
                            }, null);
                    SearchEntityBean contactsEntityBean = new SearchEntityBean();
                    while (cur1.moveToNext()) {

                        // to get the contact names

                        String name = cur1
                                .getString(cur1
                                        .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                        String image = cur1
                                .getString(cur1
                                        .getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_ID));
                        String mail = cur1
                                .getString(cur1
                                        .getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));

                        if (mail != null) {
                            if (!mail.equalsIgnoreCase(LoginPreferenceClass
                                    .getEmailID(mContext)))
                                email = email + mail + ",";
                        }
                        // Log.e("rohit", "Contact  Email :" + email);
                        contactsEntityBean.setName(name);
                        contactsEntityBean.setImage(image);

                    }

                    if (email != null) {

                        if (email.length() > 0) {

                            if (email.split(",").length > 1) {

                                contactsEntityBean.setMutipleEmail(true);

                            }

                            contactsEntityBean.setUserType("2");
                            contactsEntityBean.setContactId(id);
                            contactsEntityBean.setEmail(email);
                            contactList.add(contactsEntityBean);
                        }
                    }
                    cur1.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        HashSet<SearchEntityBean> hs = new HashSet<SearchEntityBean>();
        hs.addAll(contactList);
        contactList.clear();
        contactList.addAll(hs);
        return contactList;
    }

Solution

You should modify your ContactsEntityBean like below

public class ContactsEntityBean {
    private HashSet<String> emails = new HashSet<String>(); 

    public void setEmail(String email) {
        if (email == null)
            return; 
        this.emails.add(email.trim()); 
    }

    public HashSet<String> getEmails() {
        return this.emails; 
    }
}

Will care about duplicate emails... you can use same logic for addresses, phones etc.


Replace your ContactsEntityBean with below code

public class ContactsEntityBean {
    private HashSet<String> emails;
    private HashSet<String> phones;
    private HashSet<String> addresses;
    private String contactId;
    private boolean checked = false;

    public ContactsEntityBean() {
        this.emails = new HashSet<String>();
        this.phones = new HashSet<String>();
        this.addresses = new HashSet<String>();
    }

    public HashSet<String> getPhones() {
        return phones;
    }

    public void setPhones(String phone) {
        if (phone == null)
            return;
        this.phones.add(phone.trim());
    }

    public HashSet<String> getAddresses() {
        return addresses;
    }

    public void setAddresses(String address) {
        if (address == null)
            return;
        this.addresses.add(address.trim());
    }

    public void setEmails(String email) {
        if (email == null)
            return;
        this.emails.add(email.trim());
    }

    public HashSet<String> getEmails() {
        return emails;
    }

    public String getContactId() {
        return contactId;
    }

    public void setContactId(String contactId) {
        this.contactId = contactId;
    }

    public boolean isChecked() {
        return checked;
    }

    public void setChecked(boolean checked) {
        this.checked = checked;
    }
}

And no need to care about duplicates. this will care about all the things..



Answered By - Pankaj Kumar
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to fetch all contacts record in iOS 9 using Contacts Framework

 November 06, 2022     contacts, ios, ios9, nspredicate     No comments   

Issue

Most part of AddressBook framework is deprecated in iOS 9. In the new Contacts Framework documentation only shows how to fetch records matches a NSPredicate, but what if I want all the record?


Solution

Both other answers do only load contacts from the container with the defaultContainerIdentifier. In a scenario, where the user has more than one container (i.e. an Exchange and an iCloud account which both are used to store contacts), this would only load the contacts from the account that is configured as the default. Therefore, it would not load all contacts as requested by the author of the question.

What you'll probably want to do instead is getting all the containers and iterate over them to extract all contacts from each of them. The following code snippet is an example of how we do it in one of our apps (in Swift):

lazy var contacts: [CNContact] = {
    let contactStore = CNContactStore()
    let keysToFetch = [
        CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName),
        CNContactEmailAddressesKey,
        CNContactPhoneNumbersKey,
        CNContactImageDataAvailableKey,
        CNContactThumbnailImageDataKey]

    // Get all the containers
    var allContainers: [CNContainer] = []
    do {
        allContainers = try contactStore.containersMatchingPredicate(nil)
    } catch {
        print("Error fetching containers")
    }

    var results: [CNContact] = []

    // Iterate all containers and append their contacts to our results array
    for container in allContainers {
        let fetchPredicate = CNContact.predicateForContactsInContainerWithIdentifier(container.identifier)

        do {
            let containerResults = try contactStore.unifiedContactsMatchingPredicate(fetchPredicate, keysToFetch: keysToFetch)
            results.appendContentsOf(containerResults)
        } catch {
            print("Error fetching results for container")
        }
    }

    return results
}()


Answered By - flohei
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to access the phone contact list and display it in tableview?

 November 06, 2022     abaddressbook, contacts, iphone, objective-c     No comments   

Issue

Such as the Table cell having:

  1. Contact image

  2. Contact name.

I found that we have to use framework:

  1. AddressBook.framework

  2. AddressBookUI.framework

How can I achieve this?


Solution

ABAddressBookRef addressBook = ABAddressBookCreate(); // create address book reference object
NSArray *abContactArray = (NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook); // get address book contact array

NSInteger totalContacts =[abContactArray count];
    
for(NSUInteger loop= 0 ; loop < totalContacts; loop++)
{
    ABRecordRef record = (ABRecordRef)[abContactArray objectAtIndex:loop]; // get address book record
        
   if(ABRecordGetRecordType(record) ==  kABPersonType) // this check execute if it is person group
    {
            ABRecordID recordId = ABRecordGetRecordID(record); // get record id from address book record
            
            NSString *recordIdString = [NSString stringWithFormat:@"%d",recordId]; // get record id string from record id
            
            NSString *firstNameString = (NSString*)ABRecordCopyValue(record,kABPersonFirstNameProperty); // fetch contact first name from address book  
            NSString *lastNameString = (NSString*)ABRecordCopyValue(record,kABPersonLastNameProperty); // fetch contact last name from address book
    }
}

for more check these links

http://developer.apple.com/library/ios/#documentation/AddressBook/Reference/ABPersonRef_iPhoneOS/Reference/reference.html

http://developer.apple.com/library/ios/#DOCUMENTATION/AddressBook/Reference/ABAddressBookRef_iPhoneOS/Reference/reference.html



Answered By - Sadia
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] how to convert a CNPhoneNumber to string in swift4?

 November 06, 2022     casting, contacts, swift     No comments   

Issue

I am using this code for getting contact number from contacts app but when I want to show the number in label I get this warning and doesn't work: Cast from 'CNPhoneNumber' to unrelated type 'String' always fails

func contactPicker(_ picker: CNContactPickerViewController, didSelect contacts: [CNContact]) {
    contacts.forEach {(contact) in
        for number in contact.phoneNumbers{
            let phone = number.value
            print(phone)
            numberLabel.text = phone as! String
        }
    }
}

Solution

TRY :

if let phone = number.value as? CNPhoneNumber {
    print(phone.stringValue)
} else {
   print("number.value not of type CNPhoneNumber")
}

also take a look at CNContact , CNPhoneNumber



Answered By - PhillipJacobs
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to sort contacts using Contacts with Swift

 November 06, 2022     cncontact, contacts, ios, swift     No comments   

Issue

I've read official apple documentation about sorting contacts, although I am not sure how to implement it. So, here is fetch request:

let fetchRequest = CNContactFetchRequest(keysToFetch: keysToFetch)

and my prefered sort order:

let sortOrder = CNContactSortOrder.UserDefault

and this is how I usually fetch contacts:

    do {
        try store.enumerateContactsWithFetchRequest(fetchRequest, usingBlock: { (let contact, let stop) -> Void in
                self.contacts.append(contact)
        })
    }
    catch let error as NSError {
        print(error.localizedDescription)
    }

Now what should I do with sortOrder? Where and should I include in my whole fetching process?


Solution

Updated For Swift 4.0

let fetchRequest = CNContactFetchRequest(keysToFetch: [CNContactGivenNameKey as CNKeyDescriptor, CNContactFamilyNameKey as CNKeyDescriptor, CNContactMiddleNameKey as CNKeyDescriptor, CNContactEmailAddressesKey as CNKeyDescriptor,CNContactPhoneNumbersKey as CNKeyDescriptor])

        fetchRequest.sortOrder = CNContactSortOrder.userDefault

        let store = CNContactStore()

        do {
            try store.enumerateContacts(with: fetchRequest, usingBlock: { (contact, stop) -> Void in
              //  print(contact.phoneNumbers.first?.value ?? "not found")

            })
        }
        catch let error as NSError {
            print(error.localizedDescription)
        }

Old Version write like this

 fetchRequest.sortOrder = CNContactSortOrder.UserDefault

after fetchRequest object created so your final output is like

let fetchRequest = CNContactFetchRequest(keysToFetch: keysToFetch)

fetchRequest.sortOrder = CNContactSortOrder.UserDefault

 do {
        try store.enumerateContactsWithFetchRequest(fetchRequest, usingBlock: { (let contact, let stop) -> Void in
                self.contacts.append(contact)
        })
    }
    catch let error as NSError {
        print(error.localizedDescription)
    }


Answered By - Jaydeep Patel
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do you access a phone number from your user's contacts in swift?

 November 06, 2022     addressbook, contacts, ios, swift, xcode     No comments   

Issue

Here is my code for getting the name of a contact, how would I go about getting their phone number?

func createAddressBook() -> Bool {
    if self.addressBook != nil {
        return true
    }
    var err : Unmanaged<CFError>? = nil
    let addressBook : ABAddressBook? = ABAddressBookCreateWithOptions(nil, &err).takeRetainedValue()
    if addressBook == nil {
        println(err)
        self.addressBook = nil
        return false
    }
    self.addressBook = addressBook
    getContactNames()
    return true
}

func getContactNames() {
    if !self.determineStatus() {
        println("not authorized")
        return
    }
    let people = ABAddressBookCopyArrayOfAllPeople(addressBook).takeRetainedValue() as NSArray as [ABRecord]
    for person in people {
        var contactName = ABRecordCopyCompositeName(person).takeRetainedValue() as String
        self.contacts.append(contact(name: contactName))
    }
}

Any help would be greatly appreciated.


Solution

As of iOS 9, we would use Contacts framework, in which phoneNumbers is a CNLabeledValue<CNPhoneNumber>:

let status = CNContactStore.authorizationStatus(for: .contacts)
if status == .denied || status == .restricted {
    presentSettingsAlert()
    return
}

// open it

let store = CNContactStore()
store.requestAccess(for: .contacts) { granted, error in
    guard granted else {
        self.presentSettingsAlert()
        return
    }
    
    // get the contacts
    
    let request = CNContactFetchRequest(keysToFetch: [CNContactFormatter.descriptorForRequiredKeys(for: .fullName), CNContactPhoneNumbersKey as CNKeyDescriptor])
    do {
        try store.enumerateContacts(with: request) { contact, stop in
            let name = CNContactFormatter.string(from: contact, style: .fullName)
            print(name)
            
            for phone in contact.phoneNumbers {
                var label = phone.label
                if label != nil {
                    label = CNLabeledValue<CNPhoneNumber>.localizedString(forLabel: label!)
                }
                print("  ", label, phone.value.stringValue)
            }
        }
    } catch {
        print(error)
    }
}

Where

private func presentSettingsAlert() {
    let settingsURL = URL(string: UIApplicationOpenSettingsURLString)!
    
    DispatchQueue.main.async {
        let alert = UIAlertController(title: "Permission to Contacts", message: "This app needs access to contacts in order to ...", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "Go to Settings", style: .default) { _ in
            UIApplication.shared.openURL(settingsURL)
        })
        alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
        self.present(alert, animated: true)
    }
}

Prior to iOS 9, you would use the AddressBook framework, in which the phone numbers is a ABMultiValueRef, so get that reference and then iterate through the phone numbers:

// make sure user hadn't previously denied access

let status = ABAddressBookGetAuthorizationStatus()
if status == .denied || status == .restricted {
    presentSettingsAlert()
    return
}

// open it

var error: Unmanaged<CFError>?
guard let addressBook: ABAddressBook? = ABAddressBookCreateWithOptions(nil, &error)?.takeRetainedValue() else {
    print(String(describing: error?.takeRetainedValue()))
    return
}

// request permission to use it

ABAddressBookRequestAccessWithCompletion(addressBook) { granted, error in
    if !granted {
        self.presentSettingsAlert()
        return
    }
    
    guard let people = ABAddressBookCopyArrayOfAllPeople(addressBook)?.takeRetainedValue() as [ABRecord]? else {
        print("unable to get contacts")
        return
    }
    
    for person in people {
        let name = ABRecordCopyCompositeName(person)?.takeRetainedValue() as String?
        print(name)
        
        if let phoneNumbers: ABMultiValue = ABRecordCopyValue(person, kABPersonPhoneProperty)?.takeRetainedValue() {
            for index in 0 ..< ABMultiValueGetCount(phoneNumbers) {
                let number = ABMultiValueCopyValueAtIndex(phoneNumbers, index)?.takeRetainedValue() as? String
                let label  = ABMultiValueCopyLabelAtIndex(phoneNumbers, index)?.takeRetainedValue()
                print("  ", self.localizedLabel(label), number)
            }
        }
    }
}

MacOS has an existing routine to localize that label, but I don't know of any such public function in AddressBook framework for iOS, so you may want to convert it yourself (or populate localization table for NSLocalizedString):

// frankly, you probably should just use `NSLocalizedString()` and fill the table with these values

private func localizedLabel(_ label: CFString?) -> String? {
    guard let label = label else {
        return nil
    }
    
    if CFStringCompare(label, kABHomeLabel, []) == .compareEqualTo {            // use `[]` for options in Swift 2.0
        return "Home"
    } else if CFStringCompare(label, kABWorkLabel, []) == .compareEqualTo {
        return "Work"
    } else if CFStringCompare(label, kABOtherLabel, []) == .compareEqualTo {
        return "Other"
    } else if CFStringCompare(label, kABPersonPhoneMobileLabel, []) == .compareEqualTo {
        return "Mobile"
    } else if CFStringCompare(label, kABPersonPhoneIPhoneLabel, []) == .compareEqualTo {
        return "iPhone"
    } else if CFStringCompare(label, kABPersonPhoneMainLabel, []) == .compareEqualTo {
        return "Main"
    } else if CFStringCompare(label, kABPersonPhoneHomeFAXLabel, []) == .compareEqualTo {
        return "Home fax"
    } else if CFStringCompare(label, kABPersonPhoneWorkFAXLabel, []) == .compareEqualTo {
        return "Work fax"
    } else if CFStringCompare(label, kABPersonPhoneOtherFAXLabel, []) == .compareEqualTo {
        return "Other fax"
    } else if CFStringCompare(label, kABPersonPhonePagerLabel, []) == .compareEqualTo {
        return "Pager"
    } else {
        return label as String
    }
}

For Swift 2, see previous revision of this answer.



Answered By - Rob
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to set or update a contact's photo with Google Apps Script?

 November 06, 2022     contacts, google-apps-script, google-contacts-api     No comments   

Issue

I used this other question as an example, and it appears like it works, but the contact's photo doesn't actually change, and no error is returned.

I'm able to get the contact's current photo and delete the contact's photo just fine.

My Code

const accessToken = ScriptApp.getOAuthToken();
const id = '4c18faa28828aa3f';
const url = '-URL Omitted-';
const blob = UrlFetchApp.fetch(url).getBlob();
const data = Utilities.base64EncodeWebSafe(blob.getBytes());
const response = UrlFetchApp.fetch(`https://www.google.com/m8/feeds/photos/media/me/${id}`, {
  method: 'put',
  contentType: 'image/jpeg',
  payload: data,
  headers: {
    Authorization: `Bearer ${accessToken}`,
  },
});
const content = response.getContentText();
console.log(content);

Response XML

<?xml version='1.0' encoding='UTF-8'?>
<entry xmlns='http://www.w3.org/2005/Atom'>
  <id>http://www.google.com/m8/feeds/photos/media/-OMITTED-%40gmail.com/4c18faa28828aa3f</id>
  <updated>2020-10-12T22:10:01.271Z</updated>
  <link rel='self' type='application/atom+xml'
        href='https://www.google.com/m8/feeds/photos/media/-OMITTED-%40gmail.com/4c18faa28828aa3f'/>
  <link rel='edit' type='application/atom+xml'
        href='https://www.google.com/m8/feeds/photos/media/-OMITTED-%40gmail.com/4c18faa28828aa3f/1B2M2Y8AsgTpgAmY7PhCfg'/>
</entry>

Solution

I figured it out. I was encoding the image blob bytes for the payload for some reason. I should have just passed the blob as the payload like this.

const accessToken = ScriptApp.getOAuthToken();
const id = '4c18faa28828aa3f';
const url = '-URL Omitted-';
const blob = UrlFetchApp.fetch(url).getBlob();
const response = UrlFetchApp.fetch(`https://www.google.com/m8/feeds/photos/media/me/${id}`, {
  method: 'put',
  contentType: 'image/jpeg',
  payload: blob,
  headers: {
    Authorization: `Bearer ${accessToken}`,
  },
});
const content = response.getContentText();
console.log(content);


Answered By - burkybang
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to search phone contacts in swift

 November 06, 2022     contacts, search, swift, tableview     No comments   

Issue

In project i am getting all my contacts.. here i need to search contacts by their name how to do that

i have done almost but unable to filter in textDidChange

below is my tried code:

class ContactsViewController1: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var joinersTableView: UITableView!
    var contacts = [CNContact]()

    var search = false
    var searchArray = [CNContact]()

    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return jsonArrayTagged.count
        } else {
            if search {
                return searchArray.count
            } else {
                return contacts.count
            }
        }
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 1 {
            var cell1: ContactsTableViewCell2 = tableView.dequeueReusableCell(withIdentifier: "ContactsTableViewCell2", for: indexPath) as! ContactsTableViewCell2
            if search {
                cell1.nameLbl.text    = searchArray[indexPath.row].givenName + " " + searchArray[indexPath.row].familyName
                cell1.empRoleLbl.text = searchArray[indexPath.row].phoneNumbers.first?.value.stringValue
                cell1.inviteButn.addTarget(self, action: #selector(connected(sender:)), for: .touchUpInside)
            } else {
                cell1.nameLbl.text    = contacts[indexPath.row].givenName + " " + contacts[indexPath.row].familyName
                cell1.empRoleLbl.text = contacts[indexPath.row].phoneNumbers.first?.value.stringValue
                cell1.inviteButn.addTarget(self, action: #selector(connected(sender:)), for: .touchUpInside)
            }

            return cell1
        }

        return UITableViewCell()
    }
}

extension ContactsViewController: UISearchBarDelegate {
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        searchArray = contacts.filter({$0.lowercased().prefix(searchText.count) == searchText.lowercased()})
        search = true

        joinersTableView.reloadData()
    }

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        search = false
        searchBar.text = ""
        joinersTableView.reloadData()
    }
}

error:

Value of type 'CNContact' has no member 'lowercased'


Solution

You can't just use a CNContact as a String and compare it with a String. You need to specify which String property of the CNContact you want to filter.

If you want to search the familyName for instance, do $0.familyName.lowerCased() instead of $0.lowerCased, since $0 is a CNContact.

extension ContactsViewController: UISearchBarDelegate {
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        searchArray = contacts.filter {$0.familyName.lowercased().prefix(searchText.count) == searchText.lowercased()}
        search = true

        joinersTableView.reloadData()
    }
...
}

Unrelated to your question, but why are you searching the beginning of the text only? Using localizedCaseInsensitiveContains instead of prefix would yield a much better user experience.



Answered By - Dávid Pásztor
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to get whatsapp Contacts from Android Programmatically?

 November 06, 2022     android, android-contacts, android-contentresolver, contacts, whatsapp     No comments   

Issue

I have to try to get WhatsApp contacts from phone and I get a total Count of WhatsApp contact but from RawContacts how to get WhatsApp numbers and names that I don't know. I have tried to find a solution but can't get the exact solution for that. Please help me.

I put my code below.

ContentResolver cr = context.getContentResolver();

Cursor c = cr.query(
                        ContactsContract.RawContacts.CONTENT_URI,
                        new String[] { ContactsContract.RawContacts.CONTACT_ID, ContactsContract.RawContacts.DISPLAY_NAME_PRIMARY },
                        ContactsContract.RawContacts.ACCOUNT_TYPE + "= ?",
                        new String[] { "com.whatsapp" },
                        null);

                ArrayList<String> myWhatsappContacts = new ArrayList<>();

                String projection[] = { ContactsContract.CommonDataKinds.Phone.NUMBER };

                if(c != null) {
                    if (c.getCount() > 0) {
                        while (c.moveToNext()) {

                            String whatsappContactId = c.getString(c.getColumnIndex(ContactsContract.RawContacts.Data._ID));

                            Cursor dataCursor = cr.query(
                                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                    projection,
                                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                                    new String[]{whatsappContactId}, null);
                            // You can also read RawContacts.CONTACT_ID to read the
                            // ContactsContract.Contacts table or any of the other related ones.
                            String number = dataCursor.getString(dataCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NORMALIZED_NUMBER));
                            myWhatsappContacts.add(number);

                        }
                    }
                }

                showLogI(TAG, " WhatsApp contact size :  " + myWhatsappContacts.size());

Solution

I have found Solution of my question so i put my answer here.. may it useful for others..

First Read and try to understand diagram of Android Contacts Data Store after that it's easy to understand whole contact flow. Three tier data model diagram is given below the snippets.

Code Snippets

//This class provides applications access to the content model.
ContentResolver cr = context.getContentResolver();

//RowContacts for filter Account Types
Cursor contactCursor = cr.query(
        ContactsContract.RawContacts.CONTENT_URI,
        new String[]{ContactsContract.RawContacts._ID,
                ContactsContract.RawContacts.CONTACT_ID},
        ContactsContract.RawContacts.ACCOUNT_TYPE + "= ?",
        new String[]{"com.whatsapp"},
        null);

//ArrayList for Store Whatsapp Contact
ArrayList<String> myWhatsappContacts = new ArrayList<>();

if (contactCursor != null) {
    if (contactCursor.getCount() > 0) {
        if (contactCursor.moveToFirst()) {
            do {
                //whatsappContactId for get Number,Name,Id ect... from  ContactsContract.CommonDataKinds.Phone
                String whatsappContactId = contactCursor.getString(contactCursor.getColumnIndex(ContactsContract.RawContacts.CONTACT_ID));

                if (whatsappContactId != null) {
                    //Get Data from ContactsContract.CommonDataKinds.Phone of Specific CONTACT_ID
                    Cursor whatsAppContactCursor = cr.query(
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                            new String[]{ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
                                    ContactsContract.CommonDataKinds.Phone.NUMBER,
                                    ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME},
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                            new String[]{whatsappContactId}, null);

                    if (whatsAppContactCursor != null) {
                        whatsAppContactCursor.moveToFirst();
                        String id = whatsAppContactCursor.getString(whatsAppContactCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
                        String name = whatsAppContactCursor.getString(whatsAppContactCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                        String number = whatsAppContactCursor.getString(whatsAppContactCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

                        whatsAppContactCursor.close();

                        //Add Number to ArrayList
                        myWhatsappContacts.add(number);

                        showLogI(TAG, " WhatsApp contact id  :  " + id);
                        showLogI(TAG, " WhatsApp contact name :  " + name);
                        showLogI(TAG, " WhatsApp contact number :  " + number);
                    }
                }
            } while (contactCursor.moveToNext());
            contactCursor.close();
        }
    }
}

showLogI(TAG, " WhatsApp contact size :  " + myWhatsappContacts.size());

here is the show Android Contact Data Store Diagram enter image description here



Answered By - Mansukh Ahir
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to add Millions of contacts to telegram?

 November 06, 2022     automation, contacts, python, telegram, telethon     No comments   

Issue

My goal is to add 10M contacts to telegram.

How can we add contacts to telegram using telegram API? I have tried using telethon in which I batched 500 contacts in one request. However, telegram responded all such requests with all contacts in retry_contacts and none were imported.

I have also found out a solution to convert the txt file of 10M contacts to csv file and import them using an android app. But this takes approx 10 mins for 10k contacts. So this won't be a good idea for adding 10M contacts.

Any other method for having this done is also welcomed.


Solution

This is not possible. Telegram has deliberately set limits on the number of contacts you can add. Initially you can add about 5000 contacts and after that you can add about 100 more every day. This is because of security not decreasing their API load. If you could add 10M numbers, you could easily map @usernames to numbers which is against Telegram privacy policy.

In my experience, the best practical option is to add an array of 10 numbers each time using telethon's ImportContactsRequest, until you get locked. Then try 24 hours later again until you get locked again, and so on. This is the fastest solution and due to Telegram restrictions, if you only have 1 SIM card, it takes around 274 years to add 10M contacts.



Answered By - Ali Hashemi
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to update 'profile' contact programmatically in Android?

 November 06, 2022     android, android-contentprovider, contacts, user-profile     No comments   

Issue

I want to edit the device main user's profile from within my application. So I used the ContentProviderOperation with newUpdate method to collect the changes and then commit them using the ContentResolver method's : applyBatch. Here is the code i wrote so far:

public ContentProviderResult[] updateProfile(Contact userProfile) {
        try {
            ArrayList<ContentProviderOperation> ops = new ArrayList<>();
            ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, Integer.valueOf(userProfile.id))
                    .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                    .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, edtName.getText().toString().trim())
                    .build());
            return getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

I am getting any run-time Exception but no change is commited! Am I missing something?


Solution

I have figured it out, the problem was that I didn't know how to retrieve the User Profile RAW_CONTACT_ID to project on it on the ContactsContract.Data table.

My quick fix was by deleting the User Profile record and then create a new one. This is the code I used so far :

public ContentProviderResult[] createOrUpdateUserProfile() {
        ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
        int rawContactInsertIndex = ops.size();

        try {
            ops.add(ContentProviderOperation.
                    newDelete(ContactsContract.Profile.CONTENT_RAW_CONTACTS_URI)
                    .build());

            getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
            ops.clear();

            //Create User Profile
            ops.add(ContentProviderOperation.newInsert(ContactsContract.Profile.CONTENT_RAW_CONTACTS_URI)
                    .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
                    .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
                    .build());

            //Create User Name
            if (!(edtName.getText().toString().matches(""))) {
                ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                        .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
                        .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                        .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, edtName.getText().toString())
                        .build());
            }

            if (!(edtHomePhone.getText().toString().matches(""))) {
                ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                        .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
                        .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                        .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, edtHomePhone.getText().toString())
                        .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, 1)
                        .build());
            }

            if (!(edtMobilePhone.getText().toString().matches(""))) {
                ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                        .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
                        .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                        .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, edtMobilePhone.getText().toString())
                        .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, 2)
                        .build());
            }

            if (!(edtWorkPhone.getText().toString().matches(""))) {
                ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                        .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
                        .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                        .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, edtWorkPhone.getText().toString())
                        .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, 3)
                        .build());
            }

            if (!(edtHomeEmail.getText().toString().matches(""))) {
                ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                        .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
                        .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
                        .withValue(ContactsContract.CommonDataKinds.Email.ADDRESS, edtHomeEmail.getText().toString())
                        .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, 1) // contact.numbers.get(0).type
                        .build());
            }

            if (!(edtWorkEmail.getText().toString().matches(""))) {
                ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                        .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
                        .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
                        .withValue(ContactsContract.CommonDataKinds.Email.ADDRESS, edtWorkEmail.getText().toString())
                        .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, 2) // contact.numbers.get(0).type
                        .build());
            }

            /*String completeAddress = edtStreet.getText().toString() + edtCity.getText().toString() + edtState.getText().toString()
                    + edtCountry.getText().toString();*/
            ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
                    .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
                    .withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET, edtStreet.getText().toString())
                    .withValue(ContactsContract.CommonDataKinds.StructuredPostal.CITY, edtCity.getText().toString())
                    .withValue(ContactsContract.CommonDataKinds.StructuredPostal.REGION, edtState.getText().toString())
                    .withValue(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY, edtCountry.getText().toString())
                    .withValue(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE, edtZip.getText().toString())
                    .withValue(ContactsContract.CommonDataKinds.StructuredPostal.TYPE, 1)
                    .build());

            if (!(edtSkype.getText().toString().matches(""))) {
                ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                        .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
                        .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE)
                        .withValue(ContactsContract.CommonDataKinds.Im.DATA, edtSkype.getText().toString())
                        .withValue(ContactsContract.CommonDataKinds.Im.PROTOCOL, 3)
                        .build());
            }


            ContentProviderResult[] res = getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
            return res;
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (OperationApplicationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }


Answered By - AouledIssa
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to search contacts by name and phone number?

 November 06, 2022     android, android-contacts, contacts     No comments   

Issue

I am using Contacts.CONTENT_FILTER_URI to search for contacts.

Uri contentUri = Uri.withAppendedPath(
                ContactsContract.Contacts.CONTENT_FILTER_URI,
                Uri.encode(searchString));

The searchstring can be either a number or a name. That works great.
My only problem is that the result does not contain a contact phone number.

I know that I can get it by querying ContactsContract.Data.CONTENT_URI. However, I would like to find a solution that will give me a contact name and phone number with a single query.


Solution

You should use Phone.CONTENT_FILTER_URI instead of Contacts.CONTENT_FILTER_URI

Docs say:

The filter is applied to display names as well as phone numbers.

Try this:

Uri filterUri = Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, Uri.encode(searchString));
String[] projection = new String[]{ Phone.CONTACT_ID, Phone.DISPLAY_NAME, Phone.NUMBER };
Cursor cur = getContentResolver().query(filterUri, projection, null, null, null);


Answered By - marmor
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to get a CNContact phone number(s) as string in Swift?

 November 06, 2022     addressbook, contacts, ios, ios9, swift     No comments   

Issue

I am attempting to retrieve the names and phone number(s) of all contacts and put them into arrays with Swift in iOS. I have made it this far:

func findContacts() -> [CNContact] {

    marrContactsNumber.removeAllObjects()
    marrContactsName.removeAllObjects()

    let store = CNContactStore()

    let keysToFetch = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey]

    let fetchRequest = CNContactFetchRequest(keysToFetch: keysToFetch)

    var contacts = [CNContact]()

    do {
        try store.enumerateContactsWithFetchRequest(fetchRequest, usingBlock: { (let contact, let stop) -> Void in
            contacts.append(contact)

            self.marrContactsName.addObject(contact.givenName + " " + contact.familyName)

            self.marrContactsNumber.addObject(contact.phoneNumbers)

            print(contact.phoneNumbers)
    }
    catch let error as NSError {
        print(error.localizedDescription)
    }

    print(marrContactsName.count)
    print(marrContactsNumber.count)

    return contacts
}

Once completed, marrContactsName contains an array of all my contacts' names exactly as expected. i.e. "John Doe". However, marrContactsNumber returns an array of values like

[<CNLabeledValue: 0x158a19950: identifier=F831DC7E-5896-420F-AE46-489F6C14DA6E,
label=_$!<Work>!$_, value=<CNPhoneNumber: 0x158a19640: countryCode=us, digits=6751420000>>,
<CNLabeledValue: 0x158a19a80: identifier=ECD66568-C6DD-441D-9448-BDEDDE9A68E1,
label=_$!<Work>!$_, value=<CNPhoneNumber: 0x158a199b0: countryCode=us, digits=5342766455>>]

I would like to know how to retrieve JUST the phone number(s) as a string value(s) i.e. "XXXXXXXXXX". Basically, how to call for the digit(s) value. Thanks!


Solution

I found the solution: (contact.phoneNumbers[0].value as! CNPhoneNumber).valueForKey("digits") as! String



Answered By - Baylor Mitchell
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] how many contacts in contact list

 November 06, 2022     android, android-contacts, contacts     No comments   

Issue

How can I tell how many contacts there are in the contact list? I got the contact number, but one person can have more than one contact and I want to account for this in finding the total number of contacts in the contact list.


Solution

To find the count of phone numbers of all the contacts

Cursor cursor =  managedQuery(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);

int count = cursor.getCount();

To find the count of all the phone numbers of a particular RawContactID (pass the contact id value in rawContactId).

Cursor cursor =  managedQuery(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID + " = " + rawContactId, null, null);

    int count = cursor.getCount();

The number of contacts displayed in the ContactsListActivity consists can be determined by following query.

Cursor cursor =  managedQuery(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

int count = cursor.getCount();

However if a person has been entered under multiple accounts then only a single instance is obtained by the above query as ContactsContract.Contacts combines all such contacts.

Cursor cursor =  managedQuery(RawContacts.CONTENT_URI, null, null, null, null);

int count = cursor.getCount();

The relation between ContactsContract.Contacts and RawContacts can be found out at http://developer.android.com/resources/articles/contacts.html

Hope this resolves your doubt!



Answered By - Manish Khot
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing