简体   繁体   中英

Choose a text file and then read it on Android Platform

My android app has a Button widget, wherein I have written the following inside the file activity_main.xml , apart from other necessary text.

<Button
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Numbers"
   android:id="@+id/btnBrowse"
   android:onClick="clickButtonBrowse"
 />

In the file MainActivity.java apart from the other functions, I wrote the following:

protected void clickButtonBrowse() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType("text/plain");
    startActivity(intent, FILE_REQUEST_CODE);
}

My idea is to open a file browser, and select a file. I have taken the help from this question on selecting a file .

Now I have no idea on the following:

  1. How to get the name of the file from the intent, so that I can read it.
  2. How is this FILE_REQUEST_CODE to be defined? What are the permissible values?

Could you help me?

You need to startActivityForResult not startActivity, as in the example you were using.
Then you can:

public synchronized void onActivityResult(final int requestCode,
        int resultCode, final Intent data) {

    if (resultCode == Activity.RESULT_OK) {
        String filePath = data.getStringExtra(FileDialog.RESULT_PATH);
    } 
}

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