How do I create a speed dial button programmatically? - android

So i've created a simple launcher using this tutorial. I've created a few empty buttons that I intend to use to dial a number instantly when they are pressed.
By default, the buttons have no assigned number. I want the button to launch the default contacts application window when first pressed, so the user can select a contact's number to assign to the button. I'll then launch this through an intent.
I have no idea how to make the first part of this work (bringing up the contacts app, and then assigning details to the button). How do I make this work?

if I understand your question corectly you need to start an activity for result . You start your activity (contacts app ) by clicking a button then onActivityResult - > you get the data you want .
For example :
private static final int REQUEST_CONTACT = 1;
private static final int RESULT_OK = -1;
private static final int RESULT_CANCELED = 0;
private Uri mInfo;
private Context mContext;
Button startContactsApp = (Button)findViewByid(...);
startContactsApp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Thread(new Runnable() { // you need a thread because this operation takes plenty of time
#Override
public void run() {
Intent contactIntent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
contactIntent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE); // to display contacts who have phone number
startActivityForResult(contactIntent, REQUEST_CONTACT);
}
}).start();
}
});
The result:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_CONTACT){
if(resultCode == RESULT_OK && data != null){
mInfo = data.getData();
String name = getContactNameAgenda(); // the name you need
String phone = getContactPhoneNumberAgenda(); //the number you need
Toast.makeText(mContext,"CONTACT ADDED !",Toast.LENGTH_SHORT).show();
}
else if (resultCode == RESULT_CANCELED){
Toast.makeText(getActivity(),"CANCELLED OR SOME ERROR OCCURRED !",Toast.LENGTH_SHORT).show();
}
}
Here you'll get the name and the phone number from that selected contact :
private String getContactNameAgenda(){
Cursor cursor = mContext.getContentResolver().query(mInfo, null,
null, null, null);
cursor.moveToFirst();
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
cursor.close();
return name;
}
private String getContactPhoneNumberAgenda(){
Cursor cursor = mContext.getContentResolver().query(mInfo, new String[]{ContactsContract.Contacts._ID},
null, null, null);
cursor.moveToFirst();
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
cursor.close();
// Using the contact ID now we will get contact phone number
Cursor cursorPhone = mContext.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},
ContactsContract.CommonDataKinds.Phone._ID + " = ? AND " + // Phone._ID is for the database ; Phone.CONTACT_ID is for contact when you are not querying that table
ContactsContract.CommonDataKinds.Phone.TYPE + " = " +
ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,
new String[]{id},
null);
cursorPhone.moveToFirst();
String number = cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
cursorPhone.close();
return number;
}
I hope this will help you.

Related

Android - back from Contacts intent without selecting one

In my android application I have a list of people (name and telephone number) and I let the user add a person to the app's database by importing one from their contacts list. Everything works fine, but a user could click the button to import a new person and then go back, so the Contacts intent will be closed without actually selecting a contact.
So I need to know where to put an if, or something else, in my code in order to see whether the user selected a contact or not.
private void pickContact() {
Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));
pickContactIntent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE); // Show user only contacts w/ phone numbers
startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request it is that we're responding to
if (requestCode == PICK_CONTACT_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// Get the URI that points to the selected contact
Uri contactUri = data.getData();
String[] projection = {ContactsContract.CommonDataKinds.Phone.NUMBER};
Cursor cursor = getContentResolver().query(contactUri, null, null, null, null);
cursor.moveToFirst();
// Retrieve the name from the DISPLAY_NAME column
String name = cursor.getString(cursor.getColumnIndex(ontactsContract.Contacts.DISPLAY_NAME));
// Retrieve the phone number from the NUMBER column
int column = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
String number = cursor.getString(column);
// update database
dbManager.addPerson(name, number, true);
}
}
}
So how can I check if the user actually selected a contact or went back?
So I need to know where to put an if, or something else, in my code in order to see whether the user selected a contact or not.
You already have the code for this: if (resultCode == RESULT_OK). If the user presses BACK, you will not get RESULT_OK.
You are using an startActivityForResult which will return you back to the same activity once your
Intent.ACTION_PICK, Uri.parse("content://contacts")
jobs gets over that is the user has selected a contact.
And in order to get the name , number or any other details of the contact selected you do it in your onActivityResult callback like follows :
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
if(reqCode == PICK_CONTACT_REQUEST) {
String cNumber = null;
String cName = null;
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor cursor = getContentResolver().query(contactData, null, null, null, null);
String hasPhone = null;
String contactId = null;
if (cursor != null) {
cursor.moveToFirst();
try {
hasPhone = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.HAS_PHONE_NUMBER));
contactId = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
} catch (IllegalArgumentException e) {
Log.e(TAG, "Exception Message : " + e.getMessage());
DisplayMessage.error("Sorry can't access contacts. Check permissions settings.", this);
return;
}
if (hasPhone != null && hasPhone.equals("1")) {
Cursor phones = getContentResolver().query
(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = " + contactId, null, null);
if (phones != null) {
while (phones.moveToNext()) {
String phoneNumber = phones.getString(phones.getColumnIndex
(ContactsContract.CommonDataKinds.Phone.NUMBER)).replaceAll("[-() ]", "");
cNumber = phoneNumber;
}
phones.close();
}
cName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Log.d(TAG, "Contact name is:" + cName);
}
cursor.close();
}
}
}
}

