I have create custom incoming call screen that can current show the name and phone number of an incoming call. If the contact has a profile pic set that image should display in the ImageView. I calls the below method, and assigns the picture to the ImageView. The problem is that the else statement is always executed:
public static Uri getPhotoUri(String savedNumber, Context context) {
try {
Cursor cur = context
.getContentResolver()
.query(
ContactsContract.Data.CONTENT_URI,
null,
ContactsContract.Data.CONTACT_ID
+ "="
+ getContactIDFromNumber(savedNumber,
context)
+ " AND "
+ ContactsContract.Data.MIMETYPE
+ "='"
+ ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE
+ "'", null, null);
if (cur != null) {
if (!cur.moveToFirst()) {
return null; // no photo
}
} else {
return null; // error in cursor process
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI,
getContactIDFromNumber(savedNumber, context));
return Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
}
public static int getContactIDFromNumber(String contactNumber,Context context) {
int phoneContactID = 0;
Cursor contactLookupCursor = context.getContentResolver().query(
Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(contactNumber)),
new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup._ID},
null, null, null);
try {
contactLookupCursor.moveToFirst();
while (contactLookupCursor.moveToNext()) {
phoneContactID = contactLookupCursor.getInt(contactLookupCursor
.getColumnIndexOrThrow(ContactsContract.PhoneLookup._ID));
}
} finally {
contactLookupCursor.close();
}
return phoneContactID;
}
IncomingActivity:
#Override
protected void onResume() {
super.onResume();
callerNumber.setText(savedNumber);
callerName.setText(CommonMethods.getCallerName(savedNumber, this));
callerImageUri = CommonMethods.getPhotoUri(savedNumber, this);
if (callerImageUri != null) {
callerImage.setImageURI(callerImageUri);
} else {
callerImage.setImageResource(R.drawable.contact_default);
}
}
Does anyone have any ideas as to why "callerInamgeUri" is remaining null?
Related
I would like to check whether a record exists or not.If exist , i want to add the quantity.
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String code = etCode.getText().toString();
String product = etProduct.getText().toString();
String qty = etQty.getText().toString();
try {
if (isExist(code)) {
rQty = Integer.parseInt(rQty + etQty.getText().toString());
} else {
myDB.addData(code, product, Integer.parseInt(qty));
Toast.makeText(MainActivity.this, "Data Inserted", Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_LONG).show();
}
}
});
}
public boolean isExist(String code) {
boolean result;
SQLiteDatabase db = myDB.getReadableDatabase();
try {
Cursor cursor = db.rawQuery("SELECT QTY FROM users_data WHERE CODE " + code + "'", null);
if (cursor.getCount() > 0 ){
while (cursor.moveToFirst()){
rQty = cursor.getInt(cursor.getColumnIndex("QTY"));
}
result = true;
}else {
result = false;
}
}
catch (Exception ex){
result = false;
}
return result;
}
}
Here is the code.if insert the same code of item , the data become duplicate and it not add the quantity for the same code.Please help me to solve this problem .
There are multiple errors and bugs in your code. One problem is this code
rQty = Integer.parseInt(rQty + etQty.getText().toString());
It won't add qQty with input quantity. because here strings concatenated.
You have to use
rQty += Integer.parseInt (qty);
Second one is your sqlite query is not right and it is incomplete
so change
Cursor cursor = db.rawQuery("SELECT QTY FROM users_data WHERE CODE " + code + "'", null);
to
Cursor cursor = db.rawQuery("SELECT QTY FROM users_data WHERE CODE = '" + code + "'", null);
Try below code
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String code = etCode.getText().toString();
String product = etProduct.getText().toString();
String qty = etQty.getText().toString();
try {
if (isExist(code)) {
rQty += Integer.parseInt (qty);
} else {
myDB.addData(code, product, Integer.parseInt(qty));
Toast.makeText(MainActivity.this, "Data Inserted", Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_LONG).show();
}
}
});
}
public boolean isExist(String code) {
boolean result;
SQLiteDatabase db = myDB.getReadableDatabase();
try {
Cursor cursor = db.rawQuery("SELECT QTY FROM users_data WHERE CODE = '" + code + "'", null);
if (cursor.getCount() > 0 ){
while (cursor.moveToFirst()){
rQty = cursor.getInt(cursor.getColumnIndex("QTY"));
}
result = true;
}else {
result = false;
}
}
catch (Exception ex){
result = false;
}
return result;
}
I'm trying to add events to the basic Calendar by using Intent. I think it's working fine but when I try to read it I always got an exception. java.lang.IllegalArgumentException: Unknown URL content://com.android.calendar/
If I'm using this URL: "content://com.android.calendar/calendars" my ReadFromCalendar() method shows me two IDs but non of them is correct and if I add a new event the number of the IDs doesn't change. So I guess it's not the correct URL.
If I'm using this URL:"content://com.android.calendar/" + "events" then I got IDs from the lowest value to the highest value. When I add a new event the IDs value growing with +1 no matter what set to ID.
So the quesiton is how can I get the correct eventID-s from my calendar? Am I using the wrong URL?
Here is the what I'm using:
public class CalendarUtils {
static int numC = 0;
private final Activity activity;
public CalendarUtils(Activity activity) {
this.activity = activity;
}
public void InsertAnEvent() {
numC++;
long event_id = numC;
Calendar calendarEvent = Calendar.getInstance();
Intent i = new Intent(Intent.ACTION_EDIT);
i.setType("vnd.android.cursor.item/event");
i.putExtra("beginTime", calendarEvent.getTimeInMillis());
i.putExtra("allDay", true);
i.putExtra("_id", event_id);
i.putExtra("rule", "FREQ=YEARLY");
i.putExtra("endTime", calendarEvent.getTimeInMillis() + 60 * 60 * 1000);
i.putExtra("title", "Eskuvo");
activity.startActivity(i);
}
public void ReadFromCalendar() {
Uri EVENTS_URI = Uri.parse(getCalendarUriBase(activity));
ContentResolver cr = activity.getContentResolver();
Cursor cursor;
cursor = cr.query(EVENTS_URI, null, null, null, null);
while (cursor.moveToNext()) {
long id = cursor.getLong(cursor.getColumnIndex("_id"));
Log.d("TAG", "ID: " + id);
if (id == 63) {
Toast.makeText(activity, "győztél", Toast.LENGTH_SHORT).show();
}
}
cursor.close();
}
public static String getCalendarUriBase(Activity activity) {
String calendarUriBase = null;
Uri calendars = Uri.parse("content://calendar/calendars");
Cursor managedCursor = null;
try {
managedCursor = activity.getContentResolver().query(calendars,
null, null, null, null);
} catch (Exception e) {
}
if (managedCursor != null) {
calendarUriBase = "content://calendar/";
} else {
calendars = Uri.parse("content://com.android.calendar/calendars");
try {
managedCursor = activity.getContentResolver().query(calendars,
null, null, null, null);
} catch (Exception e) {
}
if (managedCursor != null) {
calendarUriBase = "content://com.android.calendar/";
}
}
return calendarUriBase;
}
}
I go through the addressbook and try to get all contacts' photos which are not null.
I'm using android API8, so i cannot query for image_uri.
given photo_id (API 5), how can i get the photo bitmap?
here is my query:
public final static String[] PROJECTION2 = new String[] {
ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.PHOTO_ID
};
public static void fillAddressBookData() {
String sHash = null;
String where = ContactsContract.Contacts.IN_VISIBLE_GROUP + "= ? ";
String[] selectionArgs = new String[] {"1"};
Cursor cursor =
AppService
.getAppContext()
.getContentResolver()
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PROJECTION2, where,
selectionArgs, null);
...
try this:
private void GetImageByPhoneNumber(String number)
{
Uri uri1 = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(number));
Cursor test = getContentResolver().query(uri1,
new String[] { "photo_uri" }, null, null,
null);
if (test.getCount() > 0) {
test.moveToFirst();
Uri photoUri = Uri.parse(test.getString(test
.getColumnIndexOrThrow("photo_uri"))));
Bitmap image = getPhoto(context , photoUri);
}
test.close();
}
and getPhoto:
public static Bitmap getPhoto(Context context , Uri uri){
Bitmap bm = null;
try {
bm = BitmapFactory.decodeStream(context.getContentResolver()
.openInputStream(uri));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (bm == null) {
bm = BitmapFactory.decodeResource(context.getResources(),
R.drawable.default_user_avatar);
}
return bm;
}
Try the next code snippet, it should do the trick
public Uri getPhotoUri(long contactId) {
ContentResolver contentResolver = getContentResolver();
try {
Cursor cursor = contentResolver
.query(ContactsContract.Data.CONTENT_URI,
null,
ContactsContract.Data.CONTACT_ID
+ "="
+ contactId
+ " AND "
+ ContactsContract.Data.MIMETYPE
+ "='"
+ ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE
+ "'", null, null);
if (cursor != null) {
if (!cursor.moveToFirst()) {
return null; // no photo
}
} else {
return null; // error in cursor process
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
Uri person = ContentUris.withAppendedId(
ContactsContract.Contacts.CONTENT_URI, contactId);
return Uri.withAppendedPath(person,
ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
}
I am new to Android and Java and this week I've been doing a self-taught crash course. So far what I've learned has not been too complicated as I've already built a number of years of coding experience. So, background history out of the way, onto my question.
The below code is two functions I wrote to take an image ID from a database and parse the correct Uri which I can then use to upload the photo to a website. So could you kind folks look over my code and let me know if I'm doing a terrible job or if I am heading in the right direction or even if there is a better/native way to do what I need.
Also, note: the below code does work. I just don't know if it is the right way to do it.
Thanks!
// Usage Map idPath = ImageIdPathFetcher.getRealIdPathFromID(getApplicationContext(), Integer.valueOf(image_id));
public static Map getRealIdPathFromID(Context context, Integer id) {
Map<String,String> idPath = new HashMap<String, String>();
Uri external_images_uri = MediaStore.Images.Media.getContentUri("external");
Uri internal_images_uri = MediaStore.Images.Media.getContentUri("internal");
// initialize uri
Uri uri = external_images_uri;
String ext_img_uri = external_images_uri.toString()+"/"+id;
String int_img_uri = internal_images_uri.toString()+"/"+id;
if(check_uri(context, ext_img_uri))
{
uri = Uri.parse(ext_img_uri);
}else if(check_uri(context, int_img_uri))
{
uri = Uri.parse(int_img_uri);
}else {
idPath.put("id", "");
idPath.put("path", "");
return idPath;
}
String[] proj = { Media.DATA, Media._ID };
Cursor cursor = context.getContentResolver().query(uri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(Media.DATA);
cursor.moveToFirst();
String filepath = cursor.getString(column_index);
idPath.put("id", id.toString());
idPath.put("path", filepath);
return idPath;
}
public static boolean check_uri(Context context, String uri)
{
try{
ContentResolver cr = context.getContentResolver();
String[] projection = {MediaStore.MediaColumns.DATA};
Cursor cur = cr.query(Uri.parse(uri), projection, null, null, null);
if(cur != null)
{
cur.moveToFirst();
String filePath = cur.getString(0);
if(! new File(filePath).exists()){
return false;
}
} else {
return false;
}
} catch (Exception e)
{
return false;
}
return true;
}
This is what I use
public static Uri getImageContentUri(Context context, File imageFile) {
String filePath = imageFile.getAbsolutePath();
Cursor cursor = context.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Images.Media._ID},
MediaStore.Images.Media.DATA + "=? ",
new String[]{filePath}, null);
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
return Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, String.valueOf(id));
}
} finally {
cursor.close();
}
}
cursor = context.getContentResolver().query(
MediaStore.Images.Media.INTERNAL_CONTENT_URI,
new String[]{MediaStore.Images.Media._ID},
MediaStore.Images.Media.DATA + "=? ",
new String[]{filePath}, null);
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
return Uri.withAppendedPath(MediaStore.Images.Media.INTERNAL_CONTENT_URI, String.valueOf(id));
}
} finally {
cursor.close();
}
}
return null;
}
It is possible to query both internal and external MediaStore database also with MergeCursor:
String myIdImgStr = "123"; // the unique ID of the image in the MediaStore
ContentResolver contentResolver = this.getContext().getContentResolver();
String [] proj = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
MergeCursor cursor = new MergeCursor(new Cursor[] {
MediaStore.Images.Media.query(contentResolver,
Uri.parse(MediaStore.Images.Media.INTERNAL_CONTENT_URI + "/" + myIdImgStr),
proj),
MediaStore.Images.Media.query(contentResolver,
Uri.parse(MediaStore.Images.Media.EXTERNAL_CONTENT_URI + "/" + myIdImgStr),
proj)
});
if(cursor.getCount() == 1) {
cursor.moveToFirst();
String filepath = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
}
Im using this code to set a picture from a contact's phonenumber.
From the phonenumber i get a contact ID, and from the ID i can get a photo URL.
Im trying to set a picture in the imageview with: mPhotoView.setImageURI(uri);
But it wont work. I've debugged and the URL does NOT equal null.
The URL contains the following: content://com.android.contacts/contacts/502/photo
Does anyone know how to fix this?
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView mPhotoView = (ImageView) findViewById(R.id.imageView1);
Uri uri = getPhotoUri(Long.parseLong(fetchContactIdFromPhoneNumber(YOUR_PHONENUMBER))); //Set a number for yourself!
if (uri != null) {
mPhotoView.setImageURI(uri);
} else {
mPhotoView.setImageResource(R.drawable.ic_launcher);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public String fetchContactIdFromPhoneNumber(String phoneNumber) {
Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(phoneNumber));
Cursor cursor = this.getContentResolver().query(uri,
new String[] { PhoneLookup.DISPLAY_NAME, PhoneLookup._ID },
null, null, null);
String contactId = "";
if (cursor.moveToFirst()) {
do {
contactId = cursor.getString(cursor
.getColumnIndex(PhoneLookup._ID));
} while (cursor.moveToNext());
}
return contactId;
}
public Uri getPhotoUri(long contactId) {
ContentResolver contentResolver = getContentResolver();
try {
Cursor cursor = contentResolver
.query(ContactsContract.Data.CONTENT_URI,
null,
ContactsContract.Data.CONTACT_ID
+ "="
+ contactId
+ " AND "
+ ContactsContract.Data.MIMETYPE
+ "='"
+ ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE
+ "'", null, null);
if (cursor != null) {
if (!cursor.moveToFirst()) {
return null; // no photo
}
} else {
return null; // error in cursor process
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
Uri person = ContentUris.withAppendedId(
ContactsContract.Contacts.CONTENT_URI, contactId);
return Uri.withAppendedPath(person,
ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
}
}