2

I have some text files on my android's SD Card, and i need to access one of them. I came across the below code here:

  //Find the directory for the SD Card using the API
//*Don't* hardcode "/sdcard"
File sdcard = Environment.getExternalStorageDirectory();

//Get the text file
File file = new File(sdcard,"file.txt");

//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');
    }
}
catch (IOException e) {
    //You'll need to add proper error handling here
}

//Find the view by its id
TextView tv = (TextView)findViewById(R.id.text_view);

//Set the text
tv.setText(text);

But in this part of the code:

//Get the text file

File file = new File(sdcard,"file.txt");

the name of the text file is specified but i need the user to choose the text file he wants (from those text files in SD Card). So how can i let the user brows the SD Card and choose the file he wants?

Community
  • 1
  • 1
gandalf
  • 53
  • 2
  • 5
  • https://stackoverflow.com/a/59104787/3141844 + https://github.com/criss721/Android-FileSelector – Criss Nov 29 '19 at 13:51

1 Answers1

4

You need a file chooser/browser to be created here. There are lots of libraries available using which you can achieve the required functionality. Here is one -

https://code.google.com/p/android-file-chooser/

Also, necessary code is required on first page. Like to invoke the file chooser, you will need to write these lines of code -

Intent intent = new Intent(this, FileChooser.class);
ArrayList<String> extensions = new ArrayList<String>();
extensions.add(".txt"); //can be used for multiple filters
intent.putStringArrayListExtra("filterFileExtension", extensions);
startActivityForResult(intent, FILE_CHOOSER);

And, for callback to get path of Selected File by User -

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
   if ((requestCode == FILE_CHOOSER) && (resultCode == -1)) {
      String fileSelected = data.getStringExtra("fileSelected");
      Toast.makeText(this, fileSelected, Toast.LENGTH_SHORT).show();
   }                   
}
Kanak Sony
  • 1,570
  • 1
  • 21
  • 37
  • thanks for your help. i have two questions :1.I know that the "FILE_CHOOSER" is a constant but what is the value of the constant? 2. I am using the filechooser as a library should i declare FileChooser as an activity in my android? – gandalf Apr 24 '14 at 05:31
  • You can assign any value to it :). Yes you can do but lib will be good if you don't need to change anything in code. – Kanak Sony Apr 24 '14 at 05:44