Fetching a Single Phone Number from a contact in Contacts Book which is having multiple numbers saved

I need to ask a user for a contact number to make a call. On Button Click the User should be directly redirected to Contacts Book and the user can select a Phone Number. Following is the Source Code what I am using now.
Button buttonReadContact;
TextView textPhone;
final int RQS_PICKCONTACT = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonReadContact = (Button)findViewById(R.id.readcontact);
textPhone = (TextView)findViewById(R.id.phone);
buttonReadContact.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View arg0) {
//Start activity to get contact
final Uri uriContact = ContactsContract.Contacts.CONTENT_URI;
Intent intentPickContact = new Intent(Intent.ACTION_PICK, uriContact);
startActivityForResult(intentPickContact, RQS_PICKCONTACT);
}});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(resultCode == RESULT_OK){
if(requestCode == RQS_PICKCONTACT){
Uri returnUri = data.getData();
Cursor cursor = getContentResolver().query(returnUri, null, null, null, null);
if(cursor.moveToNext()){
int columnIndex_ID = cursor.getColumnIndex(ContactsContract.Contacts._ID);
String contactID = cursor.getString(columnIndex_ID);
int columnIndex_HASPHONENUMBER = cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
String stringHasPhoneNumber = cursor.getString(columnIndex_HASPHONENUMBER);
if(stringHasPhoneNumber.equalsIgnoreCase("1")){
Cursor cursorNum = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactID,
null,
null);
//Get the first phone number
if(cursorNum.moveToNext()){
int columnIndex_number = cursorNum.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
String stringNumber = cursorNum.getString(columnIndex_number);
textPhone.setText(stringNumber);
}
}else{
textPhone.setText("NO Phone Number");
}
}else{
Toast.makeText(getApplicationContext(), "NO data!", Toast.LENGTH_LONG).show();
}
}
}
}
But now the issue is I can only select one number from a contact which is having multiple Phone Numbers saved.
I need to do this as in Skype Application. When the User select a contact which is having multiple contacts, from the Contacts Book itself it should ask the User to choose the number. Please help me to do it.
I used this code to open the Contacts and allow the user to select a single contact, then parse the result to display the contact name, phone number and thumbnail photo. In the example below, the members mName, mPhoneNumber, and mContactImage are already defined.
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Start an activity to pick a single contact (ACTION_PICK)
Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
// Show only contacts with phone numbers
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
// Start the Contacts activity
startActivityForResult(intent, PICK_CONTACT);
}
});
Parse the results in onActivityResult().
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case PICK_CONTACT :
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
String[] projection = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Photo.PHOTO_THUMBNAIL_URI};
Cursor c = getActivity().getContentResolver().query(contactData, projection, null, null, null);
c.moveToFirst();
int nameIdx = c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int phoneNumberIdx = c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int photoIdx = c.getColumnIndex(ContactsContract.CommonDataKinds.Photo.PHOTO_THUMBNAIL_URI);
String name = c.getString(nameIdx);
String phoneNumber = c.getString(phoneNumberIdx);
String photo = c.getString(photoIdx);
if (photo == null) {
// If no photo then substitute a dummy image
mContactImage.setImageResource(R.drawable.ic_contact_picture);
} else {
// Display the contact photo
final Uri imageUri = Uri.parse(photo);
mContactImage.setImageURI(imageUri);
}
if (name == null) {
name = "No Name";
}
mName.setText(name);
mPhoneNumber.setText(phoneNumber);
c.close();
// Now you have the phone number
}
break;
}
}
I think this answers your question.

Android fetch email from contacts doesn't work

