I have this code which allows users to access the camera to take photos and select images from gallery, it works on my Sony Xperia Z3 running Android 5.1.1.
I now have upgraded to a Nexus 5X running Android 6.0, but when i try to use the camera or save an image i get errors any help?
My Code to use Camera
Intent CameraImage = new Intent("android.media.action.IMAGE_CAPTURE");
Intent SelectedCameraImage = Intent.createChooser(CameraImage, "Take A Photo With");
startActivityForResult(SelectedCameraImage, SELECTED);
My Result Handler
public void onActivityResult(int RequestCode, int ResultCode, Intent Data) {
if (ResultCode == RESULT_OK) {
if (RequestCode == SELECTED) {
Uri SelectedImageUri = Data.getData();
SelectedImagePath = getPath(SelectedImageUri);
Log.d("DatabaseOperations", "Image Path : " + SelectedImagePath);
Img.setImageURI(SelectedImageUri);
try {
FileInputStream FileInpStream = new FileInputStream(SelectedImagePath);
BufferedInputStream BufInputStream = new BufferedInputStream(FileInpStream);
DBByte = new byte[BufInputStream.available()];
BufInputStream.read(DBByte);
Log.d("DatabaseOperations", "Image Size : " + DBByte.length + " KB");
}
catch (IOException e) {
Log.d("DatabaseOperations", "Error : " + SelectedImagePath);
Log.d("DatabaseOperations", e.getMessage(), e);
}
}
}
}
public String getPath(Uri Uris) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor Cursor = managedQuery(Uris, projection, null, null, null);
int ColumnIndex = Cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
Cursor.moveToFirst();
return Cursor.getString(ColumnIndex);
}
My Manifest Permissions
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission-sdk-23 android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission-sdk-23 android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission-sdk-23 android:name="android.permission.CAMERA" />
The Errors (Logcat)
FATAL EXCEPTION: main
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: Process: rajancorporations.database, PID: 3768
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: java.lang.SecurityException: Permission Denial: starting Intent { act=android.media.action.IMAGE_CAPTURE cmp=com.google.android.GoogleCamera/com.android.camera.CaptureActivity } from ProcessRecord{c9f94d7 3768:rajancorporations.database/u0a80} (pid=3768, uid=10080) with revoked permission android.permission.CAMERA
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at android.os.Parcel.readException(Parcel.java:1620)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at android.os.Parcel.readException(Parcel.java:1573)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:2658)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at android.app.Instrumentation.execStartActivity(Instrumentation.java:1507)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at android.app.Activity.startActivityForResult(Activity.java:3930)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at android.app.Activity.startActivityForResult(Activity.java:3890)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:784)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at rajancorporations.database.Reg$2.onClick(Reg.java:75)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at android.view.View.performClick(View.java:5204)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at android.view.View$PerformClick.run(View.java:21153)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at android.os.Handler.handleCallback(Handler.java:739)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:95)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at android.os.Looper.loop(Looper.java:148)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5417)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
03-01 22:12:44.071 3768-3768/rajancorporations.database E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Here is my complete code for taking image from camera or Gallery and it is working fine in marshmallow with others.
Here i am Declaring Varriables
protected static final int CAMERA_REQUEST = 0;
protected static final int GALLERY_REQUEST = 1;
private static final int REQUEST_ACESS_STORAGE=3;
private static final int REQUEST_ACESS_CAMERA=2;
private Uri uri;
Here i have some Methods for permission in marshmallow
public static boolean checkPermission(String permission, Context context) {
int statusCode = ContextCompat.checkSelfPermission(context, permission);
return statusCode == PackageManager.PERMISSION_GRANTED;
}
public static void requestPermission(AppCompatActivity activity, String[] permission, int requestCode) {
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission[0])) {
Toast.makeText(activity, "Application need permission", Toast.LENGTH_SHORT).show();
}
ActivityCompat.requestPermissions(activity, permission, requestCode);
}
public static void requestPermission(Fragment fragment, String[] permission, int requestCode) {
fragment.requestPermissions(permission, requestCode);
}
My onclick method
if (v.getId()==R.id.idOfPhoto){
handleCamera();
}
Details of handle camera method
private void handleCamera(){
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M) {
if (checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, this)) {
startDilog();
}else{
requestPermission(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUEST_ACESS_STORAGE);
}
}else{
startDilog();
}
}
startdilog method
private void startDilog() {
AlertDialog.Builder myAlertDilog = new AlertDialog.Builder(YourActivity.this);
myAlertDilog.setTitle("Upload picture option..");
myAlertDilog.setMessage("Where to upload picture????");
myAlertDilog.setPositiveButton("Gallery", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent picIntent = new Intent(Intent.ACTION_GET_CONTENT,null);
picIntent.setType("image/*");
picIntent.putExtra("return_data",true);
startActivityForResult(picIntent,GALLERY_REQUEST);
}
});
myAlertDilog.setNegativeButton("Camera", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
if(checkPermission(Manifest.permission.CAMERA,YourActivity.this)){
openCameraApplication();
}else{
requestPermission(YourActivity.this,new String[]{Manifest.permission.CAMERA},REQUEST_ACESS_CAMERA);
}
}else{
openCameraApplication();
}
}
});
myAlertDilog.show();
}
openCameraApplication method
private void openCameraApp() {
Intent picIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (picIntent.resolveActivity(getPackageManager())!= null){
startActivityForResult(picIntent, CAMERA_REQUEST);
}
}
Rest of code
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_REQUEST) {
if (resultCode == RESULT_OK) {
if (data != null) {
uri = data.getData();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
try {
BitmapFactory.decodeStream(getContentResolver().openInputStream(uri), null, options);
options.inSampleSize =calculateInSampleSize(options, 100, 100);
options.inJustDecodeBounds = false;
Bitmap image = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri), null, options);
imageview.setImageBitmap(image);
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "Cancelled",
Toast.LENGTH_SHORT).show();
}
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(getApplicationContext(), "Cancelled",
Toast.LENGTH_SHORT).show();
}
} else if (requestCode == CAMERA_REQUEST) {
if (resultCode == RESULT_OK) {
if (data.hasExtra("data")) {
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
uri = getImageUri(YourActivity.this, bitmap);
File finalFile = new File(getRealPathFromUri(uri));
imageview.setImageBitmap(bitmap);
} else if (data.getExtras() == null) {
Toast.makeText(getApplicationContext(),
"No extras to retrieve!", Toast.LENGTH_SHORT)
.show();
BitmapDrawable thumbnail = new BitmapDrawable(
getResources(), data.getData().getPath());
owner_pic.setImageDrawable(thumbnail);
}
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(getApplicationContext(), "Cancelled",
Toast.LENGTH_SHORT).show();
}
}
}
private String getRealPathFromUri(Uri tempUri) {
Cursor cursor = null;
try {
String[] proj = {MediaStore.Images.Media.DATA};
cursor = this.getContentResolver().query(tempUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
private Uri getImageUri(YourActivity youractivity, Bitmap bitmap) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
String path = MediaStore.Images.Media.insertImage(youractivity.getContentResolver(), bitmap, "Title", null);
return Uri.parse(path);
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode==REQUEST_ACESS_STORAGE && grantResults[0]== PackageManager.PERMISSION_GRANTED){
startDilog();
}
if(requestCode==REQUEST_ACESS_CAMERA && grantResults[0]==PackageManager.PERMISSION_GRANTED){
openCameraApp();
}
}
it's working fine in witth all devices..
First, you assume that Data.getData() is meaningful here. There is no Uri returned by ACTION_IMAGE_CAPTURE, according to the specification. Your options are either to supply EXTRA_OUTPUT (in which case, the image should be where you indicate in that extra), or to get a thumbnail back from Data.getExtra("data"). There may be a few camera apps that do return a Uri. But there are over 8,000 Android device models, with hundreds, if not thousands, of different default camera apps. The user might also be having your request be handled by a third-party camera app. Most camera apps will give you a null value for Data.getData().
Second, even if you get a Uri, you assume that the Uri is known to the MediaStore. That is not required.
Third, even if you get a Uri and it is is known to the MediaStore, you assume that the DATA column is a path to a local file that you can access. This is not required. For example, it might be a path to removable storage, which you cannot access on Android 4.4+.
To address those three problems, use EXTRA_OUTPUT to designate where you want the camera to store the picture, and get rid of getPath() and your dependence upon the Uri.
Fourth, when working with external storage on Android 6.0+, if your targetSdkVersion is 23 or higher, you need to request READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE from the user at runtime. The same holds true for the CAMERA permission.
Fifth, do not have <uses-permission> and <uses-permission-sdk-23> for the same permissions. In your case, use <uses-permission>.
Related
My app is crashing when I click on the following button to use dispatchTakePictureIntent
My code:
ic_img_item.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dispatchTakePictureIntent(PHOTO);
}
});
private void dispatchTakePictureIntent(int requestCode) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(activity.getPackageManager()) != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, PHOTO_TEMP);
takePictureIntent.putExtra("return-data", true);
startActivityForResult(takePictureIntent, requestCode);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
try {
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 2;
Bitmap bitmap = RotateBitmap(BitmapFactory.decodeStream(activity.getContentResolver().openInputStream(PHOTO_TEMP), null, bmOptions), getPictureOrientation(PHOTO_TEMP));
thumb = getThumbnail(bitmap);
setThumbnail(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Log:
--------- beginning of crash
2020-09-10 17:41:31.769 25093-25093/ubisolutions.net.datacenterinventory.debug E/AndroidRuntime: FATAL EXCEPTION: main
Process: ubisolutions.net.datacenterinventory.debug, PID: 25093
java.lang.RuntimeException: android.os.TransactionTooLargeException: data parcel size 3087012 bytes
at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3782)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
Caused by: android.os.TransactionTooLargeException: data parcel size 3087012 bytes
at android.os.BinderProxy.transactNative(Native Method)
at android.os.BinderProxy.transact(Binder.java:615)
at android.app.ActivityManagerProxy.activityStopped(ActivityManagerNative.java:3653)
at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3774)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:889)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:779)
2020-09-10 17:41:31.775 1239-1239/? E/NotificationService: Suppressing notification from package by user request.
2020-09-10 17:41:31.775 1239-25274/? I/QCALOG: [MessageQ_Client] connecting to server [/data/misc/location/mq/location-mq-s]
2020-09-10 17:41:31.776 1239-25274/? E/QCALOG: [MessageQ_Client] connect error: 111, [Connection refused]
I have seen some responses about similar issues but none of them helped me to solve it.
thanks.
Your code line
takePictureIntent.putExtra("return-data", true);
requests, that the picture data is returned directly, but it is too large to be passed back in the result. You should instead get it from PHOTO_TMP you are passing in the intent too.
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, PHOTO_TEMP)
Activity results is NullPointerException, What I have done wrong or missed?
Photo gallery application(Eventually), followed the instructions on the android developer site about taking photos with inbuilt camera. onActivityResult giving null pointer. I am new to android so can't figure it out.
Because of this it crashes, i expect it to show a bitmap in the activity.
public class aCamera extends AppCompatActivity {
static final int REQUEST_IMAGE_CAPTURE = 1;
static final int REQUEST_TAKE_PHOTO = 1;
ImageView imageView;
String currentPhotoPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a_camera);
dispatchTakePictureIntent();
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
Log.i("DTPI-1", "dispatchTakePictureIntent: The IF AND TRY");
} catch (IOException ex) {
Log.i("DTPI-3" , "dispatchTakePictureIntent: catch");
}
// Continue only if the File was successfully created
if (photoFile != null) {
Log.i("photoURI", "dispatchTakePictureIntent: PHOTO FILE NOT EMPTY");
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
//setResult(RESULT_OK, takePictureIntent);
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
Log.i("CIF -1", "createImageFile: Create FILE");
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = image.getAbsolutePath();
return image;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i("Result", "onActivityResult: WE GET HERE");
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
imageView = findViewById(R.id.imageView);
imageView.setImageBitmap(imageBitmap);
}
}
Error logs.
2019-05-06 20:01:33.555 23363-23363/com.example.camera E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.camera, PID: 23363
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {com.example.camera/com.example.camera.aCamera}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:4339)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4382)
at android.app.ActivityThread.-wrap19(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1654)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:251)
at android.app.ActivityThread.main(ActivityThread.java:6572)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
at com.example.camera.aCamera.onActivityResult(aCamera.java:81)
at android.app.Activity.dispatchActivityResult(Activity.java:7235)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4335)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4382)
at android.app.ActivityThread.-wrap19(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1654)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:251)
at android.app.ActivityThread.main(ActivityThread.java:6572)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
The camera saves the image to the photoUri that you supply in your Intent. In onActivityResult you have to get the Bitmap from that file.
The line putExtra is the issue. Delete that line and receive bitmap in
onActivityResult like mentioned below.
#Override
protected void onActivityResult(int requestCode, int resultcode, Intent intent) {
if (requestCode == REQUEST_TAKE_PHOTO && resultcode == RESULT_OK) {
Uri uri = intent.getData();
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
} catch (IOException e) {
e.printStackTrace();
}
image.setImageBitmap(bitmap);
}
}
Hope this works. You will see the explaination here on a post with similar issue.
As mentioned by #aalap patel, the issue is not with onActivityResult, it is with one line in dispatchTakePictureIntent method.
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
adding to this is the code that he also mentions.
I am very sorry if this may be a question with a simple solution.
What Am I Trying To Do?
Capture an image from a Button
Upload that image to Firebase storage
Retrieve that image in an ImageView
What Is My Trouble So Far?
Takes picture, but crashes when I click the tick.
Hence nothing is being uploaded or being achieved.
My Code
P.N I have looked at lots of other forums and video tutorials but nothing seems to be working. Hopefully someone can help.
public class LeaderboardActivity extends AppCompatActivity {
private static final int CAMERA_REQUEST_CODE = 1;
private static final int REQUEST_TAKE_PHOTO = 1;
private StorageReference mStorage;
private ProgressDialog mProgress;
String mCurrentPhotoPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_leaderboard);
mStorage = FirebaseStorage.getInstance().getReference();
final Button bImage = (Button) findViewById(R.id.bCamera);
final ImageView ivPic = (ImageView) findViewById(R.id.ivPic);
mProgress = new ProgressDialog(this);
bImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
mProgress.setMessage("Uploading Image");
mProgress.show();
Uri uri = data.getData();
StorageReference filepath = mStorage.child("Photo").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener < UploadTask.TaskSnapshot > () {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mProgress.dismiss();
Toast.makeText(LeaderboardActivity.this, "Uploading Complete...", Toast.LENGTH_LONG);
}
});
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
}
Error In Android Monitor
Not sure if this will help
02-13 02:30:32.693 2133-2133/com.example.rikhi.chores E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.rikhi.chores, PID: 2133
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.example.rikhi.chores/com.example.rikhi.chores.LoginRegister.InsideMainActivity.LeaderboardActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getLastPathSegment()' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:4089)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4132)
at android.app.ActivityThread.-wrap20(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1533)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getLastPathSegment()' on a null object reference
at com.example.rikhi.chores.LoginRegister.InsideMainActivity.LeaderboardActivity.onActivityResult(LeaderboardActivity.java:74)
at android.app.Activity.dispatchActivityResult(Activity.java:6932)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4085)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4132)
at android.app.ActivityThread.-wrap20(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1533)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
I have looked at other people who had the same problem, followed what they said nothing happend, followed the Google Android instructions for this and again same problem.
On button, click remove that intent and just call your
dispatchTakePictureIntetnt() method on Onclick button Listener
Also, check go to your emulator settings, and check your camera
permission is on for your this app and also go to firebase console
and check the rules if, rules are not equal to null made them equal
to null then run your app because !=null rules only work when there
is an authentication method in your app
I am trying to get the absolute path to the images in the gallery or camera.
After the camera intent opens up, I click on a image & am trying to fetch the file path from URI. Please see the code bit.
//In the OnActivityResult:
Uri uri = data.getData();
File myFile = new File(uri.getPath());
File imageFilePath = new File(getRealPathFromURI(uri));
//The method to fetch path:
private String getRealPathFromURI(Uri contentURI) {
String result;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
Log.d("", "cursor = " +cursor);
if (cursor == null) { // Source is Dropbox or other similar local file path
result = contentURI.getPath();
} else {
int idx = cursor.getColumnIndex(MediaStore.Images.Media.DATA ); // Is this the wrong way to get the image cursor?
Log.d("", "came here = " +idx); // Here idx us -1!!!
cursor.moveToFirst();
result = cursor.getString(idx);
cursor.close();
}
return result;
}
// image pick intent
public void imageFromGallery() {
Intent intent = new Intent();
// Show only images, no videos or anything else
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// Always show the chooser (if there are multiple options available)
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
Adding the logCat:
721-4721/com.coolhydro.copy E/CursorWindow﹕ Failed to read row 0, column -1 from a CursorWindow which has 1 rows, 6 columns.
10-11 18:53:55.495 4721-4721/com.coolhydro.copy D/AndroidRuntime﹕ Shutting down VM
10-11 18:53:55.495 4721-4721/com.coolhydro.copy E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.coolhydro.copy, PID: 4721
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://com.android.providers.media.documents/document/image:49 flg=0x1 }} to activity {com.coolhydro.copy/com.coolhydro.copy.MainActivity}: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at android.app.ActivityThread.deliverResults(ActivityThread.java:3699)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3742)
at android.app.ActivityThread.-wrap16(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1393)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at android.database.CursorWindow.nativeGetString(Native Method)
at android.database.CursorWindow.getString(CursorWindow.java:438)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51 )
at android.database.CursorWrapper.getString(CursorWrapper.java:137)
at com.coolhydro.copy.MainActivity.getRealPathFromURI(MainActivity.java:80)
at com.coolhydro.copy.MainActivity.onActivityResult(MainActivity.java:52)
at android.app.Activity.dispatchActivityResult(Activity.java:6428)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3695)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3742)
at android.app.ActivityThread.-wrap16(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1393)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
10-11 18:54:01.237 4721-4730/com.coolhydro.copy W/CursorWrapperInner﹕ Cursor finalized without prior close()
10-11 18:58:55.523 4721-4721/? I/Process﹕ Sending signal. PID: 4721 SIG: 9
Thanks!
You need to pass a projection into your query call. As is, you return a cursor with no columns, and so when you try to find the index of a certain column you return -1. Try using
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(contentURI, projection, null, null, null);
Then when you want to retrieve data, you already know the column index (it's the index of that column in the projection array) so you can just set
int idx = 0;
I have this code when i request images from both gallery and camera:
Intent pickIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
pickIntent.setType("image/*");
Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(fileCameraCapturedImage));
String pickTitle = "Select or take a new Picture"; // Or get from strings.xml
Intent chooserIntent = Intent.createChooser(pickIntent, pickTitle);
chooserIntent.putExtra
(
Intent.EXTRA_INITIAL_INTENTS,
new Intent[]{captureIntent}
);
startActivityForResult(chooserIntent, REQUEST_CODE_ADD_PHOTO);
and on my onActivityResult() i check of the returned data came from gallery or camera then i use it:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
if(requestCode == REQUEST_CODE_ADD_PHOTO) {
Log.v(TAG, "Photo ok! " + data);
boolean isCamera;
//getclip data requires API 16
if (Build.VERSION.SDK_INT >= 16){
if (data == null || (data.getData() == null && data.getClipData() == null)) {
isCamera = true;
} else {
final String action = data.getAction();
if (action == null) {
isCamera = false;
} else {
isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
}
}
}
else{
if (data == null || data.getData() == null) {
isCamera = true;
} else {
final String action = data.getAction();
if (action == null) {
isCamera = false;
} else {
isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
}
}
}
Log.v(TAG, "is camera: " + isCamera);
if(!isCamera) {
//gallery result
Uri selectedImageUri = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImageUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
Log.v(TAG,"Path: "+filePath);
if(filePath !=null) {
if(!filePath.equalsIgnoreCase("")) {
imagePath = filePath;
Picasso.with(getApplicationContext()).load("file://" + imagePath).into(ivPhotoContainer);
btnAddChange.setText("Change");
}
}
}
else {
//is camera result
Log.v(TAG, "is camera result");
String path = fileCameraCapturedImage.getAbsolutePath();
imagePath = path;
// ivPhotoContainer.setImageBitmap(thumbnail);
Picasso.with(getApplicationContext()).load("file://"+imagePath).into(ivPhotoContainer);
btnAddChange.setText("Change");
}
}
}
}
Note: fileCameraCapturedImage is of type file which references the file where the captured image will be saved on the device.
private File fileCameraCapturedImage = new File(Environment.getExternalStorageDirectory()+File.separator+"capturedImage.jpg");
I've written an application which should take a picture and then show it on the screen for modifications.
When trying it on the eclipse emulator the camera won't work, so I'm trying it on my Galaxy Nexus Smart Phone.
Nevertheless when running it on my SP the application will crash saying that it unfortunally stopped working.
When executing the app this is what exactly happens:
I click on the camera button and the camera interface gets opened
After taking the picture it gives me the choice to discard it or open it
If I click on discard the application returns to normal usage
If I click on open the application crashes as mentioned above
I googled a little and found out that you need permissions to use hardware devices check here, so I created the file /etc/udev/rules.d/51-android.rules and this is its content:
SUBSYSTEM=="USB", ATTR{IDVENDOR}=="18d1", MODE="0666, "GROUP="plugdev"
SUBSYSTEM=="USB", ATTR{IDVENDOR}=="04e8", MODE="0666, "GROUP="plugdev"
SUBSYSTEM=="USB", ATTR{IDVENDOR}=="0bb4", MODE="0666, "GROUP="plugdev"
But still I won't be able to use camera.
Here are the permissions I declared in my manifest file:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
Here is the code I use to launch the camera intent:
//create new Intent
Intent cameraIntent = new Intent( android.provider.MediaStore.ACTION_IMAGE_CAPTURE );
//get something back from the activity we are starting
startActivityForResult( cameraIntent, CAMERA_PICTURE_REQUEST );
And this is the code for processing the result:
public void onActivityResult( int requestCode, int resultCode, Intent imageReturnedIntent )
{
if( resultCode == RESULT_OK )
{
if( requestCode == GALLERY_PICTURE_REQUEST )
{
selectedImageUri = imageReturnedIntent.getData();
Log.d( TAG, selectedImageUri );
Intent intent = new Intent( DVAHLUI_SuperviseActivity.this, DVAHLUI_SelectImageContentActivity.class );
intent.setData( selectedImageUri );
startActivity( intent );
}
if( requestCode == CAMERA_PICTURE_REQUEST )
{
selectedImageUri = imageReturnedIntent.getData();
Log.d( TAG, selectedImageUri );
Intent intent = new Intent( DVAHLUI_SuperviseActivity.this, DVAHLUI_SelectImageContentActivity.class );
intent.setData( selectedImageUri );
startActivity( intent );
}
}
}
This is the getPath() function causing the Java Null pointer exception:
public String getPath( Uri uri )
{
String[] filePathColumn = { android.provider.MediaStore.Images.Media.DATA };
LINE 343 --> Cursor cursor = getContentResolver().query( uri, filePathColumn, null, null, null );
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndexOrThrow( filePathColumn[0] );
String filePath = cursor.getString( columnIndex );
cursor.close();
return filePath;
}
Can you please tell me what's going wrong?
FOGOT TO POST LOGCAT:
E/AndroidRuntime(27859): FATAL EXCEPTION: main
E/AndroidRuntime(27859): java.lang.RuntimeException: Failure delivering result ResultInfo{who=supervise, request=1, result=-1, data=Intent { act=inline-data (has extras) }} to activity {com.DVA_HLUI/com.DVA_HLUI.DVAHLUI_TabModeActivity}: java.lang.NullPointerException
E/AndroidRuntime(27859): at android.app.ActivityThread.deliverResults(ActivityThread.java:3141)
E/AndroidRuntime(27859): at android.app.ActivityThread.handleSendResult(ActivityThread.java:3184)
E/AndroidRuntime(27859): at android.app.ActivityThread.access$1100(ActivityThread.java:130)
E/AndroidRuntime(27859): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1243)
E/AndroidRuntime(27859): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(27859): at android.os.Looper.loop(Looper.java:137) E/AndroidRuntime(27859): at android.app.ActivityThread.main(ActivityThread.java:4745)
E/AndroidRuntime(27859): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(27859): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(27859): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
E/AndroidRuntime(27859): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
E/AndroidRuntime(27859): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(27859): Caused by: java.lang.NullPointerException
E/AndroidRuntime(27859): at android.content.ContentResolver.acquireUnstableProvider(ContentResolver.java:1094)
E/AndroidRuntime(27859): at android.content.ContentResolver.query(ContentResolver.java:354)
E/AndroidRuntime(27859): at android.content.ContentResolver.query(ContentResolver.java:313)
E/AndroidRuntime(27859): at com.DVA_HLUI.DVAHLUI_SuperviseActivity.getPath(DVAHLUI_SuperviseActivity.java:343)
E/AndroidRuntime(27859): at com.DVA_HLUI.DVAHLUI_SuperviseActivity.onActivityResult(DVAHLUI_SuperviseActivity.java:312)
E/AndroidRuntime(27859): at android.app.ActivityGroup.dispatchActivityResult(ActivityGroup.java:122)
E/AndroidRuntime(27859): at android.app.ActivityThread.deliverResults(ActivityThread.java:3137)
E/AndroidRuntime(27859): ... 11 more
It sounds and looks like your not allowing the system to update itself that a new media file has been created. Thats why your method is failing. You can either manully create the image file path so you have the images location on the file tree or you can call for the media service to run an update. I always create my own filepath as older phones take longer to update using the media service and so your method in that case would fail.
Apparently this crash is due to a known Samsung problem: it seems like you need to create a Uri before calling the camera intent, in this way when running the onActivityResult method
the content provider will allready have allocated the place where to save the resource.
For further information check the following:
My Android camera Uri is returning a null value, but the Samsung fix is in place, help?
Android: startActivityForResult always null and force close my app
wordpress link
Android Samsung: Camera app won't return intent.getData()
and many more by googling...
P.S. as soon as possible I'll post the solution that worked for me.
I know it is late to answer it but asap i found the answer i replied for it so please atleast review it .
AndroidCameraUtil could be nice and easy solution for each and every device below is the code snippet you can use with the library
private void setupCameraIntentHelper() {
mCameraIntentHelper = new CameraIntentHelper(this, new CameraIntentHelperCallback() {
#Override
public void onPhotoUriFound(Date dateCameraIntentStarted, Uri photoUri, int rotateXDegrees) {
messageView.setText(getString(R.string.activity_camera_intent_photo_uri_found) + photoUri.toString());
Bitmap photo = BitmapHelper.readBitmap(CameraIntentActivity.this, photoUri);
if (photo != null) {
photo = BitmapHelper.shrinkBitmap(photo, 300, rotateXDegrees);
ImageView imageView = (ImageView) findViewById(de.ecotastic.android.camerautil.sample.R.id.activity_camera_intent_image_view);
imageView.setImageBitmap(photo);
}
}
#Override
public void deletePhotoWithUri(Uri photoUri) {
BitmapHelper.deleteImageWithUriIfExists(photoUri, CameraIntentActivity.this);
}
#Override
public void onSdCardNotMounted() {
Toast.makeText(getApplicationContext(), getString(R.string.error_sd_card_not_mounted), Toast.LENGTH_LONG).show();
}
#Override
public void onCanceled() {
Toast.makeText(getApplicationContext(), getString(R.string.warning_camera_intent_canceled), Toast.LENGTH_LONG).show();
}
#Override
public void onCouldNotTakePhoto() {
Toast.makeText(getApplicationContext(), getString(R.string.error_could_not_take_photo), Toast.LENGTH_LONG).show();
}
#Override
public void onPhotoUriNotFound() {
messageView.setText(getString(R.string.activity_camera_intent_photo_uri_not_found));
}
#Override
public void logException(Exception e) {
Toast.makeText(getApplicationContext(), getString(R.string.error_sth_went_wrong), Toast.LENGTH_LONG).show();
Log.d(getClass().getName(), e.getMessage());
}
});
}
#Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
mCameraIntentHelper.onSaveInstanceState(savedInstanceState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mCameraIntentHelper.onRestoreInstanceState(savedInstanceState);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
mCameraIntentHelper.onActivityResult(requestCode, resultCode, intent);
}
}