Open text file using ACTION_OPEN_DOCUMENT - android

I'm trying to set an 'EditText' to the contents of a simple txt file. After looking at the developer page I stumbled across some code that gets a photo. I edited to what I thought would suit my needs but it doesn't work:
private void importText(){
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.setType("text/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0 && resultCode == RESULT_OK) {
String textContent = data.getDataString();
mEditText.setText(textContent);
}
}
What this does is it puts the string name of what appears to be the files location in the EditText not the contents of it. My app right now only supports API 19 so I thought I would be able to use this as a feature. Is this function possible using ACTION_OPEN_DOCUMENT or do I need to do something else?

Use following method to read data :
public static String readTextFromUri(Context context, Uri uri) throws IOException {
StringBuilder stringBuilder = new StringBuilder();
try (InputStream inputStream =
context.getContentResolver().openInputStream(uri);
BufferedReader reader = new BufferedReader(
new InputStreamReader(Objects.requireNonNull(inputStream)))) {
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
}
return stringBuilder.toString();
}
and get uri from given intent in onActivityResult method :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0 && resultCode == RESULT_OK) {
Uri uri = data.getData();
String myText = readTextFromUri(yourContext , uri);
}
}

You need to retrieve an Input Stream from the Uri as explained in the documentation. (Section "Get an Input Stream").

Related

Android storage access framework returning "raw" path

Trying to use the Storage access framework to select a file from the device (an html file that I wan't to parse) but it returns a file path that doesn't appear to be a content URI (/document/raw:/storage/emulated/0/Download/test.html) and that errors when I use it with the content resolver.
Intent to fetch file:
boolean alreadyHasReadPermissions = hasPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
if (alreadyHasReadPermissions) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("text/html");
try {
activity.startActivityForResult(intent, fileChooserResultCode);
}catch(ActivityNotFoundException e){
Toast.makeText(activity, R.string.unable_to_open_file_picker, Toast.LENGTH_LONG).show();
}
}
Code to read a file:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==fileChooserResultCode){
if(resultCode == Activity.RESULT_OK && data.getData()!=null) {
String contentUriString = data.getData().getPath();
try {
Uri contentUri = Uri.parse(contentUriString);
InputStream inputStream = getContentResolver().openInputStream(contentUri); // <<< Errors with FileNotFoundException
BufferedReader bf = new BufferedReader(new InputStreamReader(inputStream));
...
}catch (NullPointerException | IOException e){
Toast.makeText(this, R.string.unable_to_open_file, Toast.LENGTH_LONG).show();
}
}
}
}
Delete:
String contentUriString = data.getData().getPath();
and delete:
Uri contentUri = Uri.parse(contentUriString);
And change:
InputStream inputStream = getContentResolver().openInputStream(contentUri);
to:
InputStream inputStream = getContentResolver().openInputStream(data.getData());
IOW, do not call getPath() on a Uri.

How get Image Uri from Camera?

Help pls,
how i can get URI from camera Picture i check some articals and don't understand how dows it works, pls explain me or give some links on this topic here's my code:
private void createDirectory() {
directory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Meassure Preassure Pic");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == REQUEST_CODE_PHOTO && resultCode == RESULT_OK) {
if (intent != null && intent.getExtras() != null) {
Bitmap imageBitmap = (Bitmap) intent.getExtras().get("data");
ivPhoto.setImageBitmap(imageBitmap);
}
}
}
public void onClickPhoto(View view) {
Intent pictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (pictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(pictureIntent, REQUEST_CODE_PHOTO);
}
}
The onActivityResult method contains the data. Firstly you need to check if the data is null, after that you can use getdata() on returned intent to get URI. You can also get the real path of the captured image if you want to. Below is the code sample :
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_GALLERY_CODE && resultCode == Activity.RESULT_OK) {
uri = data.getData();
String filePath = getRealPathFromURIPath(uri, getActivity());
File file = new File(filePath);
Log.d(TAG, "Filename " + file.getName());
}
}

Android getPath() from Uri not working

On huawei honor 8 with android 7.0 the uri.getPath() returns something like /external/file/3344 instead of real path of the file.This code also works fine on many devices and also on android emulator with android 7.0 and uri.getPath() returns /storage/emulated/0/PCalculator/main.js but not on honor 8. I used Intent to choose a file in my program as below :
private void fileBrowse(){
Intent intent = new Intent();
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser
(intent,"Open File"),RCODE_OPENFILE);
}
And in onActivityResult I want to read the file as below :
public void onActivityResult(int requestCode,int resultCode,Intent data) {
super.onActivityResult(requestCode,resultCode,data);
switch(requestCode){
case RCODE_OPENFILE:
if(resultCode == RESULT_OK &&
data != null && data.getData() != null){
fileOpen(data.getData());
}
break;
}
}
And the fileOpen function :
private void fileOpen(Uri uri){
File mFile = new File(uri.getPath());
StringBuilder mText = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(mFile));
String line;
while ((line = br.readLine()) != null) {
mText.append(line);
mText.append('\n');
}
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
etCode.setText(mText);
tvTitle.setText(mFile.getName());
}

