简体   繁体   中英

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.txt

i want that when users select any one of the file,the selected file should be read. i know the code to read a single file ie

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 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();

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);
}


} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM