Image uploading to Cloudinary Failed in Android - java

I am trying to upload an image to Cloudinary after clicking the image from the camera.
The camera is working fine but after clicking the image, the application is crashing again and again. Tried to debug it but not getting where I am having the error.
LOGCAT:
beginning of crash
05-03 00:29:58.243 4880-4880/com.example.maaz.taxit E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.maaz.taxit, PID: 4880
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=-1, data=null} to activity {com.example.maaz.taxit/com.example.maaz.taxit.ImageDeleteTest}: android.os.NetworkOnMainThreadException
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: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
at java.net.InetAddress.lookupHostByName(InetAddress.java:431)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:188)
at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:157)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:100)
at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:357)
at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:340)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:330)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:433)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:114)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:245)
at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getOutputStream(DelegatingHttpsURLConnection.java:218)
at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java)
at com.cloudinary.android.MultipartUtility.<init>(MultipartUtility.java:52)
at com.cloudinary.android.UploaderStrategy.callApi(UploaderStrategy.java:48)
at com.cloudinary.Uploader.callApi(Uploader.java:22)
at com.cloudinary.Uploader.upload(Uploader.java:55)
at com.example.maaz.taxit.ImageDeleteTest.onActivityResult(ImageDeleteTest.java:63)
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) 
I tried to hard code the sample image URL's but still it is not working.
May be the issue is with this line
cloudinary.uploader().upload(photoFile.getAbsolutePath(), ObjectUtils.emptyMap());
public static final int TAKE_PHOTO_REQUEST = 0;
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PHOTO_REQUEST) {
if (resultCode == RESULT_OK) {
//File to upload to cloudinary
Toast.makeText(this, "Pakistan Zinabad", Toast.LENGTH_SHORT).show();
Map config = new HashMap();
config.put("cloud_name", "nomancloud");
config.put("api_key", "myKey");
config.put("api_secret", "mySecretApi");
Cloudinary cloudinary = new Cloudinary(config);
try {
cloudinary.uploader().upload(photoFile.getAbsolutePath(), ObjectUtils.emptyMap());
} catch (IOException e) {
e.printStackTrace();
}
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture
//finish();
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String imageFileName = "capturedImage";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
return image;
}
#Override
public void onClick(View v) {
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePhotoIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
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) {
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePhotoIntent, TAKE_PHOTO_REQUEST);
}
}
}

Can you try using:
Map uploadResult = cloudinary.uploader().upload("http://res.cloudinary.com/demo/image/upload/sample.jpg", ObjectUtils.emptyMap());
And print the RuntimeException/uploadResult?

Try using the MediaManager class for android provided by Cloudinary. You will need to call the dispatch() method which will run on a background thread. Basically you are getting NetworkOnMainThread exception which means you are doing network calls on the UI thread with Android does not allow. Check the documentation, its easy.
String requestId = MediaManager.get().upload("imageFile.jpg")
.unsigned("sample_preset")
.dispatch();
A snippet from docs.
Checkout this link to learn more:
Cloudinary upload documentation page

Related

Get Real Path of mp3 file from Uri

