简体   繁体   English

选择一个文本文件,然后在 Android 平台上阅读它

[英]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.我的 android 应用程序有一个 Button 小部件,其中除了其他必要的文本之外,我还在文件activity_main.xml编写了以下内容。

<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:在文件MainActivity.java除了其他函数之外,我写了以下内容:

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?这个FILE_REQUEST_CODE是如何定义的? What are the permissible values?允许的值是多少?

Could you help me?你能帮我吗?

You need to startActivityForResult not startActivity, as in the example you were using.您需要 startActivityForResult 而不是 startActivity,就像您使用的示例一样。
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);
    } 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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