I am trying to get the file from picking image from photos and get intent data, save the file in internal memory and use the file to load on Image views.
But I am getting the error as follows:
java.io.FileNotFoundException: /storage/emulated/0/Android/data/com.dailyfaithapp.dailyfaith/Files/MI_10052020_1711.png: open failed: ENOENT (No such file or directory)
I checked on the lower version of api i.e. on 24 it worked once or twice but again it failed.
And on api 29 its not working at all. For that I followed this url :
https://medium.com/#sriramaripirala/android-10-open-failed-eacces-permission-denied-da8b630a89df
I checked the code in java and tried the same but still its giving the error.
I am also checking for runtime permissions and have specified permissions in manifest file.
Following is my code:
<uses-permission android:name = "android.permission.INTERNET" />
<uses-permission android:name = "android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name = "android.permission.WAKE_LOCK" />
<uses-permission android:name = "android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name = "android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name = "android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name = "com.google.android.apps.photos.permission.GOOGLE_PHOTOS" />
Checking runtime permissions :
private boolean checkPermission() {
return ContextCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
;
}
private void requestPermissionAndContinue() {
if (ContextCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(this, READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, WRITE_EXTERNAL_STORAGE)
&& ActivityCompat.shouldShowRequestPermissionRationale(this, READ_EXTERNAL_STORAGE)) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Allow Daily Faith to access photos," +
"media, and files on your device?");
alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(ThemesActivity.this,
new String[]{WRITE_EXTERNAL_STORAGE
, READ_EXTERNAL_STORAGE}, 200);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
Log.e("", "permission denied, show dialog");
} else {
ActivityCompat.requestPermissions(ThemesActivity.this,
new String[]{WRITE_EXTERNAL_STORAGE,
READ_EXTERNAL_STORAGE}, 200);
}
} else {
selectImageFromGallery();
}
}
Checking if permission is given:
if (!checkPermission()) {
selectImageFromGallery();
} else {
if (checkPermission()) {
requestPermissionAndContinue();
} else {
selectImageFromGallery();
}
}
Opening intent :
public void selectImageFromGallery()
{
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto , 2);
}
Get intent data on result :
#RequiresApi(api = Build.VERSION_CODES.KITKAT) #Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 2) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// The user picked a image.
// The Intent's data Uri identifies which item was selected.
if (data != null) {
customTheme = true;
// This is the key line item, URI specifies the name of the data
mImageUri = data.getData();
// Saves image URI as string to Default Shared Preferences
SharedPreferencesData sharedPreferencesData =
new SharedPreferencesData(this);
sharedPreferencesData.setStr("customThemeSet","true");
try {
Bitmap bitmap =
MediaStore.Images.Media.getBitmap(getContentResolver(), mImageUri);
/* Utils.storeImage(bitmap,
ThemesActivity.this);
File file = Utils.getOutputMediaFile(ThemesActivity.this);
*/
try {
final ParcelFileDescriptor parcelFileDescriptor = getContentResolver().openFileDescriptor(
mImageUri, "r");
final FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
Utils.storeImage(bitmap,
ThemesActivity.this);
File file = Utils.getOutputMediaFile(ThemesActivity.this);
int color = Utils.getDominantColor(bitmap);
Log.d("Bitmap", bitmap.toString());
Boolean isDark = Utils.isColorDark(color);
if(customTheme) {
for (Themes themes : themesArrayList) {
themes.setCustomTheme(file.getPath());
themes.setDark(isDark);
}
if(isDark)
sharedPreferencesData.setStr("ThemeColor","dark");
else
sharedPreferencesData.setStr("ThemeColor","light");
themesAdapter = new ThemesAdapter(themesArrayList, this,customTheme);
recyclerView.setAdapter(themesAdapter);
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
Log.e("Failed", "Failed to Parse Image Uri", e);
try {
throw new Exception("failed to parse image uri");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
}
}
Saving and getting file
public static File getOutputMediaFile(Context context){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ context.getApplicationContext().getPackageName()
+ "/Files");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
mediaStorageDir.mkdirs();
}
else {
return null;
}
// Create a media file name
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
File mediaFile;
String mImageName="MI_"+ timeStamp +".png";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
public static void storeImage(Bitmap image,Context context) {
File pictureFile = getOutputMediaFile(context);
if (pictureFile == null) {
Log.d(TAG,
"Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
Before I was getting EACCESS error when I only used above two funtions to save the file.
Later I tried Parcel file descriptor but not working
Why am I getting this error? Is it only on api level 29 or below too?
What can be the solution for this to run on all devices?
Here is what worked for me Using the downloads folder which all phones old and new have public access to..
try{
File csvfile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/brcOrdersaved.csv");
final String filename = csvfile.toString();
if (!csvfile.exists()) {
// displayMsg(context, "No Saved Order: ");
return (false);
}
FileReader fr = new FileReader(filename);
BufferedReader reader = new BufferedReader(fr);
String csvLine = "";
final char Separator = ',';
final char Delimiter = '"';
final char LF = '\n';
final char CR = '\r';
boolean quote_open = false;
if (reader.equals(null)) {
displayMsg(context, "NULL");
return (false);//rww 11/13/2021
}
int i = 0;
while (!myendofcsvfile) {
csvLine = reader.readLine();
if (csvLine == null) {
myendofcsvfile = true;
}
// do stuff here
}
fr.close();
fileexists = true;
} catch (Exception e) {
String msg = "Can not Load Saved Order ";
fileexists = false;
return (fileexists);
}
I add this permissions, and it works.
<uses-permission
enter code hereandroid:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"
tools:ignore="ProtectedPermissions" />
Related
Those are variables
private static final int FILECHOOSER_RESULTCODE = 1;
private ValueCallback<Uri> mUploadMessage;
private Uri mCapturedImageURI = null;
// the same for Android 5.0 methods only
private ValueCallback<Uri[]> mFilePathCallback;
private String mCameraPhotoPath;
This is the file chooser code
Usually it should create a image after taking the image, but it is creating a blank image before opening the camera intent, and then it is showing an error icon instead of showing the Image.
Please help me to fix the problem
public boolean onShowFileChooser(
WebView webView, ValueCallback<Uri[]> filePathCallback,
WebChromeClient.FileChooserParams fileChooserParams) {
if (mFilePathCallback != null) {
mFilePathCallback.onReceiveValue(null);
}
mFilePathCallback = filePathCallback;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// create the file where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
} catch (IOException ex) {
// Error occurred while creating the File
Log.e(TAG, "Unable to create Image File", ex);
}
// continue only if the file was successfully created
if (photoFile != null) {
mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("image/*");
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else {
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.image_chooser));
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
return true;
}
// creating image files (Lollipop only)
private File createImageFile() throws IOException {
// Create an image file name
Log.d(TAG, "createImageFile: creating Image");
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
mCameraPhotoPath = "file:" + image.getAbsolutePath();
return image;enter code here
}
On Activity Result code given below
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// code for all versions except of Lollipop
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == this.mUploadMessage) {
return;
}
Uri result = null;
try {
if (resultCode != RESULT_OK) {
result = null;
} else {
// retrieve from the private variable if the intent is null
result = data == null ? mCapturedImageURI : data.getData();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "activity :" + e, Toast.LENGTH_LONG).show();
}
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
} // end of code for all versions except of Lollipop
// start of code for Lollipop only
if (requestCode != FILECHOOSER_RESULTCODE || mFilePathCallback == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
Uri[] results = null;
// check that the response is a good one
if (resultCode == Activity.RESULT_OK) {
if (data == null || data.getData() == null) {
// if there is not data, then we may have taken a photo
if (mCameraPhotoPath != null) {
results = new Uri[]{Uri.parse(mCameraPhotoPath)};
}
} else {
String dataString = data.getDataString();
if (dataString != null) {
results = new Uri[]{Uri.parse(dataString)};
}
}
}
mFilePathCallback.onReceiveValue(results);
mFilePathCallback = null;
}
Remove this
return File.createTempFile(imageFileName,".jpg",storageDir);
Add this
File image = new File(storageDir.toString()+"/"+imageFileName+".jpg");
return image;
No exercise needed you came here for an answer i presume.
I want to call the camera through intent, capture images, and save it locally in the gallery and in the app-specific storage how can I achieve that?
I went through this question also but the code is not working I don't know why.
I'm assuming the app-specific storage is some sort of cache, in your onActivityResult() wouldn't you save the picture first to app-specific storage and then copy it to Environment.DIRECTORY_PICTURES?
I have done something like this Before, I Share my code with you and others that may help.
in this scenario if you want to save captured image, you have to check which api level that device is running with. for api level 28 and below you have to use specific method and for api level 28 above you have specific way.
so first step, start from:
AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="28" tools:ignore="ScopedStorage"/>
and add this line in to your AndroidManifest.xml application tag:
android:requestLegacyExternalStorage="true"
if your project targetSdkVersion is 28 and above, you have to use ActivityResultLauncher otherwise you have to override onRequestPermissionResult in your fragment or activity.
if you use fragment you have to register your ActivityResultLauncher in onAttach method, if not register it in onCreate of your Activity, so do this:
public class YourFragment extends Fragment {
private Bitmap bitmap;
private ActivityResultLauncher<String> storageResultActivity;
#Override
public void onAttach(#NonNull #NotNull Context context) {
super.onAttach(context);
registerWriteExternalStoragePermission();
}
registerWriteExternalStoragePermission has this codes:
private void registerWriteExternalStoragePermission() {
storageResultActivity = registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
if (isGranted) {
checkStoragePermissionAndSaveImage(bitmap);
}
});
}
so next step is to get back result of captured image from intent and change it to Bitmap for this section we need another activityResultLauncher so do this in onAttach of your fragment or onCreate of your activity:
ActivityResultLauncher<Intent> activityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
if (result.getResultCode() == RESULT_OK) {
Intent data = result.getData();
if (data == null || data.getData() == null) {
//showError
}
Uri uri = data.getData();
if (Build.VERSION.SDK_INT < 29) {
bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), uri);
} else {
ImageDecoder.Source source = ImageDecoder.createSource(context.getContentResolver(), uri);
bitmap = ImageDecoder.decodeBitmap(source);
}
}
so next step is to check your app has storage permission or not:
if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
saveImageInAndroidApi28AndBelow(bitmap);
} else if (ActivityCompat.shouldShowRequestPermissionRationale(requireActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
//show user app can't save image for storage permission denied
} else {
storageResultActivity.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
ok as we near the end of this answer :) you have to implement saveImageInAndroidApi28AndBelow method, se lets go to do it:
private boolean saveImageInAndroidApi28AndBelow(Bitmap bitmap) {
OutputStream fos;
String imagesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).toString();
File image = new File(imagesDir, "IMG_" + System.currentTimeMillis() + ".png");
try {
fos = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.PNG, 95, fos);
Objects.requireNonNull(fos).close();
} catch (IOException e) {
e.printStackTrace();
//isSuccess = false;
return false;
}
//isSuccess = true;
return true;
}
and the final step is to implement saveImageInAndroidApi29AndAbove method do it like this:
#NonNull
public Uri saveImageInAndroidApi29AndAbove(#NonNull final Bitmap bitmap) throws IOException {
final ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DISPLAY_NAME, "IMG_" + System.currentTimeMillis());
values.put(MediaStore.MediaColumns.MIME_TYPE, "image/png");
if (SDK_INT >= Build.VERSION_CODES.Q) {
values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM);
}
final ContentResolver resolver = requireContext().getContentResolver();
Uri uri = null;
try {
final Uri contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
uri = resolver.insert(contentUri, values);
if (uri == null) {
//isSuccess = false;
throw new IOException("Failed to create new MediaStore record.");
}
try (final OutputStream stream = resolver.openOutputStream(uri)) {
if (stream == null) {
//isSuccess = false;
throw new IOException("Failed to open output stream.");
}
if (!bitmap.compress(Bitmap.CompressFormat.PNG, 95, stream)) {
//isSuccess = false;
throw new IOException("Failed to save bitmap.");
}
}
//isSuccess = true;
return uri;
} catch (IOException e) {
if (uri != null) {
resolver.delete(uri, null, null);
}
throw e;
}
}
so you have to check which API Level that device is running and with with little code handle what you want:
if (SDK_INT >= Build.VERSION_CODES.Q) {
try {
saveImageInAndroidApi29AndAbove(bitmap);
} catch (Exception e) {
//show error to user that operatoin failed
}
} else {
saveImageInAndroidApi28AndBelow(bitmap);
}
Don't FORGET TO call .launch ON YOUR ActivityResultLauncher
have a good time with the codes :)
Simple, make a Launcher attach the camera and gallery and you have everything in one place, here I send you 2 links to make a launcher
https://code.tutsplus.com/es/tutorials/build-a-custom-launcher-on-android--cms-21358
https://steemit.com/utopian-io/#ideba/how-to-build-a-custom-android-launcher-and-home-screen-application-part-1
Whenever you take a photo from the device, you the image uri in the onActivityResult. Now to save it to another location, you can use the code given below
void savefile(Uri sourceuri){
String sourceFilename= sourceuri.getPath();
String destinationFilename = android.os.Environment.getExternalStorageDirectory().getPath()+File.separatorChar+"abc.mp3";
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(sourceFilename));
bos = new BufferedOutputStream(new FileOutputStream(destinationFilename, false));
byte[] buf = new byte[1024];
bis.read(buf);
do {
bos.write(buf);
} while(bis.read(buf) != -1);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bis != null) bis.close();
if (bos != null) bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
And in the onActivityResult, you can call it like this
saveFile(data.getData());
Hello I am tring to open a .pdf file present in a file using an intent but it is giving me 2 errors on the following line
File file = new File(getContext().getAssets().open("assets/test.pdf"));
Errors
1.Unhandled java.IO.Exception.
2.getAssets()may produce java.lang.NullPointerException
Here us the code in a fragment
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 0) {
File file = new File(getContext().getAssets().open("assets/test.pdf"));
if (file .exists())
{
Uri path = Uri.fromFile(file );
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent.setDataAndType(path , "application/pdf");
pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try
{
startActivity(pdfIntent ); }
catch (ActivityNotFoundException e)
{
Toast.makeText(getActivity(), "Please install a pdf file viewer",
Toast.LENGTH_LONG).show();
}
}
}
}
File fileBrochure = new File(Environment.getExternalStorageDirectory() + "/" + "abc.pdf");
if (!fileBrochure.exists())
{
CopyAssetsbrochure();
}
/** PDF reader code */
File file = new File(Environment.getExternalStorageDirectory() + "/" + "abc.pdf");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),"application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try
{
getApplicationContext().startActivity(intent);
}
catch (ActivityNotFoundException e)
{
Toast.makeText(SecondActivity.this, "NO Pdf Viewer", Toast.LENGTH_SHORT).show();
}
}
//method to write the PDFs file to sd card
private void CopyAssetsbrochure() {
AssetManager assetManager = getAssets();
String[] files = null;
try
{
files = assetManager.list("");
}
catch (IOException e)
{
Log.e("tag", e.getMessage());
}
for(int i=0; i<files.length; i++)
{
String fStr = files[i];
if(fStr.equalsIgnoreCase("abc.pdf"))
{
InputStream in = null;
OutputStream out = null;
try
{
in = assetManager.open(files[i]);
out = new FileOutputStream(Environment.getExternalStorageDirectory() + "/" + files[i]);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
break;
}
catch(Exception e)
{
Log.e("tag", e.getMessage());
}
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
You cannot open the pdf file directly from the assets folder.You first have to write the file to sd card from assets folder and then read it from sd card
try with the file provider
Intent intent = new Intent(Intent.ACTION_VIEW);
// set flag to give temporary permission to external app to use your FileProvider
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
// generate URI, I defined authority as the application ID in the Manifest, the last param is file I want to open
String uri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID, file);
// I am opening a PDF file so I give it a valid MIME type
intent.setDataAndType(uri, "application/pdf");
// validate that the device can open your File!
PackageManager pm = getActivity().getPackageManager();
if (intent.resolveActivity(pm) != null) {
startActivity(intent);
}
To serve a file from assets to another app you need to use a provider.
Google for the StreamProvider of CommonsWare.
As a preface, I am familiar with coding (2 years in highschool) but am a complete novice when it comes to Android Studio (and Java, in general). I've been searching for solutions for my problem, but due to my inexperience I have no idea how to implement the solutions to my project.
In short, I need to download a pdf from some external URL, store it into external storage, and display it using some pdf-viewer application. I've been getting error:
...
android.os.FileUriExposedException: file:///storage/emulated/0/pdf/Read.pdf exposed beyond app through Intent.getData()
...
I've been using this source on using an intent to open a pdf-viewer and this source on "File Provider" as references.
Below is what I have so far:
Fire (with a clickable TextView that should download and display the pdf)
public class Fire extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fire);
final TextView testButton = findViewById(R.id.testPDF);
// File file = getFilesDir();
testButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Fire.this, pdfView.class);
startActivity(intent);
}
});
pdfView activity
public class pdfView extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdf_view);
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "pdf");
folder.mkdir();
File file = new File(folder, "Read.pdf");
try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
Downloader.DownloadFile(__PDF_URL___, file);
showPdf();
}
public void showPdf()
{
File file = new File(Environment.getExternalStorageDirectory()+"/pdf/Read.pdf");
PackageManager packageManager = getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
}
Downloader class
public class Downloader {
public static void DownloadFile(String fileURL, File directory) {
try {
FileOutputStream f = new FileOutputStream(directory);
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
e.printStackTrace();
}
}
From my research, it seems that my problem stems from my usage of URI instead of a "File provider." Also, it seems the solution that implements a "File Provider" uses Context in some form or another, and I'm confused on what the purpose of context is and how to implement it.
If you do not have answers that is fine. Any information on how to figure this out or even understand the concept is good enough for me.
If your targetSdkVersion >= 24, then we have to use FileProvider class to give access to the particular file or folder to make them accessible for other apps.
1) First Add a FileProvider tag in AndroidManifest.xml under tag as below:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
...
<application
...
<provider
android:name=".GenericFileProvider"
android:authorities="${applicationId}.my.package.name.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths"/>
</provider>
</application>
</manifest>
2) Then create a provider_paths.xml file in res/xml folder. Folder may be needed to created if it doesn't exist.
<paths>
<external-path name="external_files" path="."/>
</paths>
3) Now create PdfDownload.java class file and paste below code:
public class PdfDownload extends Activity {
TextView tv_loading;
Context context;
int downloadedSize = 0, totalsize;
float per = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
isStoragePermissionGranted();
super.onCreate(savedInstanceState);
tv_loading = new TextView(this);
tv_loading.setGravity(Gravity.CENTER);
tv_loading.setTypeface(null, Typeface.BOLD);
setContentView(tv_loading);
downloadAndOpenPDF();
}
public static String getLastBitFromUrl(final String url) {
return url.replaceFirst(".*/([^/?]+).*", "$1");
}
void downloadAndOpenPDF() {
final String download_file_url = getIntent().getStringExtra("url");
new Thread(new Runnable() {
public void run() {
Uri path = Uri.fromFile(downloadFile(download_file_url));
try {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri uri = FileProvider.getUriForFile(PdfDownload.this, BuildConfig.APPLICATION_ID, downloadFile(download_file_url));
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
finish();
} catch (ActivityNotFoundException e) {
tv_loading
.setError("PDF Reader application is not installed in your device");
}
}
}).start();
}
File downloadFile(String dwnload_file_path) {
File file = null;
try {
URL url = new URL(dwnload_file_path);
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.connect();
String test = getLastBitFromUrl(dwnload_file_path);
String dest_file_path = test.replace("%20", "_");
// set the path where we want to save the file
File SDCardRoot = Environment.getExternalStorageDirectory();
// // create a new file, to save the downloaded file
file = new File(SDCardRoot, dest_file_path);
if (file.exists()) {
return file;
}
FileOutputStream fileOutput = new FileOutputStream(file);
// Stream used for reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
// this is the total size of the file which we are
// downloading
totalsize = urlConnection.getContentLength();
setText("Starting PDF download...");
// create a buffer...
byte[] buffer = new byte[1024 * 1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
per = ((float) downloadedSize / totalsize) * 100;
if ((totalsize / 1024) <= 1024) {
setText("Total PDF File size : " + (totalsize / 1024)
+ " KB\n\nDownloading PDF " + (int) per + "% complete");
} else {
setText("Total PDF File size : " + (totalsize / 1024) / 1024
+ " MB\n\nDownloading PDF " + (int) per + "% complete");
}
// setText("configuring your book pleease wait a moment");
}
// close the output stream when complete //
fileOutput.close();
// setText("Download Complete. Open PDF Application installed in the device.");
setText("configuaration is completed now your book is ready to read");
} catch (final MalformedURLException e) {
setTextError("Some error occured. Press back and try again.",
Color.RED);
} catch (final IOException e) {
setTextError("Some error occured. Press back and try again.",
Color.RED);
} catch (final Exception e) {
setTextError(
"Failed to download image. Please check your internet connection.",
Color.RED);
}
return file;
}
void setTextError(final String message, final int color) {
runOnUiThread(new Runnable() {
public void run() {
tv_loading.setTextColor(color);
tv_loading.setText(message);
}
});
}
void setText(final String txt) {
runOnUiThread(new Runnable() {
public void run() {
tv_loading.setText(txt);
}
});
}
private static final String TAG = "MyActivity";
public boolean isStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v(TAG, "Permission is granted");
return true;
} else {
Log.v(TAG, "Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
} else { //permission is automatically granted on sdk<23 upon installation
Log.v(TAG, "Permission is granted");
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.v(TAG, "Permission: " + permissions[0] + "was " + grantResults[0]);
}
}
}
I am having trouble in writing the file to sd card. (I am using Android 5.1 sdk version 23).
I have even tried the following code which prompts the user to select the user, where I select the "Sd card" and persist the permissions.
Manifest also has the write permission.
AndroidManifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
public writeToFile() {
String filePath = "/storage/sdcard1/FileBrowser/Music";
File file = new File(filePath);
File parentDir = file.getParentFile();
if (parentDir != null) {
Log.d(TAG, parentDir.toString());
Log.d(TAG, file.getName());
File newFile = new File(parentDir + "/test.txt");
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(newFile));
writer.write("Hello", 0, "Hello".length());
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Log.d(TAG, "Parent file is null");
}
}
private void takeWritePermission() {
if(Build.VERSION.SDK_INT > 19) {
List<UriPermission> permissionList = getActivity().getContentResolver().getPersistedUriPermissions();
if (permissionList != null) {
UriPermission permission = permissionList.get(0);
if (permission == null) {
startPermissionActivity();
} else {
if (permission.isWritePermission()) {
writeToFile();
} else {
startPermissionActivity();
}
}
} else {
startPermissionActivity();
}
}
}
private void startPermissionActivity() {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intent, 42);
}
public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
if(Build.VERSION.SDK_INT > 19) {
if (resultCode == AppCompatActivity.RESULT_OK) {
Uri treeUri = resultData.getData();
getActivity().getContentResolver().takePersistableUriPermission(treeUri,
Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
writeToFile();
}
}
}
> Exception: java.io.FileNotFoundException:
> /storage/sdcard1/FileBrowser/Music/test.txt: open failed: EACCES
> (Permission denied) at libcore.io.IoBridge.open(IoBridge.java:456)
> at java.io.FileOutputStream.<init>(FileOutputStream.java:87) at
> java.io.FileOutputStream.<init>(FileOutputStream.java:72) at
> java.io.FileWriter.<init>(FileWriter.java:42)