Android : use of mediaStore with pdf file - android

I try to use media store to store a pdf download (in Environment.DIRECTORY_DOWNLOADS) from a private network and to show it. I want the user to be able to choose the application to show it.
In my code, I have difficulty to define the file path "dataFile"
Can you give advice, thanks
Laurent
String fileType="application/pdf";
String filetxt="Choose pdf Application";
final Intent intent = new Intent(Intent.ACTION_VIEW)
.setDataAndType(dataFile, fileType);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Intent intentChooser = Intent.createChooser(intent,filetxt);
context.startActivity(intentChooser);

dataFile should be URI, which can be easily created from File (or its path)
File file = new File(pathToFile);
Uri dataFile = Uri.parse(file.toString()); // or strightly pass pathToFile here

My solution after several tests :
String[] projections = new String[]{
MediaStore.DownloadColumns._ID,
};
String selection =MediaStore.Files.FileColumns.DISPLAY_NAME+"=?";
String[] selectionArgs = new String[]{newLocalpath};
Cursor cursor = context.getContentResolver().query(
MediaStore.Downloads.EXTERNAL_CONTENT_URI,
projections,
selection,
selectionArgs,
null
);
Uri uri=null;
int docIndex = cursor.getColumnIndexOrThrow(MediaStore.DownloadColumns._ID);
if (cursor.moveToNext()==true) {
uri = ContentUris.withAppendedId(MediaStore.Downloads.EXTERNAL_CONTENT_URI, cursor.getInt(docIndex));
}
if (uri!=null) {
try {
String fileType="application/pdf";
String filetxt="Choose pdf Application";
final Intent intent = new Intent(Intent.ACTION_VIEW)
.setDataAndType(uri, fileType);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Intent intentChooser = Intent.createChooser(intent,filetxt);
intentChooser.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intentChooser);
} catch (Exception e) {
Log.d("application", "error starting download file: " + e.toString());
}

Related

How to use from my app another app to visualize an image?

I want to program an app. In this app, the user selects an image file path and the app opens another app (Google Photos) to show that image. This image is in the public folder Downloads.
I am using Android 9.0.
What I tried:
File imageFile = new File("/storage/emulated/0/DCIM/Camera/IMG_20220203_114716.jpg");
Uri uri = Uri.fromFile(imageFile);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "image/*");
startActivity(intent);
And in AndroidManifest:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
I get a FileUriExposedException.
SOLVED:
Uri collection = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL);
String[] projection = new String[]{MediaStore.Files.FileColumns._ID};
String selection = MediaStore.Files.FileColumns.DATA + "=?";
String[] selectionArgs = new String[]{"/storage/emulated/0/DCIM/Camera/IMG_20220203_114716.jpg"};
String sortOrder = null;
Cursor cursor = getApplicationContext().getContentResolver().query(collection, projection, selection, selectionArgs, sortOrder);
cursor.moveToFirst();
Uri uri = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL, cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns._ID)));
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setPackage("com.google.android.apps.photos");
intent.setDataAndType(uri, "image/*");
startActivity(intent);

Open folder in Android/Xamarin.Android programatically

