Open folder in Android/Xamarin.Android programatically - android

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.

Related

Android : use of mediaStore with pdf file

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());
}

How to open a folder create within application in android

I am generated a folder name "tesApplication" and create a file name "testFile.csc" in it and store some date into that file. Now I want to open folder dir using new intent.
I had try below code but did not work in my case any other way to achieve this.
Uri selectedUri = Uri.parse(fileNameString);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(selectedUri, "text/csv");
if (intent.resolveActivityInfo(getPackageManager(), 0) != null)
{
startActivity(intent);
}
else
{
// if you reach this place, it means there is no any file
// explorer app installed on your device
}
copy this in else
public void openFolder()
{
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath()
+ "/myFolder/");
intent.setDataAndType(uri, "text/csv");
startActivity(Intent.createChooser(intent, "Open folder"));
}

How to read/open PPT files in Android?

[This question may be duplicate, but i din't find what i am looking for]
[Read]How can we open files like ppt, doc, pps, rtf, etc. in Android?
I am having PPT files. In my app, i have a list view which display the PPT file list available in my private app folder. In click of particular file, i want to open corresponding PPT file for reading in my App.
The App which i am creating is just like collection of PPTs and reading them one by one.
Please provide any API/Example/Links.
You need to use other application to open your ppt files , Make sure that file location you are providing is accessible to other application. Try with following :
final Uri uri = Uri.fromFile(file);
final Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/vnd.ms-powerpoint");
PackageManager pm = getPackageManager();
List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
if(list.size() > 0)
startActivity(context, intent);
Available application will be shown to user and user can choose application which can open.
private void openPPT(final String path) {
File file = new File(path);
Uri uri ;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
uri = FileProvider.getUriForFile(context, context.getPackageName() + ".provider", file);
} else {
uri = Uri.fromFile(file);
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setDataAndType(path, "application/vnd.ms-powerpoint");
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "Application not found", Toast.LENGTH_SHORT).show();
}
}

How to set up share Intent in android.

I want to share multiple images with other application using share action provided by android. The below code does not works as intended.
Sending Activity:
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND_MULTIPLE);
//intent.putExtra(Intent.EXTRA_SUBJECT, "Here are some files.");
intent.setType("image/*");
ArrayList<Uri> files = new ArrayList<Uri>();
for (String path : imageArray) {
File file = new File(path);
Uri uri = Uri.fromFile(file);
files.add(uri);
}
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, files);
shareAction.setShareIntent(intent);
Receiving activity code:
if (Intent.ACTION_SEND_MULTIPLE.equals(intent.getAction())
&& intent.hasExtra(Intent.EXTRA_STREAM)) {
ArrayList<Parcelable> list =
intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
for (Parcelable p : list) {
Uri uri = (Uri) p;
System.out.println("hello world");
}
}
Receiving activity output :
file:///absolute-path-to-file
I want output in content://absolute-path-to-file format. Because i am getting this format when receiving file intent from other applications.
Other possible way to solve this is also recommended.

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