android - How to Choose a file from files in SDCard? -
i have text files on android's sd card, , need access 1 of them. came across below code here:
//find directory sd card using api //*don't* hardcode "/sdcard" file sdcard = environment.getexternalstoragedirectory(); //get text file file file = new file(sdcard,"file.txt"); //read text 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 add proper error handling here } //find view id textview tv = (textview)findviewbyid(r.id.text_view); //set text tv.settext(text);
but in part of code:
//get text file file file = new file(sdcard,"file.txt");
the name of text file specified need user choose text file wants (from text files in sd card). how can let user brows sd card , choose file wants?
you need file chooser/browser created here. there lots of libraries available using can achieve required functionality. here 1 -
https://code.google.com/p/android-file-chooser/
also, necessary code required on first page. invoke file chooser, need write these lines of code -
intent intent = new intent(this, filechooser.class); arraylist<string> extensions = new arraylist<string>(); extensions.add(".txt"); //can used multiple filters intent.putstringarraylistextra("filterfileextension", extensions); startactivityforresult(intent, file_chooser);
and, callback path of selected file
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(); } }
Comments
Post a Comment