Reading a text file dynamically on user selection in Android
I am building an android application that reads text files. Now,i have multiple text files in the sdcard . Location of files is /sdcard/textfile/
filenames: abc.txt def.txt ghi.txti want that when users select any on开发者_JAVA百科e of the file,the selected file should be read. i know the code to read a single file i.e
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,pathtofile);
BufferedReader br = new BufferedReader(new FileReader(file));
pathtofile stores the path to file abc.txt that is defined .
Is there any way i can pass the filepath to file object for the file that user selected currently,it works for abc.txt as i have defined its path in pathtofile
You can also make a list of all the items in your textfile folder and save it in a list where the user can choose from.
public class DirectoryBrowser extends ListActivity {
private List<String> items = null;
private File currentDirectory;
private ArrayAdapter<String> fileList;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
currentDirectory = new File("/sdcard/textfile");
getFiles(currentDirectory.listFiles());
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id){
int selectedRow = (int)id;
currentDirectory = new File(items.get(selectedRow));
if(currentDirectory.isDirectory()){
getFiles(currentDirectory.listFiles());
}else{
//if the selected file is not a directory. get the filename
currentDirectory.getPath();
}
}
private void getFiles(File[] files){
items = new ArrayList<String>();
for(File file : files){
items.add(file.getPath());
}
fileList = new ArrayAdapter<String>(this,R.layout.list_text, items);
setListAdapter(fileList);
}
}
You can use a AlertDialog with a list.
final CharSequence[] items = {"abc.txt", "def.txt", "ghi.txt"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick a file");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
//Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,items[item]);
BufferedReader br = new BufferedReader(new FileReader(file));
}
});
AlertDialog alert = builder.create();
精彩评论