Uri String not Caching in android - java

Helo guys,
I am using following Code.
String fileName = "image" + "_" + title.getText().toString()+"_" + val.toString();
photo = this.createFile(fileName, ".jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
uriOfPhoto = Uri.fromFile(photo);
startActivityForResult(intent, RESULT_CAMERA_SELECT);
}
}
catch(Exception e)
{
Log.v("Error", "Can't create file to take picture!");
displayAlert("Can't create file to take picture!","SDCard Error!");
}
}
private File createFile(String part, String ext) throws Exception
{
File tempDir = new File (Environment.getExternalStorageDirectory() + "/MyFolder/Images");
if(!tempDir.exists())
{
tempDir.mkdir();
}
tempDir.canWrite();
return new File(tempDir, part+ext);
}
});
The UriOfPhoto is giving me uriString not chached in debug. It is not storing uri of the file.How can i resolve this issue.
authority Uri$Part$EmptyPart (id=830004244032)
fragment Uri$Part$EmptyPart (id=830004245408)
host "NOT CACHED" (id=830003914304)
path Uri$PathPart (id=830067926736)
port -2
query Uri$Part$EmptyPart (id=830004245408)
scheme "file" (id=830002660688)
ssp null
uriString "NOT CACHED" (id=830003914304)
userInfo null
Best Regards

This isn't enough info. What action are you putting into the intent you send? Are you sure that createFile actually creates a file?
The error listing you give isn't very useful. Is it part of the listing of variable values from debug? If so, where are you in the code when you look at the values?

String fileName = Environment.getExternalStorageDirectory() + "/MyFolder/Images" + fileName + ".jpg";
UriOfPhoto = Uri.parse(fileName);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.putExtra(MediaStore.EXTRA_OUTPUT, UriOfPhoto);
startActivityForResult(intent, RESULT_CAMERA_SELECT);
also the is no need of creating file for store photo you need to just pass the uri where the photo must be as above the Android OS create a file as you were trying to do and stores the captured image in that uri.

Related

java.io.FileNotFoundException: No content provider: /storage/emulated/0/test_video.mp4

Generally a video is chosen from the gallery and cut with a library, the problem is that I need to convert that cut video (that it is stored in the external memory: /storage/emulated/0/test_video.mp4) to base64 and that's where it fails. How can I solve it?
I already put the permissions on the manifest and request for them programmatically.
//Getting video from previous activity
Uri selectedVideo = Uri.parse(intent.getStringExtra("trimmedVideo"));
Log.d(Global.getTag(), "path: "+selectedVideo.toString());
//Converting Selected video to base64
try {
InputStream in = getContentResolver().openInputStream(selectedVideo); <---This line fails
byte[] bytes = Global.getBytes(in);
Log.d(Global.getTag(), "bytes size= "+bytes.length);
video_base64 = Base64.encodeToString(bytes,Base64.DEFAULT);
Log.d(Global.getTag(), "Base64string= "+ video_base64);
} catch (Exception e) {
e.printStackTrace();
}
And all I get in logcast is:
I found the solution on a github post! Just need to include this:
//Getting video from previous activity
Uri selectedVideo = Uri.parse(intent.getStringExtra("trimmedVideo"));
Uri selectedVideoFinal = null;
if (selectedVideo.getScheme() == null){
selectedVideoFinal = Uri.fromFile(new File(selectedVideo.getPath()));
}else{
selectedVideoFinal = selectedVideo;
}
Log.d(Global.getTag(), "path: "+selectedVideoFinal);
MediaMetadataRetriever mMMR = new MediaMetadataRetriever(); ...continue code

Create a folder like WhatsApp Images, WhatsApp Videos in Albums or Gallery

