I am used to opening my files in my apps using the next code:
public void openFile(#NonNull String uri) {
checkNotNull(uri);
File file = new File(uri);
String dataType = null;
if (ContentTypeUtils.isPdf(uri)) dataType = "application/pdf";
else if (ContentTypeUtils.isImage(uri)) dataType = "image/*";
if (file.exists() && dataType != null) {
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file), dataType);
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent = Intent.createChooser(target, "Open file");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
Log.e(TAG, "There is a problem when opening the file :(");
}
} else {
Toast.makeText(getContext(), "Invalido", Toast.LENGTH_LONG).show();
}
}
I had always used static files so this was enough, but now I am using the Google Drive SDK for Android. I possess the driveId of the file I want to open but the problem is I cannot find a clean way to open the file contents I obtain by doing this:
Drive.DriveApi.fetchDriveId(mGoogleApiClient, documentFile.getDriveId())
.setResultCallback(driveIdResult -> {
PendingResult<DriveApi.DriveContentsResult> open =
driveIdResult.getDriveId().asDriveFile().open(
mGoogleApiClient,
DriveFile.MODE_READ_ONLY,
null);
open.setResultCallback(result -> {
DriveContents contents = result.getDriveContents();
InputStream inputStream = contents.getInputStream();
// I know I can get the input stream, and use it to write a new file.
});
});
So the only thing that comes to my mind is creating a static route to create a file every time I have to open it, and erasing it every time I have to open a new file.
What I have understood up until now is that the Google Drive API for Android already saves an instance of the file so what I have in mind sounds unnecessary, I would like to know if there is a better way to achieve this. Is there a way I can open the file and do something similar to what I do with the Intent.ACTION_VIEW in a cleaner way?
Thanks in advance.
Well since it seems this will not be answered I will post what I did. All I did was create a temp file where I put my contents to be read. I still don't know if it was the best choice so this question will still be opened for a better answer.
open.setResultCallback(result -> {
DriveContents contents = result.getDriveContents();
InputStream inputStream = contents.getInputStream();
writeTempFile(inputStream);
});
And here the implementation of the `writeTempFile`:
private synchronized File writeTempFile(#NonNull InputStream inputStream) {
checkNotNull(inputStream);
File filePath = new File(mActivity.getFilesDir(), "TempFiles");
if (!filePath.exists()) filePath.mkdirs();
File file = new File(filePath, TEMP_FILE);
try {
OutputStream outputStream = new FileOutputStream(file);
IOUtils.copyLarge(inputStream, outputStream);
IOUtils.closeQuietly(inputStream);
IOUtils.closeQuietly(outputStream);
} catch (IOException e) {
e.printStackTrace();
}
return file;
}
Related
I implemented a share button in my app. When I want to share, I can select a saved json data from the device and select via which way I want to share it (mail etc.). The problem is, that the data is NOT in the attachements. The problem is likely because I use the internal app storage. Therefore I want to save tje json data into the external storage, what would be better in my case anyway. But I am not really sure how to do that. I am not sure if I should use the Media type of content of the Documents and other files type of content which is provided by android. There is also the Appspecific files type but this looks like it is not applicaple for me, because I need to share the json data wit ha share functin. At the moment my code looks like this:
Save Function, which get's a file name I can choose myself
private void saveState(String name) {
File file = new File(getFilesDir(), name + ".json");
try{
OutputStream out = new FileOutputStream(file);
MyJsonWriter writer = new MyJsonWriter();
writer.writeJsonStream(out, ... //data structure);
out.close();
}catch (Exception e){
Log.e("saveState ERROR", "----------------------------------------------------");
}
}
LoadButtonClick Functin which shows me all files
public void loadStateClick(View view) {
final LinearLayout layout = new LinearLayout(MainActivity.this);
layout.setOrientation(LinearLayout.VERTICAL);
String[] files = MainActivity.this.fileList();
... //more code which is not important here
Load Function
private void loadState(String name) {
File file = new File(getFilesDir(), name);
InputStream in = null;
... //setting my data structure, not important here
try{
in = new FileInputStream(file);
MyJsonReader reader = new MyJsonReader(MainActivity.this);
SaveData savedData = reader.readJsonStream(in);
... // handling data structure, not important here
in.close();
}catch (Exception e){
Log.e("LOAD ERROR", e.toString());
}
}
I want to implement functionality for saving image in Downloads directory and after that offer to user to open this one in a directory (open directory in which user can find and open this image). But I've got one issue. Saving ends successfully, but when user clicks "OPEN" in snackbar and chooses app to perform this action another directory appears. It contains also "Downloads" directory as well, this Downloads directory does not contain saved images! It seems like in android we have two different "Downloads" directories.
Below is how i get path for save image:
private File getFileForImageSaving() {
String filename = getImageNameFromUrl(mImageUrl) + ".png";
File dest = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
filename);
int index = 1;
while (dest.exists()) {
filename = getImageNameFromUrl(mImageUrl) + "_" + index + ".png";
dest = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
filename);
index++;
}
return dest;
}
This is how i run activity for view "Download" directory and open files.
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
Uri uri = Uri.parse(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath());
intent.setDataAndType(uri, "image/png");
startActivity(Intent.createChooser(intent, "Open folder"));
This is how I save image. It is realy works, I've checked.
pri
vate void saveImageToFile() {
File dest = getFileForImageSaving();
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
FileOutputStream out = null;
try {
dest.createNewFile();
out = new FileOutputStream(dest);
Bitmap bitmap = Glide.with(ArticleImageViewActivity.this)
.load(mImageUrl)
.asBitmap()
.into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
.get();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
Utils.showInSnackBar(
ArticleImageViewActivity.this, getString(R.string.image_has_been_successfully_saved),
Snackbar.LENGTH_LONG,
onOpenImageInDirectoryListener,
getString(R.string.open_image_in_directory));
} catch (Exception e) {
Utils.showInSnackBar(ArticleImageViewActivity.this,
getString(R.string.error_occurred_during_saving_image),
Snackbar.LENGTH_SHORT, null, null);
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}.execute();
}
I partially resolve my problem by using Intent.ACTION_VIEW instead of Intent.ACTION_GET_CONTENT and " / " mime type instead of "image/png". But only partially because in this case user will be offered to choose a wide range of applications, but not only applications like filemanagers.
use MediaScannerConnection.scanFile to scan the file after saving. if you don't many/most galleries wont show your file.
https://developer.android.com/reference/android/media/MediaScannerConnection.html
I am having an issue, I have never had problem opening files via ACTION_VIEW the next way:
File file = new File(getActivity().getFilesDir(), TEMP_FILE_NAME);
String dataType = "image/*";
if (file.exists()) {
Intent fileIntent = new Intent(Intent.ACTION_VIEW);
fileIntent.setDataAndType(Uri.fromFile(file), dataType);
fileIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent = Intent.createChooser(fileIntent, "Open file");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
Log.e(TAG, "There is a problem when opening the file");
}
} else {
Toast.makeText(getContext(), "Invalido", Toast.LENGTH_LONG).show();
}
The problem I am having right now is that even though the file exists when I choose the app to open the file it immediately closes and tells me Not found. I have put the image I am loading in an image view and there is no problem, so the file is valid but for some reason it has conflicts when I am opening it via intent.
I am aware that it may have something to do with the way I am creating the file, I am retrieving it from Google drive so I am writing the file using the Apache Commons library the next way:
DriveContents contents = result.getDriveContents();
InputStream inputStream = contents.getInputStream();
File file = new File(getActivity().getFilesDir(), TEMP_FILE_NAME);
try {
OutputStream outputStream = new FileOutputStream(file);
IOUtils.copy(inputStream, outputStream);
IOUtils.closeQuietly(inputStream);
IOUtils.closeQuietly(outputStream);
} catch (IOException e) {
e.printStackTrace();
}
What is it I am doing wrong? I am not totally sure if the problem has to do with the copy method executing asynchronously or something like that.
Thanks in advance.
I have never had problem opening files via ACTION_VIEW the next way
That code will never work, as third-party apps have no rights to work with files on getFilesDir() of your app.
What is it I am doing wrong?
You are attempting to serve an inaccessible file to third-party programs. Use FileProvider to serve the file, using FileProvider.getUriForFile() to get the Uri to use in your ACTION_VIEW Intent.
Thanks for previous replies
I am doing application with android inbuilt voice recorder. i want to store the voice in specific location. but whenever i use the android in built voice recorder(using intent action) it save all voice into default folder. is there anyway to customize the location to save the voice. If anyone have idea pls guide me..
from com.android.soundrecorder.Recorder.java,we could find:
public void startRecording(int outputfileformat, String extension) {
if (mSampleFile == null) {
File sampleDir = Environment.getExternalStorageDirectory();
if (!sampleDir.canWrite()) // Workaround for broken sdcard support on the device.
sampleDir = new File("/sdcard/sdcard");
try {
mSampleFile = File.createTempFile(SAMPLE_PREFIX, extension, sampleDir);
} catch (IOException e) {
setError(SDCARD_ACCESS_ERROR);
return;
}
....
}
}
mSampleFile is created in code,
So...we can't customize the location to save the voice.
Try this code:
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + "DemoApplication"+File.separator+"Media"+File.separator+"audio"+File.separator);
if(root.exists())
root.delete();
root.mkdirs();
File voiceDirectory = new File(root, String.format("AudioFile_%d.amr", System.currentTimeMillis()));
outputFileUri = Uri.fromFile(voiceDirectory);
intent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
I have been trying to get the URI path for an asset file.
uri = Uri.fromFile(new File("//assets/mydemo.txt"));
When I check if the file exists I see that file doesn't exist
File f = new File(filepath);
if (f.exists() == true) {
Log.e(TAG, "Valid :" + filepath);
} else {
Log.e(TAG, "InValid :" + filepath);
}
Can some one tell me how I can mention the absolute path for a file existing in the asset folder
There is no "absolute path for a file existing in the asset folder". The content of your project's assets/ folder are packaged in the APK file. Use an AssetManager object to get an InputStream on an asset.
For WebView, you can use the file Uri scheme in much the same way you would use a URL. The syntax for assets is file:///android_asset/... (note: three slashes) where the ellipsis is the path of the file from within the assets/ folder.
The correct url is:
file:///android_asset/RELATIVEPATH
where RELATIVEPATH is the path to your resource relative to the assets folder.
Note the 3 /'s in the scheme. Web view would not load any of my assets without the 3. I tried 2 as (previously) commented by CommonsWare and it wouldn't work. Then I looked at CommonsWare's source on github and noticed the extra forward slash.
This testing though was only done on the 1.6 Android emulator but I doubt its different on a real device or higher version.
EDIT: CommonsWare updated his answer to reflect this tiny change. So I've edited this so it still makes sense with his current answer.
Finally, I found a way to get the path of a file which is present in assets from this answer in Kotlin. Here we are copying the assets file to cache and getting the file path from that cache file.
#Throws(IOException::class)
fun getFileFromAssets(context: Context, fileName: String): File = File(context.cacheDir, fileName)
.also {
if (!it.exists()) {
it.outputStream().use { cache ->
context.assets.open(fileName).use { inputStream ->
inputStream.copyTo(cache)
}
}
}
}
Get the path to the file like:
val filePath = getFileFromAssets(context, "fileName.extension").absolutePath
Please try this code working fine
Uri imageUri = Uri.fromFile(new File("//android_asset/luc.jpeg"));
/* 2) Create a new Intent */
Intent imageEditorIntent = new AdobeImageIntent.Builder(this)
.setData(imageUri)
.build();
Be sure ,your assets folder put in correct position.
Works for WebView but seems to fail on URL.openStream(). So you need to distinguish file:// protocols and handle them via AssetManager as suggested.
Try this out, it works:
InputStream in_s =
getClass().getClassLoader().getResourceAsStream("TopBrands.xml");
If you get a Null Value Exception, try this (with class TopBrandData):
InputStream in_s1 =
TopBrandData.class.getResourceAsStream("/assets/TopBrands.xml");
InputStream is = getResources().getAssets().open("terms.txt");
String textfile = convertStreamToString(is);
public static String convertStreamToString(InputStream is)
throws IOException {
Writer writer = new StringWriter();
char[] buffer = new char[2048];
try {
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
is.close();
}
String text = writer.toString();
return text;
}
try this :
Uri uri = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.cat);
I had did it and it worked
Yeah you can't access your drive folder from you android phone or emulator because your computer and android are two different OS.I would go for res folder of android because it has good resources management methods. Until and unless you have very good reason to put you file in assets folder. Instead You can do this
try {
Resources res = getResources();
InputStream in_s = res.openRawResource(R.raw.yourfile);
byte[] b = new byte[in_s.available()];
in_s.read(b);
String str = new String(b);
} catch (Exception e) {
Log.e(LOG_TAG, "File Reading Error", e);
}
If you are okay with not using assets folder and want to get a URI without storing it in another directory, you can use res/raw directory and create a helper function to get the URI from resID:
internal fun Context.getResourceUri(#AnyRes resourceId: Int): Uri =
Uri.Builder()
.scheme(ContentResolver.SCHEME_ANDROID_RESOURCE)
.authority(packageName)
.path(resourceId.toString())
.build()
Now if you have a mydemo.txt file under res/raw directory you can simply get the URI by calling the above helper method
context.getResourceUri(R.raw.mydemo)
Reference: https://stackoverflow.com/a/57719958
Worked for me Try this code
uri = Uri.fromFile(new File("//assets/testdemo.txt"));
String testfilepath = uri.getPath();
File f = new File(testfilepath);
if (f.exists() == true) {
Toast.makeText(getApplicationContext(),"valid :" + testfilepath, 2000).show();
} else {
Toast.makeText(getApplicationContext(),"invalid :" + testfilepath, 2000).show();
}