I can't display the contact name while dialing a call in Android.
Here is my code:
String callTo = "9999900000";
String callername="xxx";
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:"+ callTo));
String srvname=Context.TELEPHONY_SERVICE;
TelephonyManager tm=(TelephonyManager)getSystemService(srvname);
startActivity(callIntent);
For that you need to create a broadcast receiver and in OnReceive method check an OUTGOING CALL state and then get caller number from that and then create another method to check whether the contact exists in you mobile or not for that pass that contact number in the method.
Below is the code for Caller name broadcastReceiver
package com.example.user.caller;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.telephony.TelephonyManager;
import android.widget.Toast;
/**
* Created by Vinod Dirishala on 11/27/2016.
*/
public class MyReceiver extends BroadcastReceiver {
String phoneNumber;
String name;
#Override
public void onReceive(Context context, Intent intent) {
String action=intent.getAction();
Bundle extras=intent.getExtras();
if(action.equals("android.intent.action.PHONE_STATE")){
String state=extras.getString(TelephonyManager.EXTRA_STATE);
if(state.equals(TelephonyManager.EXTRA_STATE_RINGING)){
String incomingnumber=extras.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
String msg = "";
// String person = getCname(context,msg);
String names = getContactDisplayNameByNumber(incomingnumber,context);
// Toast.makeText(context,"Caller Name"+person,Toast.LENGTH_SHORT).show();
displayToast(context,"phone is ringing"+incomingnumber+ "calling you mr."+names);
Intent intent1 = new Intent(context,
MainActivity.class);
intent.putExtra("contactname", names); //<<< put sms text
context.startActivity(intent);
// displayToast(context,"phone is ringing"+person);
// displayToast(context,"Vinod your phone is ringing"+contacname);
}else if(state.equals(TelephonyManager.EXTRA_STATE_IDLE)){
Toast.makeText(context,"phone in idle",Toast.LENGTH_SHORT).show();
}else if(state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)){
Toast.makeText(context,"phone in offhook",Toast.LENGTH_SHORT).show();
}
}else if(action.equals("android.provider.Telephony.SMS_RECEIVED")){
displayToast(context,"SMS Recived");
}
}
private void displayToast(Context context,String msg){
Toast.makeText(context,msg,Toast.LENGTH_LONG).show();
}
public String getCname(Context context,String name)
{
ContentResolver cr=context.getContentResolver();
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println(" Phone Nuber.................."+phoneNumber);
// aa.add(name);
// aa.add(phoneNumber);
}
return name;
}
public String getContactDisplayNameByNumber(String number,Context context) {
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
name = "Incoming call from";
ContentResolver contentResolver = context.getContentResolver();
Cursor contactLookup = contentResolver.query(uri, null, null, null, null);
try {
if (contactLookup != null && contactLookup.getCount() > 0) {
contactLookup.moveToNext();
name = contactLookup.getString(contactLookup.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
// this.id =
// contactLookup.getString(contactLookup.getColumnIndex(ContactsContract.Data.CONTACT_ID));
// String contactId =
// contactLookup.getString(contactLookup.getColumnIndex(BaseColumns._ID));
}else{
name = "Unknown number";
}
} finally {
if (contactLookup != null) {
contactLookup.close();
}
}
return name;
}
}
to download code visit this link done by Vinod Dirishala
Related
I am trying to write an app that has two buttons - the first brings up a list of contacts and the second sends a message to the selected contact. I am able to select a contact using startActivityForResult and onActivityResult, but I cannot return the contact's number to my main code where it would be read by the second button's onClick method. When running the code below, I get the toast message with the phone number but when I try to send a message I get the "Please select a contact first" message. I don't know how to make the "phoneNumber" variable in onActivityResult to send it to "phoneNumber" in my main activity. Thanks!
package com.example.testa;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class AndroidAlarmService extends Activity {
private PendingIntent pendingIntent;
private static final int PICK_CONTACT_REQUEST = 0;
private static final Uri CONTACTS_CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
static String phoneNumber = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button contacts_button = (Button) findViewById(R.id.getContacts);
contacts_button.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
try {
Intent intent = new Intent(Intent.ACTION_PICK, CONTACTS_CONTENT_URI);
intent.setType(Phone.CONTENT_TYPE);
startActivityForResult(intent, PICK_CONTACT_REQUEST);
} catch (Exception e) {
Log.e("AAS", "Found an error in contacts button");
}
}
});
final Button send_button = (Button) findViewById(R.id.send_button);
send_button.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
final String yourtext = "my message";
Intent myIntent = new Intent(AndroidAlarmService.this, MyAlarmService.class);
if (phoneNumber == ""){
Toast.makeText(AndroidAlarmService.this, "Please select a contact first" , Toast.LENGTH_SHORT).show();
//This is the message I get
return;
}
myIntent.putExtra("phoneNumber", phoneNumber);
myIntent.putExtra("yourtext", yourtext);
pendingIntent = PendingIntent.getService(AndroidAlarmService.this, 0, myIntent, 0);
}});
}
#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.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE },
null, null, null);
if (c != null && c.moveToFirst()) {
String number = c.getString(0);
int type = c.getInt(1);
showSelectedNumber(type, number);
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
public void showSelectedNumber(int type, String number) {
Toast.makeText(this, type + ": " + number, Toast.LENGTH_LONG).show();
//this part is working
}
}
Change
String number = c.getString(0);
to
phoneNumber = c.getString(0);
This will store the phone number in the member variable rather than in a local variable. Now you can use this phoneNumber member variable in the click listener for your second button.
Note that phoneNumber == "" is an error. You should use equals() to compare String instances for equality.
I need some help for my project.
I made an android app that would search contacts, applications, and messaging within the device. The application and contacts are working, but I have a problem in messaging since it does not go to the conversation of the desired search message when you tap.
All I want is when you tap the search message it will go to the conversation. When I run my code it just goes to the conversation list instead of opening a specific conversation.
Here is the code in the message:
package com.android.searching.engines;
import java.util.List;
import android.content.ComponentName;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import com.android.searching.ContentManager.Results;
public class SmsEngine extends Engine {
public SmsEngine(Context context, String type) {
super(context, type);
if (sSmsIcon == null) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setType("vnd.android-dir/mms-sms");
PackageManager pm = context.getPackageManager();
List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
if (list != null && list.size() == 1) {
sSmsIcon = list.get(0).loadIcon(pm);
}
}
}
private static Drawable sSmsIcon = null;
private static String smsAll = "content://sms/";
#Override
protected void doSearch(Context context, Results results, String pattern, boolean isPresearch) {
String selection = null;
if (!pattern.equals("")) {
selection = "address like '%" + pattern + "%' or body like '%" + pattern + "%'";
}
final Uri smsUri = Uri.parse(smsAll);
Cursor cursor = context.getContentResolver().query(smsUri, null,
selection, null, "date desc");
if (cursor != null) {
int idNum = cursor.getColumnIndex("_id");
int addressNum = cursor.getColumnIndex("address");
int bodyNum = cursor.getColumnIndex("body");
while (cursor.moveToNext()) {
results.add(new SmsResult(null, cursor.getString(idNum), cursor.getString(addressNum), cursor.getString(bodyNum)));
}
cursor.close();
}
}
public class SmsResult extends Engine.IResult {
protected SmsResult(Drawable icon, String id, String address, String body) {
super(id, icon, address, body);
}
#Override
public Drawable getIcon() {
return sSmsIcon == null ? sDefaultIcon : sSmsIcon;
}
#Override
public void onClick(Context context) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setComponent(new ComponentName("com.android.mms",
"com.android.mms.ui.Conversation"));
intent.setClassName("com.android.mms", "com.android.mms.ui.ConversationList");
intent.setType("vnd.android-dir/mms-sms");
Uri uri = ContentUris.withAppendedId(Uri.parse("content://sms/conversations/"),
Long.parseLong(mId));
intent.setAction(Intent.ACTION_VIEW);
intent.setData(uri);
context.startActivity(intent);
}
}
}
Your response will be really helpful and appreciated.
Thank you.
all..i have made a demo in android in that i have opened intent of addressbook and in my "onActivityResult" i am binding Contact name to List,All is going well but problem is i want ,if 1 contact name isalready added it shouldnt be added again ,my code is as below:
main.java
package com.example.mycontactpicker;
import java.util.zip.Inflater;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
public Button add;
public TextView contact;
public LinearLayout list;
private static final int CONTACT_PICKER_RESULT = 1200;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
add = (Button) findViewById(R.id.add);
list = (LinearLayout) findViewById(R.id.list);
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, CONTACT_PICKER_RESULT);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case CONTACT_PICKER_RESULT:
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
String orgName = "";
String title = "";
String emailId = "";
String cNumber = "";
String zipCode = "";
if (c.moveToFirst()) {
// Fetch Contact Name
String DisplayName = c
.getString(c
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
System.out.println("==============Display name:::::::::;; "
+ DisplayName);
View inflateView;
inflateView = LayoutInflater.from(MainActivity.this)
.inflate(R.layout.contact_row, null, true);
contact = (TextView) inflateView.findViewById(R.id.contact);
contact.setText(DisplayName);
list.addView(inflateView);
Toast.makeText(getApplicationContext(), DisplayName,
Toast.LENGTH_LONG).show();
String hasPhone = c
.getString(c
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
String contactId = c.getString(c
.getColumnIndex(ContactsContract.Contacts._ID));
// long id = c.getLong(Integer.parseInt(contactId));
if (DisplayName.equals("") || DisplayName.equals(" ")) {
DisplayName = c
.getString(c
.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME_ALTERNATIVE));
System.out
.println("=============Display name:::::::::::outer side "
+ DisplayName);
}
}
}
}
}
}
pls help frends
To check if a contact name already exists in the address book you could add...
public boolean contactExists(String contact) {
if (contact != null) {
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext()) {
if (contact.equalsIgnoreCase(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)))) {
return true;
}
}
}
return false;
}
In my PhoneGap app, I am trying to get the native Android contact picker to launch so I can fetch some phone numbers.
I researched online and couldn't find much until I saw the ContactView plugin:
https://github.com/phonegap/phonegap-plugins/tree/master/Android/ContactView
When I set up the plugin according to the instructions, I encountered errors everywhere in its ContactView.java file. It seems that it is using a very old version of the plugin structure with ctx and other deprecated commands (e.g. startActivityForResult).
So I tried to convert it into a modern plugin by going through it line by line but I was too n00b and got stuck at about line 40 (inside the startContactActivity function). This is what I have so far:
package com.rearden;
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.util.Log;
public class ContactView extends CordovaPlugin {
private static final String TAG = "PickContactPlugin";
private static final int PICK_CONTACT = 1;
#Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
Log.d(TAG, "Inside ContactView plugin.");
JSONObject result = new JSONObject();
if (action.equals("") || action.equals("ContactView")) {
return startContactActivity();
} else {
Log.e(TAG, "Unknown action provided.");
result.put("error", "Unknown action provided.");
callbackContext.success(result);
return false;
}
}
public boolean startContactActivity() {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
//STUCK HERE
this.cordova.getActivity().startActivityForResult((Plugin) this, intent, PICK_CONTACT);
}
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
String name = null;
String number = null;
String email = null;
ContentResolver contentResolver = cordova.getActivity().getContentResolver();
switch (reqCode) {
case (PICK_CONTACT):
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = contentResolver.query(contactData, null, null, null, null);
if (c.moveToFirst()) {
String ContactID = c.getString(c
.getColumnIndex(ContactsContract.Contacts._ID));
String hasPhone = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (Integer.parseInt(hasPhone) == 1) {
Cursor phoneCursor = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ "='" + ContactID + "'", null,
null);
while (phoneCursor.moveToNext()) {
number = phoneCursor
.getString(phoneCursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
}
// get email address
Cursor emailCur = contentResolver.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + "='" + ContactID + "'", null,null);
while (emailCur.moveToNext()) {
// This would allow you get several email addresses
// if the email addresses were stored in an array
email = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
//String emailType = emailCur.getString(
// emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
}
emailCur.close();
name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
JSONObject contactObject = new JSONObject();
try {
contactObject.put("name", name);
contactObject.put("phone", number);
contactObject.put("email", email);
} catch (JSONException e) {
e.printStackTrace();
}
this.success(new PluginResult(PluginResult.Status.OK,
contactObject), this.callback);
}
}
break;
}
}
}
What I don't seem to be able to do is to find an equivalent for the "this.ctx.startActivityForResult" function.
I've already spent an entire day on this and it's starting to seem excessive, so I turn to you guys for help. Can it really be that hard to access the native contact picker?
The equivalent is this.ctx.getActivity().getContentResolver().query
The code below works in cordova 2.6.
package com.rearden;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
import org.apache.cordova.api.PluginResult.Status;
import android.util.Log;
public class ContactViewPlugin extends Plugin {
private static final int PICK_CONTACT = 1;
private String callback;
#Override
public PluginResult execute(String action, JSONArray args, String callbackId) {
startContactActivity();
PluginResult mPlugin = new PluginResult(PluginResult.Status.NO_RESULT);
mPlugin.setKeepCallback(true);
this.callback = callbackId;
return mPlugin;
}
public void startContactActivity() {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
this.ctx.startActivityForResult((Plugin) this, intent, PICK_CONTACT);
}
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
String name = null;
String number = null;
String email = null;
switch (reqCode) {
case (PICK_CONTACT):
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = this.ctx.getActivity().getContentResolver().query(contactData, null, null, null, null);
if (c.moveToFirst()) {
String ContactID = c.getString(c
.getColumnIndex(ContactsContract.Contacts._ID));
String hasPhone = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (Integer.parseInt(hasPhone) == 1) {
Cursor phoneCursor = this.ctx.getActivity().getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ "='" + ContactID + "'", null,
null);
while (phoneCursor.moveToNext()) {
number = phoneCursor
.getString(phoneCursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
}
// get email address
Cursor emailCur = this.ctx.getActivity().getContentResolver().query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + "='" + ContactID + "'", null,null);
while (emailCur.moveToNext()) {
// This would allow you get several email addresses
// if the email addresses were stored in an array
email = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
//String emailType = emailCur.getString(
// emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
}
emailCur.close();
name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
JSONObject contactObject = new JSONObject();
try {
contactObject.put("name", name);
contactObject.put("phone", number);
contactObject.put("email", email);
} catch (JSONException e) {
e.printStackTrace();
}
this.success(new PluginResult(PluginResult.Status.OK,
contactObject), this.callback);
}
}
break;
}
}
}
I also changed the JS file.
var ContactViewPlugin = function() {
};
ContactViewPlugin.prototype.show = function(successCallback, failureCallback) {
console.log('calling *** show');
return cordova.exec(successCallback,
failureCallback,
'ContactViewPlugin',
'show',
[]);
};
if(!window.plugins) {
window.plugins = {};
}
if (!window.plugins.contactViewPlugin) {
window.plugins.contactViewPlugin = new ContactViewPlugin();
}
Do not forget to add the plugin to the config.xml list.
in cordova 3.0.0
this worked for me
this.cordova.startActivityForResult((CordovaPlugin) this, intent, PICK_CONTACT);
I want to fetch the photo of the contact while a user enters number.By using phone number i am getting users name but for image it shows null.
my code is following :
public class NewtempActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ImageView img = (ImageView) findViewById(R.id.imageView1);
final EditText edit = (EditText) findViewById(R.id.editText1);
TextView txt = (TextView) findViewById(R.id.textView1);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Girish", "Clicked");
String name = getContactNameFromNumber(edit.getText()
.toString(), getApplicationContext());
img.setImageBitmap(BitmapFactory
.decodeFile(ContactsContract.PhoneLookup._ID));
Log.d("Girish",
""
+ (BitmapFactory
.decodeFile(ContactsContract.PhoneLookup._ID)));
Toast.makeText(getApplicationContext(), name, name.length())
.show();
}
});
}
public String getContactNameFromNumber(String number, Context ctx) {
/*
* // define the columns I want the query to return String[] projection
* = new String[] { ContactsContract.PhoneLookup.DISPLAY_NAME,
* ContactsContract.PhoneLookup.NUMBER, };
*/
// encode the phone number and build the filter URI
Uri contactUri = Uri.withAppendedPath(
ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(number));
// query time
// Cursor c = ctx.getContentResolver().query( contactUri, projection,
// null,
Cursor c = ctx.getContentResolver().query(contactUri, null, null, null,
null);
// if the query returns 1 or more results
// return the first result
if (c.moveToFirst()) {
String name = c.getString(c
.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
return name;
}
// return the original number if no match was found
return number;
}
public static Bitmap loadContactPhoto(ContentResolver cr, long id) {
Uri uri = ContentUris.withAppendedId(
ContactsContract.Contacts.CONTENT_URI, id);
InputStream input = ContactsContract.Contacts
.openContactPhotoInputStream(cr, uri);
// InputStream input = ContactsContract.Contacts.Photo
if (input == null) {
return null;
}
return BitmapFactory.decodeStream(input);
}
public InputStream openPhoto(long contactId) {
Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI,
contactId);
Uri photoUri = Uri.withAppendedPath(contactUri,
Contacts.Photo.CONTENT_DIRECTORY);
Cursor cursor = getContentResolver().query(photoUri, null, null, null,
null);
if (cursor == null) {
return null;
}
try {
if (cursor.moveToFirst()) {
byte[] data = cursor.getBlob(0);
if (data != null) {
return new ByteArrayInputStream(data);
}
}
} finally {
cursor.close();
}
return null;
}
}
please suggest me where i am doing wrong.I have added read contact permission also
by going through your code i came to know like You are trying to get the contact name from the number. and using that you want the contact image.. but you never called the functions which you made for the contact pic..:).. so what you can do is take id from the contact number and take photo on that id. so you will get the photo for the number..
package com.android.SampleProject;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
public class NewtempActivity extends Activity {
private long id;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ImageView img = (ImageView) findViewById(R.id.imageView1);
final EditText edit = (EditText) findViewById(R.id.editText1);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d("Girish", "Clicked");
String name = getContactNameFromNumber(edit.getText()
.toString(), getApplicationContext());
img.setImageBitmap(BitmapFactory
.decodeFile(ContactsContract.PhoneLookup._ID));
img.setImageBitmap(loadContactPhoto(getContentResolver(), id));
Log.d("Girish",
""
+ (BitmapFactory
.decodeFile(ContactsContract.PhoneLookup._ID)));
Toast.makeText(getApplicationContext(), name, name.length())
.show();
}
});
}
public String getContactNameFromNumber(String number, Context ctx) {
/*
* // define the columns I want the query to return String[] projection
* = new String[] { ContactsContract.PhoneLookup.DISPLAY_NAME,
* ContactsContract.PhoneLookup.NUMBER, };
*/
// encode the phone number and build the filter URI
Uri contactUri = Uri.withAppendedPath(
ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(number));
// query time
// Cursor c = ctx.getContentResolver().query( contactUri, projection,
// null,
Cursor c = ctx.getContentResolver().query(contactUri, null, null, null,
null);
// if the query returns 1 or more results
// return the first result
if (c.moveToFirst()) {
String name = c.getString(c
.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
id = c.getLong(c
.getColumnIndex(ContactsContract.PhoneLookup._ID));
return name;
}
// return the original number if no match was found
return number;
}
public static Bitmap loadContactPhoto(ContentResolver cr, long id) {
Uri uri = ContentUris.withAppendedId(
ContactsContract.Contacts.CONTENT_URI, id);
InputStream input = ContactsContract.Contacts
.openContactPhotoInputStream(cr, uri);
// InputStream input = ContactsContract.Contacts.Photo
if (input == null) {
return null;
}
return BitmapFactory.decodeStream(input);
}
public InputStream openPhoto(long contactId) {
Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI,
contactId);
Uri photoUri = Uri.withAppendedPath(contactUri,
Contacts.Photo.CONTENT_DIRECTORY);
Cursor cursor = getContentResolver().query(photoUri, null, null, null,
null);
if (cursor == null) {
return null;
}
try {
if (cursor.moveToFirst()) {
byte[] data = cursor.getBlob(0);
if (data != null) {
return new ByteArrayInputStream(data);
}
}
} finally {
cursor.close();
}
return null;
}
}