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();
Related
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());
I am developing an Android Application that takes a picture and saves a full-size picture onto the device. I have mostly taken help from developers android site. When I run my code and try to take the picture the application crashes instantly. The code I am using is as follows:
static final int REQUEST_IMAGE_CAPTURE = 1;
static final int REQUEST_TAKE_PHOTO = 1;
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
System.out.println("Error in Dispatch Take Picture Intent");
}
// 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);
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
//Bundle extras = data.getExtras();
//Bitmap imageBitmap = (Bitmap) extras.get("data");
//imageView.setImageBitmap(imageBitmap);
Toast.makeText(getApplicationContext(),"Working",Toast.LENGTH_LONG).show();
}
}
String currentPhotoPath;
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
currentPhotoPath = image.getAbsolutePath();
return image;
}
private View.OnClickListener onCamClick() {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("Starting Camera Activity");
//dispatchTakePictureIntent();
//Toast.makeText(getApplicationContext(),"Working",Toast.LENGTH_LONG).show();
dispatchTakePictureIntent();
}
};
}
When I run my code I get the following error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.zaeem.tia, PID: 15468
java.lang.IllegalArgumentException: Failed to find configured root that contains /storage/emulated/0/Android/data/com.zaeem.tia/files/Pictures/JPEG_20200301_003227_1043176843378455577.jpg
at androidx.core.content.FileProvider$SimplePathStrategy.getUriForFile(FileProvider.java:739)
at androidx.core.content.FileProvider.getUriForFile(FileProvider.java:418)
at com.zaeem.tia.app.activities.MainActivity.dispatchTakePictureIntent(MainActivity.java:121)
at com.zaeem.tia.app.activities.MainActivity.access$000(MainActivity.java:40)
at com.zaeem.tia.app.activities.MainActivity$1.onClick(MainActivity.java:164)
at android.view.View.performClick(View.java:7339)
at android.widget.TextView.performClick(TextView.java:14221)
at android.view.View.performClickInternal(View.java:7305)
at android.view.View.access$3200(View.java:846)
at android.view.View$PerformClick.run(View.java:27787)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7076)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)
filepath.xml file:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-files-path name="my_images" path="Android/data/com.zaeem.tia.app.activities/files/Pictures" />
</paths>
Please advise regarding this matter.
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
Here, you are saying that the authority string for your FileProvider is com.example.android.fileprovider. Based on the error, that is not what you have on the <provider> element in the manifest.
add this in your manifest.xml (after ):
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="android.getqardio.com.gmslocationtest"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths"/>
</provider>
Create provider_paths on Resources/xml, and add this content:
<?xml version="1.0" encoding="utf-8"?>
<paths>
<files-path
name="share"
path="external_files"/>
</paths>
Activity:
File imagePath = new File(getFilesDir(), "external_files");
imagePath.mkdir();
File imageFile = new File(imagePath.getPath(), "test.jpg");
// Write data in your file
Uri uri = FileProvider.getUriForFile(this, getPackageName(), imageFile);
Intent intent = ShareCompat.IntentBuilder.from(this)
.setStream(uri) // uri from FileProvider
.setType("text/html")
.getIntent()
.setAction(Intent.ACTION_VIEW) //Change if needed
.setDataAndType(uri, "image/*")
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
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
How to use FileProvider for not getting error in android API >= 24?
I've tried FileProvider but it's still getting error...
Here is my source code
if(vid.equals("")) {
inFileName = img.substring(img.lastIndexOf('/') + 1);
File sdcard = Environment.getExternalStorageDirectory();
File filex = new File(sdcard, inDir + "/" + "IMAGE_" + inFileName);
if(filex.exists()) {
if (inDialog.isShowing())
inDialog.dismiss();
Uri uri = Uri.parse("file://" + filex.toString());
Intent i = new Intent();
i.setAction(Intent.ACTION_VIEW);
i.setDataAndType(uri, "image/*");
inContext.startActivity(i);
} else {
inTmp = Uri.parse(img);
Image_DownloadId = DownloadData(inTmp, "IMAGE_" + inFileName);
}
}
First log
android.os.FileUriExposedException: file:///storage/emulated/0/Images/IMAGE_26072028_383759662086144_8624202031520808960_n.jpg exposed beyond app through Intent.getData()
This error because of using android api >= 24 and need to use FileProvider, so I try to use it..
this line is a little bit confusing because of using toString method
Uri.parse("file://" + filex.toString())
Here is what I'm trying to do
if(vid.equals("")) {
inFileName = img.substring(img.lastIndexOf('/') + 1);
File sdcard = Environment.getExternalStorageDirectory();
File filex = new File(sdcard, inDir + "/" + "IMAGE_" + inFileName);
if(filex.exists()) {
if (inDialog.isShowing())
inDialog.dismiss();
Uri uri = FileProvider.getUriForFile(inContext, inContext.getApplicationContext().getPackageName() + ".provider", new File("file://" + filex.toString()));
Intent i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(uri, "image/*");
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
inContext.startActivity(i);
} else {
inTmp = Uri.parse(img);
Image_DownloadId = DownloadData(inTmp, "IMAGE_" + inFileName);
}
The application still getting force close.
Here is the log
01-14 17:48:24.288 23382-23382/com.my.app E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.my.app, PID: 23382
java.lang.IllegalArgumentException: Failed to find configured root that contains /file:/storage/emulated/0/Images/IMAGE_26072028_383759662086144_8624202031520808960_n.jpg
at android.support.v4.content.FileProvider$SimplePathStrategy.getUriForFile(FileProvider.java:711)
at android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:400)
at com.my.app.App$Loading$1.onClick(Saver.java:128)
at android.view.View.performClick(View.java:5619)
at android.view.View$PerformClick.run(View.java:22295)
at android.os.Handler.handleCallback(Handler.java:754)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6321)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:880)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:770)
Got another error in this line
String filename = cursor.getString(filenameIndex);
BroadcastReceiver downloadReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//check if the broadcast message is for our Enqueued download
long referenceId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
if(referenceId == Image_DownloadId) {
DownloadManager.Query ImageDownloadQuery = new DownloadManager.Query();
//set the query filter to our previously Enqueued download
ImageDownloadQuery.setFilterById(Image_DownloadId);
//Query the download manager about downloads that have been requested.
Cursor cursor = downloadManager.query(ImageDownloadQuery);
if(cursor.moveToFirst()){
int filenameIndex = cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME);
String filename = cursor.getString(filenameIndex);
Uri uri = Uri.parse("file://" + filename);
Intent i = new Intent();
if(inTenTipe.equals("repost")) {
i.setAction(Intent.ACTION_SEND);
i.putExtra(Intent.EXTRA_STREAM, uri);
i.setType("image/*");
}else {
i.setAction(Intent.ACTION_VIEW);
i.setDataAndType(uri, "image/*");
}
try {
if (inDialog.isShowing())
inDialog.dismiss();
inContext.startActivity(i);
} catch (android.content.ActivityNotFoundException ex) {
File file = new File(filename);
boolean deleted = file.delete();
Image_DownloadId = DownloadData(inTmp, "IMAGE_" + inFileName);
}
}
}
}
}
Log
FATAL EXCEPTION: main
Process: com.my.app, PID: 29139
java.lang.RuntimeException: Error receiving broadcast Intent { act=android.intent.action.DOWNLOAD_COMPLETE flg=0x10 pkg=com.my.app (has extras) } in com.my.app.APP$1#cc58ede
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:1140)
at android.os.Handler.handleCallback(Handler.java:754)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6321)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:880)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:770)
Caused by: java.lang.SecurityException: COLUMN_LOCAL_FILENAME is deprecated; use ContentResolver.openFileDescriptor() instead
at android.app.DownloadManager$CursorTranslator.getString(DownloadManager.java:1791)
at com.my.app.App$1.onReceive(Saver.java:616)
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:1130)
at android.os.Handler.handleCallback(Handler.java:754)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6321)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:880)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:770)
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.