My requirement is to show directory under Gallery/ Albums,
creating a directory in the following way does not full fill my requirement...
File rootPath = new File(Environment.getExternalStorageDirectory(), "directoryName");
if(!rootPath.exists()) {
rootPath.mkdirs();
}
final File localFile = new File(rootPath,fileName);
by using this code i can see the folder by using "file mangaer" with the path...
"deviceStorage/directoryName" but the folder is not visible under Gallery or Albums
for directory creation i tried the following ways too...
1)File directory = new File(this.getFilesDir()+File.separator+"directoryName");
2)File directory = new File (Environment.getExternalFilesDir(null) + "/directoryName/");
3)File directory = new File(Environment.
getExternalStoragePublicDirectory(
(Environment.DIRECTORY_PICTURES).toString() + "/directoryName");
but no luck, please help me friends
thanks in advance.
check this solution as well:
String path = Environment.getExternalStorageDirectory().toString();
File dir = new File(path, "/appname/media/app images/");
if (!dir.isDirectory()) {
dir.mkdirs();
}
File file = new File(dir, filename + ".jpg");
String imagePath = file.getAbsolutePath();
//scan the image so show up in album
MediaScannerConnection.scanFile(this,
new String[] { imagePath }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
if(Config.LOG_DEBUG_ENABLED) {
Log.d(Config.LOGTAG, "scanned : " + path);
}
}
});
Try this one.
File root = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + File.separator + "albums");
boolean rootCreated = false;
if (!root.exists())
rootCreated = root.mkdir();
You can use MediaStore API to save your media files like that:
val values = ContentValues().apply {
put(MediaStore.Images.Media.DISPLAY_NAME, "filename")
put(MediaStore.Images.Media.RELATIVE_PATH, "${Environment.DIRECTORY_DCIM}/$directoryName")
put(MediaStore.Images.Media.MIME_TYPE, mimeType)
}
val collection = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
val item = context.contentResolver.insert(collection, values) ?: throw IOException("Insert failed")
resolver.openFileDescriptor(item, "w", null)?.use {
writeImage(it.fileDescriptor)
}
This will save the media files to the media collections and make it available to the gallery. Gallery app normally shows your directoryName as an album.
Checked on Samsungs S10 and above with Android 10.
heres the java.nio library way to create directory
Java Code
File targetFile = new File(Environment.getExternalStorageDirectory(), "subDir");
Path sourceFile = Paths.get(targetFile.getAbsolutePath());
Files.createDirectory(sourceFile);
some android phone create .nomedia file inside the created app folder to prevent media from being shown in gallery app so you may check if this hidden file exists and delete it if it exists. set folder and files readable. you may wait quite time before system reflect your created file in your gallery app.
val parentFile = File(Environment.getExternalStorageDirectory(), "MyAppFolder")
if(!parentFile.exists())
parentFile.mkdir()
parentFile.setReadable(true)
// .nomedia file prevents media from being shown in gallery app
var nomedia = File(parentFile, ".nomedia")
if(nomedia.exists()){
nomedia.delete()
}
val file = File(parentFile , "myvideo.mp4")
file.setReadable(true)
input.use { input ->
var output: FileOutputStream? = null
try {
output = FileOutputStream(file)
val buffer = ByteArray(4 * 1024)
var read: Int = input.read(buffer)
while (read != -1) {
output.write(buffer)
read = input.read(buffer)
}
output.flush()
// file written to memory
} catch (ex: Exception) {
ex.printStackTrace()
} finally {
output?.close()
}
}

how do i share and save image and text together with Intent.ACTION_SEND?

i want to save and share image with text , and im using
i.putExtra(Intent.EXTRA_TEXT, shareMessages);
i.putExtra(Intent.EXTRA_STREAM,path);
i.setType("image/*");
i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
save image actually working !
but the result is :
Share Failed! on device
and
W/Bundle: Key android.intent.extra.STREAM expected Parcelable but value was a java.lang.String. The default value <null> was returned.
in logcat
maybe you can help me after see the full code below :
cardTotal.setDrawingCacheEnabled(true);
Bitmap b = cardTotal.getDrawingCache();
int random = new Random().nextInt((100000 - 100)+ 1) + 100000;
Long expense = getArguments().getLong("expense", 0);
Long income = getArguments().getLong("income", 0);
String shareMessages;
File root = Environment.getExternalStorageDirectory();
String path = root.toString() + "/" +textTitle.getText().toString()+random+ "mycarta.png";
if (!income.equals(0L)){
shareMessages = "Hey i get my income from" + textTitle.getText().toString() + "\n\n" + "Download MyCarta! Make your life easier, happier!";
}else {
shareMessages = "Hey i was doing " + textTitle.getText().toString() + "\n\n" + "Download MyCarta! Make your life easier, happier!";
}
try {
b.compress(Bitmap.CompressFormat.PNG, 95, new FileOutputStream(path));
System.out.println("SUCCESS============");
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("ERROR==============");
}
FileInputStream finalPath = new FileInputStream(new File(path));
finalPath.close();
Intent i = new Intent();
i.setAction(Intent.ACTION_SEND);
i.putExtra(Intent.EXTRA_TEXT, shareMessages);
i.putExtra(Intent.EXTRA_STREAM,path);
i.setType("image/*");
i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(i,"Share"));
}
Any help or suggestions will be appreciate
you must using Uri.parse(namepath.getAbsoultePath);
this is my code and actually working
File root = Environment.getExternalStorageDirectory();
String location = "/" +textTitle.getText().toString()+random+"mycarta.png";
String path = root.toString() + location;
File imageDir = new File(root,location);
and use imageDir on the Intent.EXTRA_STREAM , like below :
Intent i = new Intent();
i.setAction(Intent.ACTION_SEND);
i.setType("image/png");
i.putExtra(Intent.EXTRA_TEXT, shareMessages);
i.putExtra(Intent.EXTRA_STREAM, Uri.parse(imageDir.getAbsolutePath()));
i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(i,"Share"));

