I'm trying to do an application which is sending SMS, and MMS, so I need to retrieve the phone number and eventually an image.
My problem is, if I only the PICK_CONTACT case in onActivityResult, it's working fine, I got my contact phone number.
But if I'm adding the second part, PICK_IMAGE, when I'm clicking on my contact, I got a :
java.lang.IllegalArgumentException: Invalid column _data
But I can still taking images without any problems..
Both intent call
private static final int PICK_CONTACT = 3;
private static final int PICK_IMAGE = 4;
protected void onCreate(Bundle savedInstanceState) {
...
}
public void addImage() {
Intent choosePictureIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(choosePictureIntent,PICK_IMAGE );
}
public void addContact(){
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
}
onActivityResult Code
public void onActivityResult(int reqCode, int resultCode, Intent data){
super.onActivityResult(reqCode, resultCode, data);
Uri contactData = data.getData();
switch(reqCode) {
case (PICK_CONTACT):
if (resultCode == Activity.RESULT_OK) {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
if (cur.moveToFirst()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
while (pCur.moveToNext()) {
phone = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
etPhoneNo.setText(phone);
}
pCur.close();
}
}
case (PICK_IMAGE) :
if (resultCode == Activity.RESULT_OK) {
try {
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = true;
bmpFactoryOptions.inSampleSize = 2;
bmpFactoryOptions.inJustDecodeBounds = false;
Bitmap bmp = BitmapFactory.decodeStream(getContentResolver().openInputStream(contactData), null, bmpFactoryOptions);
imageView.setImageBitmap(bmp);
} catch (FileNotFoundException e) {
Log.v("ERROR", e.toString());
}
ContentResolver cr = getContentResolver();
String [] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = cr.query(contactData, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
image_path = cursor.getString(column_index);
}
}
}
How can I resolve that?
I actually solved it ..
I just forgot break; :)
Related
I'm trying to get a Bitmap from a video which I get from the device's gallery or the camera, but when I call this, I'm getting a null Bitmap:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri uri = data.getData();
if (requestCode == REQUEST_VIDEO_CAPTURE && resultCode == RESULT_OK) {
Uri videoUri = data.getData(); // -> content://com.android.providers.media.documents/document/video%3A76
// This returns null
Bitmap thumbnailVideo = ThumbnailUtils.createVideoThumbnail(videoUri.toString(), MediaStore.Video.Thumbnails.MICRO_KIND);
media1.setImageBitmap(thumbnailVideo);
}
I also tried using this, but it stills returns a null value:
String path = uri.getPath(); // -> /document/video:76
Bitmap thumbnailVideo = ThumbnailUtils.createVideoThumbnail(path , MediaStore.Video.Thumbnails.MICRO_KIND);
And the last thing I tried is this code, but as before, it doesn't work:
String[] filePathColumn = {MediaStore.Video.Media.DATA};
Cursor cursor = this.getContentResolver().query(uri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Bitmap thumbnailVideo = ThumbnailUtils.createVideoThumbnail(picturePath, MediaStore.Video.Thumbnails.MICRO_KIND);
What am I doing wrong? I tried different solutions from Stackoverflow but none of them seem to work for me.
I found a way to make this work.
try {
Bitmap thumbnailVideo;
if (Build.VERSION.SDK_INT < 19) {
thumbnailVideo = ThumbnailUtils.createVideoThumbnail(getRealPathFromURIForVideoAPI18(videoUri), MediaStore.Video.Thumbnails.MICRO_KIND);
}
else {
thumbnailVideo = ThumbnailUtils.createVideoThumbnail(getRealPathFromURIForVideoAPI19(videoUri), MediaStore.Video.Thumbnails.MICRO_KIND);
}
setThumbnail(thumbnailVideo);
} catch (Exception ex) {
ex.printStackTrace();
}
// API 18 or less (Android 4.3)
#SuppressLint("NewApi")
public String getRealPathFromURIForVideoAPI18(Uri contentUri) {
String[] proj = {MediaStore.Images.Media.DATA};
String result = null;
CursorLoader cursorLoader = new CursorLoader(this, contentUri, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
result = cursor.getString(column_index);
cursor.close();
}
return result;
}
// API 19 or higher (>Android 4.4 Kitkat)
#SuppressLint("NewApi")
private String getRealPathFromURIForVideoAPI19(Uri selectedVideoUri) {
String wholeID = DocumentsContract.getDocumentId(selectedVideoUri);
String id = wholeID.split(":")[1];
String[] column = { MediaStore.Video.Media.DATA };
String sel = MediaStore.Video.Media._ID + "=?";
Cursor cursor = getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, column, sel, new String[]{ id }, null);
String filePath = "";
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
return filePath;
}
I try to select multiple images from photo gallery and save it in my custom folder on sdCard.
I wrote some code but i have nullPintException
this is a my source
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), PICK_FROM_GALLERY);
and this is OnActivityResultCode
if(data!=null)
{
ClipData clipData = data.getClipData();
for (int i = 0; i < clipData.getItemCount(); i++)
{
Uri selectedImage = clipData.getItemAt(i).getUri();
if (selectedImage != null) {
mCurrentPhotoPath = getRealPathFromURI(selectedImage);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, options);
// bitmap=getResizedBitmap(bitmap,1280,720);
String partFilename = currentDateFormat();
if (bitmap != null) {
SaveImage(bitmap, partFilename);
}
}
}
public String getRealPathFromURI(Uri uri) {
Cursor cursor = CarRecieveActivity.this.getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
private void SaveImage(Bitmap finalBitmap,String fileName) {
File myDir = new File(rootDirectory + "/"+vinNumber.getText().toString());
myDir.mkdirs();
String fname = fileName+".jpg";
File file = new File (myDir, fname);
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
this is my source .i have two errors.
first when i click only one image in my gallery clipData is null and second,when i choose multiple images from gallery and click ok button i have this error
java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it
error is in this function getRealPathFromURI()
how i can solve both problems?
thanks
Select images from device
//Uri to store the image uri
private List<Uri> filePath;
public String path[];
public static List<ImageBeen> listOfImage;
//Image request code
private int PICK_IMAGE_REQUEST = 1;
private int PICK_IMAGE_REQUEST_MULTI = 2;
// select multiple image
private void pickImages() {
filePath = new ArrayList<>();
listOfImage = new ArrayList<>();
Intent intent;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST_MULTI);
}else {
intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
}
Activity result
//handling the image chooser activity result
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST_MULTI && resultCode == RESULT_OK && data != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
ClipData imagesPath = data.getClipData();
if (imagesPath != null) {
path = new String[imagesPath.getItemCount()];
for (int i = 0; i < imagesPath.getItemCount(); i++) {
filePath.add(imagesPath.getItemAt(i).getUri());
path[i] = getPath(imagesPath.getItemAt(i).getUri());
ImageBeen imageBeen = new ImageBeen(imagesPath.getItemAt(i).getUri());
imageBeen.setPath(path[i]);
listOfImage.add(imageBeen);
initViewPager();
}
}else {
path = new String[1];
path[0] = getPath(data.getData());
ImageBeen imageBeen = new ImageBeen(data.getData());
imageBeen.setPath(path[0]);
listOfImage.add(imageBeen);
initViewPager();
}
} else if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null) {
path = new String[1];
path[0] = getPath(data.getData());
ImageBeen imageBeen = new ImageBeen(data.getData());
imageBeen.setPath(path[0]);
listOfImage.add(imageBeen);
initViewPager();
}
}
genarate images path using Image URI
//method to get the file path from uri
public String getPath(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
String path = null;
if(cursor!=null) {
if (cursor.moveToFirst()) {
String document_id = cursor.getString(0);
document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
cursor.close();
cursor = getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
cursor.moveToFirst();
path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
return path;
}
}
return path;
}
This is image bean where stored image URI and Image path
public class ImageBeen {
private Uri fileUri;
private String path;
public ImageBeen(Uri fileUri)
{
this.fileUri=fileUri;
}
public String getPath() {
return path;
}
public void setPath(String path)
{
this.path=path;
}
public Uri getFileUri() {
return fileUri;
}
}
For display image use Picasso
compile 'com.squareup.picasso:picasso:2.5.2'
Picasso.with(context)
.load(imageBeen.getFileUri())
.placeholder(R.drawable.not_vailable)
.error(R.drawable.not_vailable)
.into(holder.image);
I'm trying to get a contact from my contact list in my application:
public void selecionar_contato(View view) {
Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
startActivityForResult(intent, CONTACT_PICKER_RESULT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case CONTACT_PICKER_RESULT:
Uri dados = data.getData();
Cursor c = getContentResolver().query(dados, new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE }, null, null, null);
if(c.moveToFirst()){
String num = c.getString(0);
int type = c.getInt(1);
mostarToast(type,num);
}
break;
}
} else {
// gracefully handle failure
Log.w("Erro", "Warning: ac");
}
}
private void mostarToast(int type, String num) {
Toast.makeText(this, type + ": " + num, Toast.LENGTH_LONG).show();
}
But when i select the contact, my app crashes:
09-21 17:44:40.897: E/AndroidRuntime(17432): FATAL EXCEPTION: main
09-21 17:44:40.897: E/AndroidRuntime(17432): Process: com.example.pacixmobile, PID: 17432
09-21 17:44:40.897: E/AndroidRuntime(17432): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1001, result=-1, data=Intent { dat=content://com.android.contacts/contacts/lookup/298i107/602 flg=0x1 }} to activity {com.example.pacixmobile/com.example.pacixmobile.CadastroActivity}: java.lang.IllegalArgumentException: Invalid column data1
09-21 17:44:40.897: E/AndroidRuntime(17432): at android.app.ActivityThread.deliverResults(ActivityThread.java:3551)
I have to overwrite the onActivityResult method right? What am i missing?
The columns that you request are not directly available for the Uri you are using. You have picked a contact. You have not picked a phone number. A contact may have zero, one, or many phone numbers.
Given a Uri picked from ContactsContract.Contacts, you can retrieve columns available on ContactsContract.Contacts.
I have this in one activity and it's working fine, tested in phones and tablets.
I first get the selected contatct then her/his phone number. I need a mobile number if it's exists, also it's 9 digits (spanish number) removing the +34 or whatever country code it has.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
// super.onActivityResult(requestCode, resultCode, intent);
if (requestCode != 0x10 || resultCode != RESULT_OK)
{
super.onActivityResult(requestCode, resultCode, intent);
return;
}
Cursor cursor = null;
Uri contactUri = intent.getData();
long contactId = -1;
// get display name from the contact
try
{
cursor = getContentResolver().query(contactUri,
new String[] { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME }, null, null,
null);
if (cursor.moveToFirst())
{
String name = cursor.getString(1);
contactId = cursor.getLong(0);
etNombre.setText(name);
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (cursor != null)
{
cursor.close();
cursor = null;
}
}
// do we have a valid contact ID?
if (contactId == -1) return;
// get all phone numbers with type from the contact
try
{
String tmpPhone = "";
boolean itsDone = false, gotPhone = false;
cursor = getContentResolver().query(Phone.CONTENT_URI, new String[] { Phone.TYPE, Phone.NUMBER },
Phone.CONTACT_ID + "=" + contactId, null, null);
// Pick up the first phone number
if (cursor.moveToFirst())
{
tmpPhone = cursor.getString(1);
itsDone = cursor.getInt(0) == Phone.TYPE_MOBILE;
gotPhone = true;
// if Not a mobile, search others numbers
if (!itsDone)
{
while (cursor.moveToNext())
{
if (cursor.getInt(0) == Phone.TYPE_MOBILE)
{
itsDone = true;
tmpPhone = cursor.getString(1);
break;
}
}
}
}
if (gotPhone)
{
int len = tmpPhone.length();
if (len > 9)
{
tmpPhone = parsePhone(tmpPhone);
len = tmpPhone.length();
if (len > 9)
tmpPhone = tmpPhone.substring(len - 9, len);
}
etTelefono.setText(tmpPhone);
etJornada.requestFocus();
}
else etTelefono.requestFocus();
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (cursor != null)
{
cursor.close();
}
}
}
void cogerContactos()
{
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, 0x10);
}
This question already has answers here:
Android contacts Display Name and Phone Number(s) in single database query?
(3 answers)
Closed 8 years ago.
I have started a new intent activity for result
Code:
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, Phone.CONTENT_URI);
startActivityForResult(contactPickerIntent, 1);
And now I want to get the phone and number:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if(resultCode == RESULT_OK){
Uri contactUri = data.getData();
String[] pN = {Phone.NUMBER};
String[] pNa = {Phone.CONTACT_ID};//idk
Cursor cP = getContentResolver().query(contactUri, pN, null, null, null);
cP.moveToFirst();
Cursor cPa = getContentResolver().query(contactUri, pNa, null, null, null);
cPa.moveToFirst();
int numc = cP.getColumnIndex(Phone.NUMBER);
String num = cP.getString(numc);
int namec = cPa.getColumnIndex(Phone.CONTACT_ID);//idk
String name = cPa.getString(namec);//idk
Log.i("", name);
}
if (resultCode == RESULT_CANCELED) {
//DO OTHER STUFF
}
}
}
The phone number is fine BUT I fail to retrieve the contact's GIVEN NAME!
Uri uri = data.getData();
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
cursor.moveToFirst();
number = cursor.getString(cursor.getColumnIndex(Phone.NUMBER));
Try this code , it might help with some minor changes...
static final int PICK_CONTACT_=1;
Intent intent_1 = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent_1, PICK_CONTACT_);
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
switch (reqCode) {
case (PICK_CONTACT_) :
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor cursor = managedQuery(contactData, null, null, null, null);
if (cursor.moveToFirst()) {
String id =cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
String hasPhone =cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (hasPhone.equalsIgnoreCase("1")) {
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ id,
null, null);
phones.moveToFirst();
cNumber = phones.getString(phones.getColumnIndex("data_1"));
System.out.println("number is:"+cNumber);
}
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
}
}
break;
}
}
I want to get the phone number form the local contact,but there's something wrong.For example,if I choose Person A,then the number showed is Person B's.
Here's the code.
//the button_click
public void testM(View v) {
Intent intent = new Intent(Intent.ACTION_PICK,
ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
MainActivity.this.startActivityForResult(intent, 1);
}
//
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
final EditText phoneText = (EditText) findViewById(R.id.editText1);
switch (requestCode) {
case (1): {
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = managedQuery(contactData, null, null, null, null);
c.moveToFirst();
String phoneNum = this.getContactPhone(c);
phoneText.setText(phoneNum);
}
break;
}
}
}
// get the number
private String getContactPhone(Cursor cursor) {
int phoneColumn = cursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.HAS_PHONE_NUMBER);
int phoneNum = cursor.getInt(phoneColumn);
String phoneResult = "";
// System.out.print(phoneNum);
if (phoneNum > 0) {
// get the id
int idColumn = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID);
String contactId = cursor.getString(idColumn);
// get cursor;
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = "
+ contactId, null, null);
// int phoneCount = phones.getCount();
// allPhoneNum = new ArrayList<String>(phoneCount);
if (phones.moveToFirst()) {
// traverse all the phone number
for (; !phones.isAfterLast(); phones.moveToNext()) {
int index = phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int typeindex = phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE);
int phone_type = phones.getInt(typeindex);
String phoneNumber = phones.getString(index);
switch (phone_type) {
case 2:
phoneResult = phoneNumber;
break;
}
// allPhoneNum.add(phoneNumber);
}
if (!phones.isClosed()) {
phones.close();
}
}
}
return phoneResult;
}
I know there's must something wrong with'ContactsContract.CommonDataKinds'.I'm not familiar with this Class.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
final EditText phoneText = (EditText) findViewById(R.id.editText1);
switch (requestCode) {
case (1): {
if (resultCode == Activity.RESULT_OK) {
Uri contactData = data.getData();
Cursor c = getContentResolver().query(contactData, new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER}, null, null, null);
if (c.moveToFirst())
{
int columnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
String phoneNum = c.getString(columnIndex);
phoneText.setText(phoneNum);
}
}
break;
}
}
}