Android Studio java -应用程序使用ACTION_OPEN_DOCUMENT_TREE崩溃

bttbmeg0  于 2023-11-15  发布在  Android
关注(0)|答案(1)|浏览(107)

注: 我已重新提交,相同的问题,但为了简化,上下文略有不同 [11.9.2021]

一个文本文件存储在手机的sheet music目录中。该应用程序是将此.txt文件打开到EditText字段中。这是一个概念证明,这是可以实现的。
我已经采取了代码示例here,并尝试修改它,以便它将在EditText字段@+id/editText中打开文件anticipation_lyrics.txt
一旦点击“使用此文件夹”,然后“允许”的应用程序崩溃。
这就是逻辑:
1.用户单击按钮启动目录选取器
1.这段代码打开一个文档树选择器,
1.然后用户可以选择一个目录
1.该应用程序将打开文件anticipation_lyrics.txt(已存储在该目录中)
1.代码检查文件是否存在
1.该代码将其内容读入字符串生成器,并将编辑文本字段editText的文本设置为文件的内容
我相信应用程序在这里崩溃:

try (InputStream inputStream = getContentResolver().openInputStream(fileUri)

字符串
但是不会产生错误。
Manifest有:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />


下面是完整的java代码:

package com.enetapplications.displayfilecontent;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class DisplayFileContentActivity extends Activity {

    private static final int RQS_OPEN_DOCUMENT_TREE = 2;

    TextView textInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textInfo = (TextView)findViewById(R.id.info);
        Button btnOpen = (Button)findViewById(R.id.opendocument);
        btnOpen.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
                startActivityForResult(intent, RQS_OPEN_DOCUMENT_TREE);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // Check if the result is OK and if the request code matches the constant for opening a document tree
        if (resultCode == RESULT_OK && requestCode == RQS_OPEN_DOCUMENT_TREE) {
            Uri uriTree = data.getData(); // Retrieve the URI representing the selected directory

            // Get the EditText field.
            EditText editText = (EditText) findViewById(R.id.editText);

            // Get the URI of the file "anticipation_lyrics.txt" within the chosen directory.
            Uri fileUri = Uri.withAppendedPath(uriTree, "anticipation_lyrics.txt");

            // Open the file for reading and set its content in the EditText field
            try (InputStream inputStream = getContentResolver().openInputStream(fileUri)) {
                // Read the contents of the file into a string builder.
                StringBuilder stringBuilder = new StringBuilder();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                String line;
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line).append("\n");
                }

                // Set the text of the EditText field to the contents of the file.
                editText.setText(stringBuilder.toString());
            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(this, "Error reading the file", Toast.LENGTH_SHORT).show(); // Notify the user about an error in file reading
            }
        }
    }
}


没有来自代码或调试器的错误消息

cgyqldqp

cgyqldqp1#

使用DocumentFile是有效的。下面是将.txt文件打开到EditText字段的概念验证示例:

package com.enetapplications.displayfilecontent;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.documentfile.provider.DocumentFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class DisplayFileContentActivity extends Activity {

    private static final int RQS_OPEN_DOCUMENT_TREE = 2;
    TextView textInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.d("DisplayFileContentActivityz", "(DisplayFileContentActivity) line #28");
        textInfo = findViewById(R.id.info);
        Button btnOpen = findViewById(R.id.opendocument);
        btnOpen.setOnClickListener(v -> openDocumentTree());
    }

    private void openDocumentTree() {
        Log.d("DisplayFileContentActivityz", "(DisplayFileContentActivity) line #34");
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
        Log.d("DisplayFileContentActivityz", "(DisplayFileContentActivity) line #36");
        startActivityForResult(intent, RQS_OPEN_DOCUMENT_TREE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d("DisplayFileContentActivityz", "(DisplayFileContentActivity) line #43");
        if (resultCode == RESULT_OK && requestCode == RQS_OPEN_DOCUMENT_TREE) {
            Uri uriTree = data.getData();
            Log.d("DisplayFileContentActivityz", "(DisplayFileContentActivity) line #47");
            EditText editText = findViewById(R.id.editText);
            Log.d("DisplayFileContentActivityz", "(DisplayFileContentActivity) line #50");

            DocumentFile pickedDir = DocumentFile.fromTreeUri(this, uriTree);
            DocumentFile file = pickedDir.findFile("anticipation_lyrics.txt");

            if (file == null || !file.exists()) {
                Log.d("DisplayFileContentActivityz", "(DisplayFileContentActivity) line #58 file = " + file);
                Toast.makeText(this, "The file 'anticipation_lyrics.txt' does not exist.", Toast.LENGTH_SHORT).show();
                return;
            }

            try (InputStream inputStream = getContentResolver().openInputStream(file.getUri())) {
                Log.d("DisplayFileContentActivityz", "(DisplayFileContentActivity) line #56");
                StringBuilder stringBuilder = new StringBuilder();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                String line;
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line).append("\n");
                }
                editText.setText(stringBuilder.toString());
            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(this, "Error reading the file", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

字符串

相关问题