I want to open folder programatically. I used the below code but no luck
Intent intent = new Intent(Intent.ActionView);
var uri=Uri.Parse("/storage/emulated/0/myFolder");
intent.SetDataAndType(uri, "*/*");
intent.SetFlags(ActivityFlags.NewTask);
// activity.StartActivity(Intent.CreateChooser(intent, "choose folder"));
activity.StartActivity(intent);
It shows various apps like Phone, Messaging, ES File Explorer, contacts etc. I want to open the default file explorer to open that folder.
Hi #Amit if want to open the default file explorer, you can do that in Native Android:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");//set type , here is setted to every type.
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent,1);
Other types :
intent.setType("image/*"); //set type be image
intent.setType("audio/*"); //set type be audio
intent.setType("video/*"); //set type be video (mp4 3gp be suported in android)
intent.setType("video/*;image/*");//set type be all video and image
And when back to app ,can deal with file in here:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
//no choose no continue to here
Uri uri = data.getData();
//get file's url , so last can get file
String[] proj = {MediaStore.Images.Media.DATA};
Cursor actualimagecursor = managedQuery(uri, proj, null, null, null);
int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
actualimagecursor.moveToFirst();
String img_path = actualimagecursor.getString(actual_image_column_index);
File file = new File(img_path);
Toast.makeText(MainActivity.this, file.toString(), Toast.LENGTH_SHORT).show();
}
}
Also in this way can open the specified file, need to use method setDataAndType like follow:
intent.setDataAndType(Uri.fromFile(dir.getParentFile()), "file/*.txt");
the dir is the File folder where file in this,like follow:
String compName = AppString.getCompanyName();
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + compName + "/OSC_DATA/";
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
If just want to scan file use other file explorer application , also can use intent to open other Application.However you should now the package name of it:
public void doStartApplicationWithPackageName(String packagename) {
PackageInfo packageinfo = null;
try {
packageinfo = mContext.getPackageManager().getPackageInfo(packagename, 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
if (packageinfo == null) {
return;
}
Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
resolveIntent.setPackage(packageinfo.packageName);
List<ResolveInfo> resolveinfoList = mContext.getPackageManager()
.queryIntentActivities(resolveIntent, 0);
ResolveInfo resolveinfo = resolveinfoList.iterator().next();
if (resolveinfo != null) {
String packageName = resolveinfo.activityInfo.packageName;
String className = resolveinfo.activityInfo.name;
// LAUNCHER Intent
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
ComponentName cn = new ComponentName(packageName, className);
intent.setComponent(cn);
mContext.startActivity(intent);
}
}
using like this:
doStartApplicationWithPackageName("com.android.documentsui")
This package name might be different in different android system.When you use this way need to be sure the correct package name in current system.

Share Video From Android App

Ours is a video hosting portal where users can upload and earn from their videos based on the views they get. We have recently launched an Android App and trying to integrate Share button to each video. Here is the code what we have placed
Intent intent = new Intent();
try {
URL url = new URL("https://www.clipsnow.com/videos/images/thumbnails/230/10493.jpg");
Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_SEND);
intent.setData(Uri.parse("https://www.clipsnow.com"));
intent.putExtra(Intent.EXTRA_TEXT,msg);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_STREAM, getImageUri(v.getContext(), image));
intent.setType("image/*");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
v.getContext().startActivity(Intent.createChooser(intent, "Share Video"));
} catch (Exception e) {
e.printStackTrace();
}
When we share any video with this, only thumbnail image is getting shared along with the video title. But, we need the video URL will get shared and when user tap on the URL, user will be taken to our app.
How can we do that?
This worked with me. Give a try!
File videoFile = new File(filePath);
Uri videoURI = Build.VERSION.SDK_INT >= Build.VERSION_CODES.N
? FileProvider.getUriForFile(mContext, mContext.getPackageName(), videoFile)
: Uri.fromFile(videoFile);
ShareCompat.IntentBuilder.from(getActivity())
.setStream(videoURI)
.setType("video/mp4")
.setChooserTitle("Share video...")
.startChooser();
You should download video first. Then you can share with using ACTION_SEND.
String path = ""; //should be local path of downloaded video
ContentValues content = new ContentValues(4);
content.put(MediaStore.Video.VideoColumns.DATE_ADDED,
System.currentTimeMillis() / 1000);
content.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4");
content.put(MediaStore.Video.Media.DATA, path);
ContentResolver resolver = getApplicationContext().getContentResolver();
Uri uri = resolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, content);
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("video/*");
sharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Hey this is the video subject");
sharingIntent.putExtra(Intent.EXTRA_TEXT, "Hey this is the video text");
sharingIntent.putExtra(Intent.EXTRA_STREAM,uri);
startActivity(Intent.createChooser(sharingIntent,"Share Video");
I guess, all the other solutions are obsolete. Here is the working solution for sharing the video to any platform (Youtube, Gmail, Hangout, Whatsapp etc),
startActivity(
Intent.createChooser(
Intent().setAction(Intent.ACTION_SEND)
.setType("video/*")
.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
.putExtra(
Intent.EXTRA_STREAM,
getVideoContentUri(this, File(currentVideo.videoPath))
), resources.getString(R.string.share_video)
)
)
Below is the getVideoContentUri method,
/**
* Return the URI for a file. This URI is used for
* sharing of video.
* NOTE: You cannot share a file by file path.
*
* #param context Context
* #param videoFile File
* #return Uri?
*/
fun getVideoContentUri(context: Context, videoFile: File): Uri? {
var uri: Uri? = null
val filePath = videoFile.absolutePath
val cursor = context.contentResolver.query(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
arrayOf(MediaStore.Video.Media._ID),
MediaStore.Video.Media.DATA + "=? ",
arrayOf(filePath), null)
if (cursor != null && cursor.moveToFirst()) {
val id = cursor.getInt(cursor
.getColumnIndex(MediaStore.MediaColumns._ID))
val baseUri = Uri.parse("content://media/external/video/media")
uri = Uri.withAppendedPath(baseUri, "" + id)
} else if (videoFile.exists()) {
val values = ContentValues()
values.put(MediaStore.Video.Media.DATA, filePath)
uri = context.contentResolver.insert(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values)
}
closeCursor(cursor)
return uri
}
To send the video in android 10 and above use this. I used this to send the video from local storage to WhatsApp.
public void shareVideo(String filepath)
{
Intent shareintent=new Intent("android.intent.action.SEND");
shareintent.setType("video/mp4");
shareintent.putExtra("android.intent.extra.STREAM",
Uri.parse(filepath));
startActivity(Intent.createChooser(shareintent,"share"));
}

Share video to viber via intents in android not working

I googled a lot but no success.
I want to share a video file in my App via this code:
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("video/mp4"); //or even video mpeg not working!
intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + outputFileInformation.getFullPath()));
startActivity(Intent.createChooser(intent, getString(R.string.share)));
And I tried some other codes, But for in sharing list if I choose Viber, After selecting recipient nothing happens, Screen flashes and nothing happens.
(I must say sharing image/png has no issue.
I really need to get this work soon.
I could easily share that video from gallery without any issue but now working in my app... .
I manged to make it work.
I must make an Uri in another way, here is the code i used for making Uri from a video file path (you could change it for Images as well)
public static Uri getVideoContentUri(Context context, File imageFile) {
String filePath = imageFile.getAbsolutePath();
Cursor cursor = context.getContentResolver().query(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Video.Media._ID },
MediaStore.Video.Media.DATA + "=? ",
new String[] { filePath }, null);
if (cursor != null && cursor.moveToFirst()) {
int id = cursor.getInt(cursor
.getColumnIndex(MediaStore.MediaColumns._ID));
Uri baseUri = Uri.parse("content://media/external/video/media");
return Uri.withAppendedPath(baseUri, "" + id);
} else {
if (imageFile.exists()) {
ContentValues values = new ContentValues();
values.put(MediaStore.Video.Media.DATA, filePath);
return context.getContentResolver().insert(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
} else {
return null;
}
}
}

How to open an excel file in android

I have downloaded the excel file to sdcard. want to open the file in my app and process it.
Is there any way or any intent to open an excel file in android. I
Use the below mentioned code and try:
File file = new File(Environment.getExternalStorageDirectory()+ "/filepath/" + filename);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),"application/vnd.ms-excel");
startActivity(intent);
Use this piece of code which can be used to open arbitrary file (not only Excel).
General idea is to get based on file mime type which Intent can handle it and then start those Intent. For sure it may happen that system doesn't have any intents to handle it or may have several Intents. Anyway here's general direction:
Get mime type for given filename
public String getMimeType(String filename)
{
String extension = FileUtils.getExtension(filename);
// Let's check the official map first. Webkit has a nice extension-to-MIME map.
// Be sure to remove the first character from the extension, which is the "." character.
if (extension.length() > 0)
{
String webkitMimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.substring(1));
if (webkitMimeType != null)
return webkitMimeType;
}
return "*/*";
}
Then get default intent which will handle given mime type
public Intent getDefaultViewIntent(Uri uri)
{
PackageManager pm = this.getPackageManager();
Intent intent = new Intent(Intent.ACTION_VIEW);
// Let's probe the intent exactly in the same way as the VIEW action
String name=(new File(uri.getPath())).getName();
intent.setDataAndType(uri, this.getMimeType(name));
final List<ResolveInfo> lri = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
if(lri.size() > 0)
return intent;
return null;
}
And as final step just start Intent returned by getDefaultViewIntent()
Try this:
public void ouvrir(View view) {
String csvFile = "myData.xls";
File yourDir = new File(Environment.getExternalStorageDirectory()+ "/CHETEHOUNA/" + csvFile);
String davUrl = "ms-excel:ofv|u|" + yourDir.toString();
Uri uri = Uri.parse(davUrl);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
Uri path = Uri.fromFile(file);
Intent excelIntent = new Intent(Intent.ACTION_VIEW);
excelIntent.setDataAndType(path , "application/vnd.ms-excel");
excelIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(excelIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(EmptyBlindDocumentShow.this,"No Application available to viewExcel", Toast.LENGTH_SHORT).show();
}
Can you elaborate?
If you want to read excel file from SD card using File, here is the code
File root = Environment.getExternalStorageDirectory();
File excelFile = new File(root, "filename.xlsx");

Categories

Resources