I chose a text file from storage and got its path (FilePath), am trying to read the content of that text file and put it in edittext..i am using the code below to get text file data and put it in edittext (eTPronounce)
File sdcard = Environment.getExternalStorageDirectory();
//Get the text filea
File file = new File(sdcard,FilePath);
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
//Find the view by its i
//Set the text
eTPronounce.setText(text);
}
});
If i replace FilePath (in the second line) with any directory where there is text file it works.For example if I replace FilePath with "Download/text.txt" it works .
I used this link to get FilePath
THANKS
I think you should be using below constructor
File(File dir, String name)
or you can use
File(String path)
If you are specifying directory name then you only need to give the file name as shown in the first example.Otherwise you can use the second one with the complete file path
if(resultCode==RESULT_OK){
if(data == null || data.getData == null){
//Log.e()
return;
}
FilePath = getPath(data.getData(),mActivity);
setfilename.setText(FilePath);
}
public static String getPath(Uri uri,Context ctx) {
String res = null;
if(null==uri){
return res;
}
if (uri != null && uri.toString().startsWith("file://")) {
return uri.toString().substring("file://".length());
}
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = ctx.getContentResolver().query(uri, proj, null, null, null);
if(cursor!=null){
if(cursor.moveToFirst()){
try {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}catch (Exception ignored){
}finally {
closeCursor(cursor);
}
}
}
closeCursor(cursor);
return res;
}
Related
In my app the user can select a xml file via an Intent:
Selecting:
Intent chooseFileXML = new Intent(Intent.ACTION_GET_CONTENT);
chooseFileXML.setType("text/xml");
Intent intentXML = Intent.createChooser(chooseFileXML, getString(R.string.importXMLDatei));
startActivityForResult(intentXML, REQUEST_CODE_IMPORT_XML_FILE);
Receiving:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
switch (requestCode){
case REQUEST_CODE_IMPORT_XML_FILE:
if(resultCode == RESULT_OK){
Uri uri = data.getData();
String filePath = uri.getPath();
File fl = new File(filePath);
//Get xml-code from file and put it in a String
FileInputStream fin = null;
try {
fin = new FileInputStream(fl);
BufferedReader reader = new BufferedReader(new InputStreamReader(fin));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
reader.close();
System.out.println(sb.toString());
fin.close();
} catch (Exception e) {
e.printStackTrace();
}
}
break;
}
}
I receive the correct filepath. But in this line: fin = new FileInputStream(fl); I get this error:
java.io.FileNotFoundException: /document/primary:Android/data/com.oli.myapp/Files/test.xml: open failed: ENOENT (No such file or directory)
Actually problem in file path .your file path is not vaild so find real path of file
String filePath = getRealPathFromURI(uri);
getRealPathFromURI methods
private String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(mContext, contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}
What I am trying to achieve. I have a button, when the button is clicked the app opens a file picker and the user selects a file. The app then uses a FileInputStream to read the file and generates a byte[]. I have a TextView below the button which will then simply display the byte[].length. Here is the code in the button.onClick() event:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
requestFilePickerCode = parent.registerActivityResultListener(this);
try
{
parent.startActivityForResult(intent, requestFilePickerCode);
}
catch (ActivityNotFoundException e)
{
Toast.makeText(task.getParent(), "Please install a file manager", Toast.LENGTH_SHORT).show();
}
Now this code works and I have confirmed that it fires onActivityResult when the file is chosen. I simply print a Log to display data.toString() which produces the following output:
11-02 15:14:36.196 2535-2535/? V/class za.co.gpsts.gpsjobcard.utility.handlers.PebbleTypeHandlerBinary: -----> content:/com.android.providers.downloads.documents/document/1
So it seems to be getting the selected file. When I run the app and I select a file it throws my custom error:
11-02 15:14:36.196 2535-2535/? E/class za.co.gpsts.gpsjobcard.utility.handlers.PebbleTypeHandlerBinary: -----> File does not exist
This obviously indicates that I am not getting the file. Here is my code:
#Override
public boolean onActivityResult(int requestCode, int resultCode, Intent data)
{
byte[] fileContent;
// check that data is not null and assign to file if not null
if (data != null)
{
Uri uri = data.getData();
String uriString = uri.toString();
file = new File(uriString);
Log.v(PebbleTypeHandlerBinary.class.toString(), "-----> " + file.toString());
// declare file input stream and read bytes
// write to string variable to test and test output
FileInputStream fin = null;
try
{
fin = new FileInputStream(file);
fileContent = new byte[(int) file.length()];
fin.read(fileContent);
String test = new String(fileContent);
Log.v(PebbleTypeHandlerBinary.class.toString(), "=====> " + test);
}
catch (FileNotFoundException e)
{
Toast.makeText(task.getParent(), "File not found", Toast.LENGTH_SHORT).show();
Log.e(PebbleTypeHandlerBinary.class.toString(), "-----> File does not exist");
}
catch (IOException e)
{
Toast.makeText(task.getParent(), "Error reading file", Toast.LENGTH_SHORT).show();
Log.e(PebbleTypeHandlerBinary.class.toString(), "-----> Error while reading the file");
}
finally
{
// close the file input stream to stop mem leaks
try
{
if (fin != null)
{
fin.close();
}
} catch (IOException e)
{
Log.e(PebbleTypeHandlerBinary.class.toString(), "-----> Error closing the stream");
}
}
Log.v(PebbleTypeHandlerBinary.class.toString(), data.toString());
}
return false;
}
Please can you guys review my code and help me to get this working. Any help would be appreciated.
/* you can get just name and size with this method.
use Cursor .
Uri uri = data.getData();
get data from onActivityResult()
*/;
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
cursor.moveToFirst();
String name = cursor.getString(nameIndex);
String size = Long.toString(cursor.getLong(sizeIndex));
Toast.makeText(this, "name : "+name+"\nsize : "+size, Toast.LENGTH_SHORT).show();
I managed to fix it as follows:
I used inputStream = task.getParent().getContentResolver().openInputStream(uri); to get an InputStream. Then used a ByteArrayOutputStream to write to a byte[]. See code below.
#Override
public boolean onActivityResult(int requestCode, int resultCode, Intent data)
{
Uri uri = data.getData();
byte[] fileContent;
InputStream inputStream = null;
try
{
inputStream = task.getParent().getContentResolver().openInputStream(uri);
if (inputStream != null)
{
fileContent = new byte[(int)file.length()];
inputStream.read(fileContent);
fileContent = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int read;
while((read=inputStream.read(fileContent))>-1) baos.write(fileContent,0,read);
fileContent = baos.toByteArray();
baos.close();
Log.v(PebbleTypeHandlerBinary.class.toString(), "-----> Input Stream: " + inputStream);
Log.v(PebbleTypeHandlerBinary.class.toString(), "-----> Byte Array: " + fileContent.length);
}
else
{
Log.e(PebbleTypeHandlerBinary.class.toString(), "-----> Input Stream is null");
}
}
catch (FileNotFoundException e)
{
Log.e(PebbleTypeHandlerBinary.class.toString(), "-----> File not found", e);
}
catch (IOException e)
{
Log.e(PebbleTypeHandlerBinary.class.toString(), "-----> Error reading file", e);
}
finally
{
if (inputStream != null)
{
try
{
inputStream.close();
}
catch (IOException e)
{
Log.e(PebbleTypeHandlerBinary.class.toString(), "-----> Error reading file", e);
}
}
}
return false;
}
Thanks for all your help.
U can search converting uri to filepath.
GetData() retruns a uri.
But new File() need a filepath param;
Like this:
public static String getRealFilePath( final Context context, final Uri uri ) {
if ( null == uri ) return null;
final String scheme = uri.getScheme();
String data = null;
if ( scheme == null )
data = uri.getPath();
else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) {
data = uri.getPath();
} else if
( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) {
Cursor cursor = context.getContentResolver().query( uri, new String[] { ImageColumns.DATA }, null, null, null );
if ( null != cursor ) {
if ( cursor.moveToFirst() ) {
int index = cursor.getColumnIndex( ImageColumns.DATA );
if ( index > -1 ) {
data = cursor.getString( index );
}
}
cursor.close();
}
}
return data;
}
1. File Name:
You can get the file name with the following method:
public static String getFileName(Context context, Uri uri) {
String result = null;
if (uri.getScheme().equals("content")) {
Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
try {
if (cursor != null && cursor.moveToFirst()) {
result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} finally {
cursor.close();
}
}
if (result == null) {
result = uri.getPath();
int cut = result.lastIndexOf('/');
if (cut != -1) {
result = result.substring(cut + 1);
}
}
return result;
}
You will call it inside onActivityResult() and pass to it the context and uri. and you can find the uri through the intent you get from the onActivityResult which is mostly called "data", you will get the Uri from it like this:
data.data
which ".data" is the Uri.
Ex:
Utils.getFileName(this, data!!.data)
And finally it will return the file name as a String.
2. File Path:
Simply to get the file path you can get it from the data intent uri like this:
data!!.data!!.path.toString()
It will get you the path of the file as a String.
I use basic4android and I want to know the size of selected image from gallery.
my code is :
Dim PicChooser As ContentChooser
PicChooser.Initialize("PicChooser")
PicChooser.Show("image/*", "Select a pic")
Sub PicChooser_Result(Success As Boolean, Dir As String, FileName As String)
If Success = True Then
Dim inp As InputStream
inp = File.OpenInput(Dir, FileName)
Dim btm As Bitmap
btm.Initialize2(inp)
end if
end Sub
I use below method in b4a but it doesn't work.
File.Size(Dir,FileName)
it returns zero because Dir and Filename in this sub doesn't really shows the path of the file.
Somewhere i found this maybe untested code:
public static String getContentSizeFromUri(Context context, Uri uri) {
String contentSize = null;
String[] proj = {MediaStore.Images.Media.SIZE };
CursorLoader cursorLoader = new CursorLoader(
context,
uri, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
if(cursor != null)
{
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.SIZE);
if (cursor.moveToFirst() )
contentSize = cursor.getString(column_index);
}
return contentSize;
}
Check if return value is null before use.
If you already get the Uri of the file, you can use the following code to get some information
if (uri != null) {
File file = new File(uri.getPath());
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("FileName", file.getName());
jsonObject.put("FilePath", file.getAbsolutePath());
jsonObject.put("FileSize", file.length());
} catch (JSONException e) {
e.printStackTrace();
}
}
Hi I am trying to read an email attachment from my app.
When I click on the email attachment it opens my app and in that I am trying to read the content of the file using the following code
Intent CallingIntent = getIntent();
Uri data = CallingIntent.getData();
final String scheme = data.getScheme();
if(ContentResolver.SCHEME_CONTENT.equals(scheme))
{
ContentResolver cr = getApplicationContext().getContentResolver();
InputStream is;
try
{
is = cr.openInputStream(data);
if(is == null)
{
return;
}
StringBuffer buf = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String str;
if (is!=null)
{
while ((str = reader.readLine()) != null)
{
buf.append(str);
}
}
is.close();
Toast.makeText(getApplicationContext(), buf, Toast.LENGTH_SHORT).show();
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
and when try to open the file using the statement is = cr.openInputStream(data); it gives me an exceptioniFileNotFoundException
Can any suggest how can I accomplish this such in my app I am able to read the content of the attachment without downloading it.
You need to extract real path of file from this URI. This function will return you the path.
// replace this
is = cr.openInputStream(data)
//with
is = cr.openInputStream(getPath(data))
public static String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = BigNoteActivity.instance.getContentResolver().query(
uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
I am getting the file path .How to get content of file. Then I need to send to javascript.
I need all data in string or stringbuilder so that I can send in javascipt.can you please tell me how to read content of file with path
------------------FilePath------------------/storage/sdcard0/Download/a.txt
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
if (requestCode == FILECHOOSER_RESULTCODE) {
if (mUploadMessage == null)
return;
Uri result = intent == null || resultCode != RESULT_OK ? null
: intent.getData();
if (result!=null){
String filePath = null;
if ("content".equals(result.getScheme())) {
Cursor cursor = this.getContentResolver().query(result, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
cursor.moveToFirst();
filePath = cursor.getString(0);
cursor.close();
} else {
filePath = result.getPath();
System.out.println("------------------FilePath------------------"+filePath);
// content send to java script
//String msgToSend = Msg.getText().toString();
// web.loadUrl("javascript:loadData(\""+msgToSend+"\")");
// web.loadUrl("javascript:loadData()");
filePath = result.getPath();
}
Uri myUri = Uri.parse(filePath);
mUploadMessage.onReceiveValue(myUri);
} else {
mUploadMessage.onReceiveValue(result);
}
mUploadMessage = null;
}
}
If you have the filePath you can try something like the following:
File file = new File(filePath);
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
}
catch (IOException e) {
//Exception-handling
}