I am trying to create a button that opens up contacts and then when you select one contact it fetches the email and adds it to a field in the application.
I've been using the solution found here:
How to call Android contacts list AND Select one phone number from its details screen?
I have changed the code to select the email, but i still get the phone number.
The code is the following:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
Uri uri = data.getData();
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver().query(uri, new String[]{
ContactsContract.CommonDataKinds.Email.CONTACT_ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Email.ADDRESS},
null, null, null);
if (c != null && c.moveToFirst()) {
long number = c.getLong(0);
String type = c.getString(1);
String mail = c.getString(2);
showSelectedNumber(type, number, mail);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
public void showSelectedNumber(String number, long type, String email) {
Toast.makeText(this, type + ": " + number+ ": " + email, Toast.LENGTH_LONG).show();
}
EDIT:
The problem was on the initial query on the onClick call. I am posting the right function
private static final int CONTACT_PICKER_RESULT = 1001;
private static final String DEBUG_TAG = null;
public void doLaunchContactPicker(View view) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.CommonDataKinds.Email.CONTENT_TYPE);
startActivityForResult(intent, 1);
}
Sorry,I do not know why it still get the phone number. But , you can screen the results from contacts again by regular expression , if match to email address ,save and if not ,remove
I am sorry for my bad english!
Add a method like this:
private boolean checkMailAddress(String mailAddress){
final String MAIL_ADDR_REGEX = "([\\w-\\.\\\\+]+)#((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([\\w-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
return mailAddress.matches(MAIL_ADDR_REGEX);
}
and I think that you should use "while" , not "if":
while(c != null && c.moveToNext()) {
long number = c.getLong(0);
String type = c.getString(1);
String mail = c.getString(2);
if(checkMailAddress(mail)){
showSelectedNumber(type, number, mail);
}
}

Get Email ID and name from android inbuilt phone book?

I am trying to get name and email-id from Android inbuilt phone book into my page, I am able to get name, contact ID, phone number. but I am unable to get email ID from the Android phone book.
Code is:
public static final int PICK_CONTACT = 1;
#Override
button.setOnClickListener(new OnClickListener() {
public void onClick(View _view) {
Intent intent = new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
}
});
}
#Override
public void onActivityResult(int reqCode, int resCode, Intent data)
{
super.onActivityResult(reqCode, resCode, data);
switch(reqCode) {
case (PICK_CONTACT) : {
if (resCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
c.moveToFirst();
String name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
String name1 = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.HAS_PHONE_NUMBER));
String ContactID = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
if(Integer.parseInt(name1) == 1){
Cursor emails = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID+ " = " + ContactID, null, null);
TextView tv = (TextView)findViewById(R.id.selected_contact_textview);
TextView tv1 = (TextView)findViewById(R.id.selected_email_textview);
tv.setText(name);
tv1.setText(ContactID);
}
}
break;
}
}
Here I am able to get name and contact ID of a selected person from the phonebook. Now I want to get name and email ID of a selected person from phone book.
How can I achieve this?
You can get the email address of the contact directly using the contact id as follows :
String selection = ContactsContract.CommonDataKinds.Email.CONTACT_ID + " =? ";
String[] selectionArgs = new String[]{aContactId};
Cursor emailCursor = aContext.getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, selection, selectionArgs, null);
while (!emailCursor.isAfterLast())
{
emailString = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
// do something with email string
emailCursor.moveToNext();
}
emailCursor.close ();

Putting contact number into field

I have this code that has one button that let's me choose an entry from contacts, and passes that choesn contact to onActivityResult function. My question is how do I select data of that single contact when all that is passed is an Intent in data variable. That data variable, if converted to string shows something like "dat: content://contacts/people/4" so I see that selected contact is somehow passed, but what now? How to get that data?
And also all I found by googling was examples with deprecated class People, so I don't know how too use new classes.
public class HelloAndroid extends Activity {
private static final int CONTACT_ACTIVITY = 100;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button contactButton = (Button) findViewById(R.id.pick_contact_button);
contactButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Uri uri = Uri.parse("content://contacts/people");
Intent contacts_intent = new Intent(Intent.ACTION_PICK, uri);
startActivityForResult(contacts_intent, CONTACT_ACTIVITY);
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode){
case(CONTACT_ACTIVITY): {
if(resultCode == Activity.RESULT_OK) {
alertText(data.toString());
}
break;
}
}
}
}
This will get the cursor holding base contact data, and will loop through the phone numbers the contact has, can have multiple.
Uri uri = (Uri)data.toString();
Cursor cursor=ctx.getContentResolver().query(uri, null, null, null, null);
while (cursor.moveToNext()) {
String contactId = cursor.getString(cursor.getColumnIndex(
ContactsContract.Contacts._ID));
String hasPhone = cursor.getString(cursor.getColumnIndex(
ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (Boolean.parseBoolean(hasPhone)) {
// You know have the number so now query it like this
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,
null, null);
while (phones.moveToNext()) {
String phoneNumber = phones.getString(
phones.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
}
phones.close();
}
}

Categories

Resources