I have picked audio file from Content Picker intent inside Fragment which extend PreferenceFragmentCompat
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("audio/mpeg");
startActivityForResult(intent, 1);
and Retrieved Uri from onActivityResult
#Override
public void onActivityResult(int requestCode, int resultcode, Intent data) {
if (requestCode == 1 && resultcode == Activity.RESULT_OK) {
audio = data.getData();
inputfile= (FileInputStream getActivity().getApplicationContext().getContentResolver().openInputStream(data.getData());
}
super.onActivityResult(requestCode, resultcode, data);
}
Where audio is declared public(Uri audio).
Now i wanted this audio file to be copied to a Directory in App Directory(/data/data/com.example.focusit).For this i need to get Real path of audio file from URI
public String getRealPathFromUri(Uri contentUri) {
String res = null;
String[] proj = {
MediaStore.Audio.Media.DATA
};
Cursor cursor = (Cursor) getActivity().getApplicationContext().getContentResolver().query(contentUri, proj, null, null, null);
if (cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
return res;
}
Now to copy audio file to my directoy i used this code
File audiofile = new File(audio.getPath());
String realpath = getRealPathFromUri(audio);
File file = new File("/data/data/com.example.focusit/Focusit_SOS/tt_temp.mp3");
if (!file.exists()) {
Toast.makeText(getContext(), "Director focus it does not existed", Toast.LENGTH_SHORT).show();
file.mkdirs();
}
try {
FileUtils.copy(new FileInputStream(audiofile), new FileOutputStream(file));enter code here
} catch (IOException e) {
e.printStackTrace();
But problem is that in function getRealPathFromUri(Uri ContentUri) cursor.movetoFirst() is returning false.Any idea how to deal with it.
Output of audio.getpath() is /external/audio/media/8099.
i tried one solution by creating Input stream directly from Uri in onActivityResult()
inputfile= (FileInputStream) getActivity().getApplicationContext().getContentResolver().openInputStream(data.getData());
but i am getting exception
2020-10-28 07:41:31.333 21292-21292/com.example.focusit E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.focusit, PID: 21292
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=65537, result=-1, data=Intent { dat=content://media/external/audio/media/8099 (has extras) }} to activity {com.example.focusit/com.example.focusit.SettingsActivity}: java.lang.SecurityException: com.example.focusit has no access to content://media/external/audio/media/8099
at android.app.ActivityThread.deliverResults(ActivityThread.java:4905)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4946)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2040)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7520)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
Caused by: java.lang.SecurityException: com.example.focusit has no access to content://media/external/audio/media/8099
at android.os.Parcel.createException(Parcel.java:2074)
at android.os.Parcel.readException(Parcel.java:2042)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:188)
at android.database.DatabaseUtils.readExceptionWithFileNotFoundExceptionFromParcel(DatabaseUtils.java:151)
at android.content.ContentProviderProxy.openTypedAssetFile(ContentProviderNative.java:705)
at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1702)
at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:1518)
at android.content.ContentResolver.openInputStream(ContentResolver.java:1202)
at com.example.focusit.SettingsActivity$SettingsFragment.onActivityResult(SettingsActivity.java:227)
at androidx.fragment.app.FragmentActivity.onActivityResult(FragmentActivity.java:170)
at android.app.Activity.dispatchActivityResult(Activity.java:8249)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4898)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4946) 
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2040) 
at android.os.Handler.dispatchMessage(Handler.java:107) 
at android.os.Looper.loop(Looper.java:224) 
at android.app.ActivityThread.main(ActivityThread.java:7520) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950) `
Providing Storage access will resolve Exception
java.lang.SecurityException: com.example.focusit has no access to content:
Do not open a FileInputStream on a path you do not have.
Instead open an InputStream on the obtained uri directly.
InputStream is = getContentResolver().openInputStream(data.getData());

MediaStore.Images.Media.insertImage returns null in some devices

Possibly Duplicate but did not find any solution.
I am trying to modify image and saving it to device using MediaStore. with following code -:
public class Utils {
private Utils() {
}
static Uri getUri(Context context, Bitmap bitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(context.getContentResolver(), bitmap, "Title", null); //returning null in some devices
Log.d("TAG", "getUri: "+path);
return Uri.parse(path); //this is returning null which cause the app crash
}
static Bitmap getBitmap(Context context, Uri uri) throws IOException {
return MediaStore.Images.Media.getBitmap(context.getContentResolver(), uri);
}
}
This code is working well in most of devices but the problem is that MediaStore.Images.Media.insertImage returning null in some devices like -:
1. Samsung J7(2016)
2. LG Magna LTE
3. Android Emulator API 21
I am surprised this app is working in Android Emulator API 26 . but getting crashed on Android Emulator API 21
I have searched google and I have also find the same question here but not find any sufficient answer.
NOTE - : I have used Runtime Permission for Read/Write External Storage
But still getting crash in mentioned devices. Below is my crash log-:
Fatal Exception: java.lang.RuntimeException: Failure delivering result ResultInfo{who=android:fragment:0, request=1, result=-1, data=Intent { dat=content://com.android.providers.media.documents/document/image:51 flg=0x1 }} to activity {com.example/com.scanlibrary.ScanActivity}: java.lang.NullPointerException: uriString
at android.app.ActivityThread.deliverResults(ActivityThread.java:3574)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3617)
at android.app.ActivityThread.access$1300(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1352)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Method.java)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by java.lang.NullPointerException: uriString
at android.net.Uri$StringUri.<init>(Uri.java:470)
at android.net.Uri$StringUri.<init>(Uri.java:460)
at android.net.Uri.parse(Uri.java:432)
at com.scanlibrary.Utils.getUri(Utils.java:24)
at com.scanlibrary.PickImageFragment.postImagePick(PickImageFragment.java:228)
at com.scanlibrary.PickImageFragment.onActivityResult(PickImageFragment.java:208)
at android.app.Activity.dispatchActivityResult(Activity.java:6196)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3570)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3617)
at android.app.ActivityThread.access$1300(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1352)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Method.java)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Thanks
Instead of using below code-:
String path = MediaStore.Media.insertImage(context.getContentResolver(),bitmap,"Title",null);
Use this code(below)-:
ContentValues values=new ContentValues();
values.put(MediaStore.Images.Media.TITLE,"Title");
values.put(MediaStore.Images.Media.DESCRIPTION,"From Camera");
Uri path=getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,values);
pass values as null if it is not working.
protected void onActivityResult(int requestCode, int resultCode,Intent data) {
if (requestCode == RequestPermissionCode && resultCode == RESULT_OK) {
try {
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, filePathColumn, null, null, null);
if (cursor == null)
return;
// find the file in the media area
cursor.moveToLast();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = "file:///"+cursor.getString(columnIndex);
cursor.close();
actualImage = FileUtil.from(this,Uri.parse(filePath));
actualImageView.setImageBitmap(BitmapFactory.decodeFile(actualImage.getAbsolutePath()));
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
}
Use onActvittyResult method i hope it will work.

Failure delivering result ResultInfo{who=null, request=2, result=-1, data=Intent { }} to activity

I have a method that gives users the option to use the camera intent to capture a photo to then upload to the application:
public void UploadImageToFeed() {
CharSequence colors[] = new CharSequence[] {"Gallery", "Take a Picture"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Upload an Image");
builder.setIcon(R.drawable.ic_upload_image);
builder.setItems(colors, (dialog, which) -> {
if (which == 0) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
} else {
Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory(), "camera.jpg");
Uri uri = Uri.fromFile(file);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(captureIntent, SELECT_PHOTO);
}
});
builder.show();
}
When a camera image is taken, I process the image to reduce its size before it is actually uploaded. This is where I get a crash.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case SELECT_PHOTO:
if (resultCode == RESULT_OK) {
ImageView imageToUpload = (ImageView) findViewById(R.id.imageToUpload);
imageToUpload.setVisibility(View.VISIBLE);
Uri selectedImage = imageReturnedIntent.getData();
InputStream imageStream = null;
try {
imageStream = getContentResolver().openInputStream(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
int nh = (int) (yourSelectedImage.getHeight() * (512.0 / yourSelectedImage.getWidth()));
Bitmap scaled = Bitmap.createScaledBitmap(yourSelectedImage, 512, nh, true);
imageToUpload.setImageBitmap(scaled);
}
}
}
Exception:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=2, result=-1, data=Intent { dat=content://com.google.android.apps.photos.contentprovider/-1/1/content://media/external/images/media/197149/ORIGINAL/NONE/724456777 flg=0x1 clip={text/uri-list U:content://com.google.android.apps.photos.contentprovider/-1/1/content%3A%2F%2Fmedia%2Fexternal%2Fimages%2Fmedia%2F197149/ORIGINAL/NONE/724456777} }} to activity {com.yitter.android/com.yitter.android.activity.YeetActivity}: java.lang.IllegalArgumentException: width and height must be > 0
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.IllegalArgumentException: width and height must be > 0
at android.graphics.Bitmap.createBitmap(Bitmap.java:829)
at android.graphics.Bitmap.createBitmap(Bitmap.java:808)
at android.graphics.Bitmap.createBitmap(Bitmap.java:739)
at android.graphics.Bitmap.createScaledBitmap(Bitmap.java:615)
at com.yitter.android.activity.YeetActivity$override.onActivityResult(YeetActivity.java:350)
at com.yitter.android.activity.YeetActivity$override.access$dispatch(YeetActivity.java)
at com.yitter.android.activity.YeetActivity.onActivityResult(YeetActivity.java:0)
at android.app.Activity.dispatchActivityResult(Activity.java:6456)
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)
 
My first suspicion was that the error occurs where I'm scaling the camera image down, but it's not so obvious from my stack trace. When I remove the two lines of code responsible for rescaling the image, I get the following error:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=2, result=-1, data=Intent { }} to activity {com.yitter.android/com.yitter.android.activity.YeetActivity}: java.lang.NullPointerException: uri
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.NullPointerException: uri
at com.android.internal.util.Preconditions.checkNotNull(Preconditions.java:60)
at android.content.ContentResolver.openInputStream(ContentResolver.java:645)
at com.yitter.android.activity.YeetActivity.onActivityResult(YeetActivity.java:366)
at android.app.Activity.dispatchActivityResult(Activity.java:6456)
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) 
What could be going wrong?
ACTION_IMAGE_CAPTURE does not return a Uri. You know the Uri where the image is supposed to be — you put it in EXTRA_OUTPUT. You need to hold onto that location (including via the saved instance state Bundle) and look there.
Also note that Uri.fromFile() will not work on Android 7.0+, once you raise your targetSdkVersion to 25 or higher.
This sample app demonstrates using ACTION_IMAGE_CAPTURE, including using FileProvider to avoid Uri.fromFile().

Android: Gallery picker and Camera intent crashes upon onActivityresult

So I have this page in my app which lets user choose to either take a picture with their camera or pick an image from gallery.
Upon choosing an alert dialog with the chosen image set as icon will be shown confirming.
Now here comes my problem, whenever I try to get an image, using either the gallery picker or camera intent, my app crashes right after with error:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1888, result=-1, data=null} to activity {my.com.thelorry.ken.thelorrypartner/com.example.Activity}:
If I am using the camera intent or if I used the gallery picker this shows:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1888, result=-1, data=null} to activity {com.example/com.example.Activity}:
Below are the codes I used to start my camera intent:
public void startCamera(){
ContentValues values;
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "New Picture");
values.put(MediaStore.Images.Media.DESCRIPTION, "From phone Camera");
imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
And my codes to start gallery picker:
public void pickGallery(){
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, GALLERY_REQUEST);
}
This is my codes to handle the results:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
photo = null;
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK ) {
try {
photo = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
photo = getResizedBitmap(photo, 600, 450);
File file = new File(imageurl);
file.delete();
} catch (Exception e) {
e.printStackTrace();
}
createDialog(photo);
}if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK && data != null) {
Uri pickedImage = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
cursor.moveToFirst();
String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
photo = getResizedBitmap(bitmap, 600, 450);
cursor.close();
createDialog(photo);
}
}
Also, odd enough, this codes seems to crash only on Samsung phones based on my crash reports, and only on some models such as the Galaxy J7, Note5, Note4 (so far, app doesn't have a huge userbase yet).
Edit: After actually getting a phone that could reproduce the crash I realize that codes above might not be the problem after all, this is the what I have in logcats:
Process: com.example, PID: 6220
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1888, result=-1, data=null} to activity {com.example/com.example.Activity}: android.content.res.Resources$NotFoundException: Resource ID #0xffffffff
at android.app.ActivityThread.deliverResults(ActivityThread.java:4019)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4062)
at android.app.ActivityThread.access$1400(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1483)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5930)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
Caused by: android.content.res.Resources$NotFoundException: Resource ID #0xffffffff
at android.content.res.Resources.getValue(Resources.java:1542)
at android.support.v7.widget.ResourcesWrapper.getValue(ResourcesWrapper.java:204)
at android.support.v7.widget.AppCompatDrawableManager.loadDrawableFromDelegates(AppCompatDrawableManager.java:321)
at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:197)
at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:192)
at android.support.v7.widget.AppCompatImageHelper.setImageResource(AppCompatImageHelper.java:66)
at android.support.v7.widget.AppCompatImageView.setImageResource(AppCompatImageView.java:71)
at com.android.internal.app.AlertController.setupTitle(AlertController.java:565)
at com.android.internal.app.AlertController.setupView(AlertController.java:474)
at com.android.internal.app.AlertController.installContent(AlertController.java:240)
at android.app.AlertDialog.onCreate(AlertDialog.java:356)
at android.app.Dialog.dispatchOnCreate(Dialog.java:373)
at android.app.Dialog.show(Dialog.java:274)
at com.example.Activity.createDialog(Activity.java:697)
at com.example.Activity.onActivityResult(Activity.java:618)
at android.app.Activity.dispatchActivityResult(Activity.java:6441)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4015)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4062) 
at android.app.ActivityThread.access$1400(ActivityThread.java:177) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1483) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5930) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200) 
Also:
FATAL EXCEPTION: main
Process: com.example, PID: 9794
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1889, result=-1, data=Intent { dat=content://media/external/images/media/3196 flg=0x1 (has extras) }} to activity {com.example/com.example.Activity}: android.content.res.Resources$NotFoundException: Resource ID #0xffffffff
at android.app.ActivityThread.deliverResults(ActivityThread.java:4019)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4062)
at android.app.ActivityThread.access$1400(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1483)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5930)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200)
Caused by: android.content.res.Resources$NotFoundException: Resource ID #0xffffffff
at android.content.res.Resources.getValue(Resources.java:1542)
at android.support.v7.widget.ResourcesWrapper.getValue(ResourcesWrapper.java:204)
at android.support.v7.widget.AppCompatDrawableManager.loadDrawableFromDelegates(AppCompatDrawableManager.java:321)
at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:197)
at android.support.v7.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:192)
at android.support.v7.widget.AppCompatImageHelper.setImageResource(AppCompatImageHelper.java:66)
at android.support.v7.widget.AppCompatImageView.setImageResource(AppCompatImageView.java:71)
at com.android.internal.app.AlertController.setupTitle(AlertController.java:565)
at com.android.internal.app.AlertController.setupView(AlertController.java:474)
at com.android.internal.app.AlertController.installContent(AlertController.java:240)
at android.app.AlertDialog.onCreate(AlertDialog.java:356)
at android.app.Dialog.dispatchOnCreate(Dialog.java:373)
at android.app.Dialog.show(Dialog.java:274)
at com.example.Activity.createDialog(Activity.java:697)
at com.example.Activity.onActivityResult(Activity.java:639)
at android.app.Activity.dispatchActivityResult(Activity.java:6441)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4015)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4062) 
at android.app.ActivityThread.access$1400(ActivityThread.java:177) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1483) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5930) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1405) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1200) 
More info, this is my createDialog function which actually causing problems.
Drawable icon = new BitmapDrawable(this.getResources(),photo);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.business_post_camera_dialog_title))
.setMessage(getString(R.string.business_post_camera_dialog_message))
.setCancelable(false)
.setPositiveButton(R.string.sign_confirm_btn, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
doSomething();
}
})
.setNegativeButton(R.string.sign_cancel_btn, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(-1).setIcon(icon); //setIcon(-1) as a workaround for bug in Android Lollipop 5.0
AlertDialog alert = builder.create();
alert.show();
Apparently .setIcon(-1) causes the crash on Samsung phones, but without it I wouldn't be able to display my images there on certain phones still on Lollipop 5.0, any solution?
The problem is here:
...
Caused by: android.content.res.Resources$NotFoundException: Resource ID #0xffffffff
...
You are trying to use setImageResource(int id) with a non-exist image. You can use it like this:
imageView.setImageResource(R.drawable.image_name)
The same thing is available for TextView too.
textView.setText("" + intValue);
Try to use below method for dialog,
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
Drawable icon = new BitmapDrawable(this.getResources(),photo);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.business_post_camera_dialog_title))
.setMessage(getString(R.string.business_post_camera_dialog_message))
.setCancelable(false)
.setPositiveButton(R.string.sign_confirm_btn, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
doSomething();
}
})
.setNegativeButton(R.string.sign_cancel_btn, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
});
if (currentapiVersion >= android.os.Build.VERSION_CODES.LOLLIPOP){
builder.setIcon(-1).setIcon(icon);
} else{
builder.setIcon(icon);
}
AlertDialog alert = builder.create();
alert.show();

Java - Android - Main thread exception uploading by FTP

I'm developing a very simple app in which you press a button, the camera is launched, you take a photo and this photo is stored in the SD card and then uploaded to my FTP. I'm using simpleFTP library to connect to my FTP but I don't know why I'm getting the error below when uploading the file.
This is the relevant part of the code from the main class:
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
photoFile = null;
try {
photoFile = createImageFile();
Log.v("photoFile", photoFile.toString());
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
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 = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
//The image is already stored in the phone, let's open it up from there
File imgFile = photoFile;
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
mImageView.setImageBitmap(myBitmap);
}
new UploadFTP<File>().doInBackground(imgFile);
}
}
And this is the class that handle's the AsycnTask:
class UploadFTP<File> extends AsyncTask<File, Void, Void> {
#Override
protected Void doInBackground(File... params) {
File file = params[0];
try
{
SimpleFTP ftp = new SimpleFTP();
// Connect to an FTP server on port 21.
ftp.connect("ftp.myurl", 21, "myuser", "mypass");
// Set binary mode.
ftp.bin();
// Change to a new working directory on the FTP server.
ftp.cwd("www/xxx");
// Upload files.
ftp.stor(new java.io.File(String.valueOf(file)));
ftp.disconnect();
}
catch (IOException e)
{
e.printStackTrace();
}
return null;
}
}
And here the error:
FATAL EXCEPTION: main
Process: com.ignistudios.photosharing, PID: 22214
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {com.ignistudios.photosharing/com.ignistudios.photosharing.MainActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.deliverResults(ActivityThread.java:3607)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3650)
at android.app.ActivityThread.access$1400(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1370)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5294)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:110)
at libcore.io.IoBridge.connectErrno(IoBridge.java:137)
at libcore.io.IoBridge.connect(IoBridge.java:122)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:163)
at java.net.Socket.startupSocket(Socket.java:590)
at java.net.Socket.tryAllAddresses(Socket.java:128)
at java.net.Socket.<init>(Socket.java:178)
at java.net.Socket.<init>(Socket.java:150)
at org.jibble.simpleftp.SimpleFTP.connect(SimpleFTP.java:68)
at com.ignistudios.photosharing.UploadFTP.doInBackground(UploadFTP.java:26)
at com.ignistudios.photosharing.MainActivity.onActivityResult(MainActivity.java:139)
at android.app.Activity.dispatchActivityResult(Activity.java:6192)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3603)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3650) 
at android.app.ActivityThread.access$1400(ActivityThread.java:154) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1370) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5294) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699) 
You are using your AsyncTask the wrong way. Call execute on it and it automatically call doInBackground() on a different thread, where network operations are allowed.
UploadFTP uploadFTP = new UploadFTP();
uploadFTP.execute();

Categories