Unable to attach picture programmatically in email

I have a function that I want to automatically take a screenshot and then upload it to the users preferred email app.
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
try {
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".png";
// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
File imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.PNG, quality, outputStream);
outputStream.flush();
outputStream.close();
File filelocation = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + now + mPath);
Uri path = Uri.fromFile(filelocation);
Intent emailIntent = new Intent(Intent.ACTION_SEND);
// set the type to 'email'
emailIntent .setType("vnd.android.cursor.dir/email");
String to[] = {"Enter your email address"};
emailIntent .putExtra(Intent.EXTRA_EMAIL, to);
// the attachment
emailIntent.putExtra(Intent.EXTRA_STREAM, path);
// the mail subject
emailIntent .putExtra(Intent.EXTRA_SUBJECT, "Journey : ");
startActivity(Intent.createChooser(emailIntent , "Select your preferred email app.."));
} catch (Throwable e) {
// Several error may come out with file handling or DOM
e.printStackTrace();
}
}
This is my function. It is taking the screen shot automatically and its store it on my local device. It is also prompting the user to select their email app. Then I select an app it says "unable to attach file" . I have read and write permissions in my manifest.
The other app may not have access to external storage. Plus, your code will crash on Android 7.0+, once you raise your targetSdkVersion to 24 or higher.
Switch to using FileProvider and its getUriForFile() method, instead of using Uri.fromFile().
And, eventually, move that disk I/O to a background thread.
check this link -
https://www.javacodegeeks.com/2013/10/send-email-with-attachment-in-android.html
and How to send an email with a file attachment in Android
Hope this help.
The problem was :
Uri path = Uri.fromFile(filelocation);
Instead I used :
File filelocation = new File(MediaStore.Images.Media.DATA + mPath);
Uri myUri = Uri.parse("file://" + filelocation);
Hopefully this helps anyone facing the same problem.

Get Uri from file in either assets or res/raw

I have tried to get this working and I have looked at many different resources online (as you can see from all of the comments I have made). I want to access a .pdf file that is either located in assets or res; It does not matter to which one so the easiest way will do.
I have the method below that will get the actual file and will call another method(under the first method below) with the Uri in the parameters.
Thank you very much for your help and I will be standing by to answer questions or add more content.
private void showDocument(File file)
{
//////////// ORIGINAL ////////////////////
//showDocument(Uri.fromFile(file));
//////////////////////////////////////////
// try 1
//File file = new File("file:///android_asset/RELATIVEPATH");
// try 2
//Resources resources = this.getResources();
// try 4
String PLACEHOLDER= "file:///android_asset/example.pdf";
File f = new File(PLACEHOLDER);
//File f = new File("android.resource://res/raw/slides1/example.pdf");
//getResources().openRawResource(R.raw.example);
// try 3
//Resources resources = this.getResources();
//showDocument(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + resources.getResourcePackageName(R.raw.example) + '/' + resources.getResourceTypeName(R.raw.example) + '/' + resources.getResourceEntryName(R.raw.example)));
showDocument(Uri.fromFile(f));
}
protected abstract void showDocument(Uri uri);
from link & Get URI of .mp3 file stored in res/raw folder in android
sing the resource id, the format is:
"android.resource://[package]/[res id]"
Uri path = Uri.parse("android.resource://com.androidbook.samplevideo/" + R.raw.myvideo);
or, using the resource subdirectory (type) and resource name (filename without extension), the format is:
"android.resource://[package]/[res type]/[res name]"
Uri path = Uri.parse("android.resource://com.androidbook.samplevideo/raw/myvideo");
If you do not know the ID of your resource, but just the name, you can use the getIdentifier(...) method of the Android Resouces object. You can retrieve the latter using the getResources() of your application context.
If, for example, your resource is stored in the /res/raw folder:
String rawFileName = "example" // your file name (e.g. "example.pdf") without the extension
//Retrieve the resource ID:
int resID = context.getResources().getIdentifier(rawFileName, "raw", context.getPackageName());
if ( resID == 0 ) { // the resource file does NOT exist!!
//Debug:
Log.d(TAG, rawFileName + " DOES NOT EXISTS! :(\n");
return;
}
//Read the resource:
InputStream inputStream = context.getResources().openRawResource(resID);
Very Helpful post.
Here's an alternative: Work with a FileDescriptor instead of the Uri, where possible.
Example: (In my case its a raw audio file)
FileDescriptor audioFileDescriptor = this.resources.openRawResourceFd(R.raw.example_audio_file).getFileDescriptor();
this.musicPlayer.setDataSource(backgroundMusicFileDescriptor);

Categories

Resources