Android - Choose File and Get Absolute Path

I am developing an app which enables the user to select a file and do processing on it after getting the path of it, I have written a code which gets me the path like this
private void OpenFile()
{
Intent i = new Intent(Intent.ActionGetContent);
i.SetType("application/zip");
StartActivityForResult(i,0);
}
In activity for result I am extracting the path as follows:
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
if (requestCode == 0)
{
if (resultCode == Result.Ok)
{
string uri = data.DataString;
System.Uri myUri = new System.Uri(uri, System.UriKind.Absolute);
Android.Net.Uri uris = Android.Net.Uri.FromParts(data.Scheme, myUri.LocalPath, myUri.Fragment);
// string a= myUri.LocalPath;
System.IO.Stream input= ContentResolver.OpenInputStream(uris);
string uri = data.DataString;
ZipLogic.Unzip(uri);
}
}
}
And the results are in such pattern:
content://com.android.externalstorage.documents/document/xxxx-83BB%3xxx%2Fxxx.zip
But this path when I try to access from returns DirectoryNotFound Exception
I am unable to resolve how to open this path as a Stream.
Luckily, I found the answer by watching closely the Intent data.
protected override void OnActivityResult(int requestCode, Result resultCode, Intent intent)
{
base.OnActivityResult(requestCode, resultCode, intent);
if (requestCode == 0)
{
if (resultCode == Result.Ok)
{
string uri = data.DataString;
//intent variable has a Field named Data which is the complete URI for the file.
Android.Net.Uri uris = Android.Net.Uri.FromParts(intent.Data.Scheme, intent.Data.SchemeSpecificPart, intent.Data.Fragment);
System.IO.Stream input = ContentResolver.OpenInputStream(intent.Data);
//related tasks
}
}
}
Explanation:
The selected file result has a field named Data in the Intent object, that is basically the Uri Invoker which tends to be a URI object
I used it to get an input stream from ContentResolver.

Android : How to get file data from a Filechooser?

I have a filechooser that I call in a webview in order to upload a file.
The method allowing me to retrieve the file in my filechooser activity is as follows :
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Option o = adapter.getItem(position);
if (o.isFolder() || o.isParent()) {
currentDir = new File(o.getPath());
fill(currentDir);
} else {
//onFileClick(o);
fileSelected = new File(o.getPath());
Intent intent = new Intent();
intent.putExtra("fileSelected", fileSelected.getAbsolutePath());
setResult(Activity.RESULT_OK, intent);
finish();
}
}
This only allows me to get the path in the onActivityResult of my webview (which calls my filechooser to upload file).
The method onActivityResult is given by the code below.
If I use another application installed in my phone other than my filechooser I use :
Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
then the result is sent by:
this.mUploadMessage.onReceiveValue(uri);
Since then, it works normally. But with my filechooser intent.getData () equals to null.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == this.mUploadMessage) {
return;
}
if (resultCode != RESULT_OK) {
mUploadMessage.onReceiveValue(null);
var = 0;
return;
}
// Toast.makeText(getApplicationContext() , "onActivityResult()" + String.valueOf(requestCode) ,Toast.LENGTH_LONG).show();
// Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
// this.mUploadMessage = null;
String fileSelected = intent.getStringExtra("fileSelected");
Bundle result = intent.getExtras();
//result = Uri.parse(fileSelected);
//this.mUploadMessage.onReceiveValue(result);
if (resultCode == RESULT_OK) {
if (intent != null) {
// Get the URI of the selected file
final Uri uri = intent.getData();
Log.i("TOTOTOT", "Uri = " + uri.toString());
Toast.makeText(this, fileSelected + " " + uri.toString() , Toast.LENGTH_SHORT).show();
this.mUploadMessage.onReceiveValue(uri);
}
}
super.onActivityResult(requestCode, resultCode, intent);
}
}
What should I return in my two methods in order to retrieve both data and path, not only the path of the sent file ? Should it be all the bundle or do you know how to get Data while using Intent.getData()?
What is need to get data from directory selected inside onActivityResult()
You got path selected so you can read file from there which you want ..
Use this method to read file as a string
private String readURLFromPath(File filePath){
String dataString = "";
// i have kept text.txt in the sd-card
if (file.exists()) // check if file exist
{
// Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(filePath));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
} catch (IOException e){
// You'll need to add proper error handling here
}
// Set the text
dataString = text.toString();
}
return dataString ;
}
this method will return data as a string now you can send this string data on server...
the solution is to Get content uri from file path in android as mentioned Get content uri from file path

Categories

Resources