从OnActivityResult获取内容

时间:2018-01-10 11:29:49

标签: android android-intent

我正在做一个texttospeech项目来导入txt文件并使用存储访问框架读取其内容。在OnActivityResult之后如何将内容转换为字符串变量并将其传递给下一个活动。我需要将txt文件内容复制到下一个活动edittext

package com.texttospeech.texttospeech;


import android.app.Activity;

import android.content.Intent;

import android.net.Uri;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.texttospeech.Main2Activity;

public class MainActivity extends AppCompatActivity {

private static final int READ_REQUEST_CODE = 42;
private Button button;

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

    button = (Button) findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            performFileSearch();
        }
    });
}

private static final int EDIT_REQUEST_CODE = 42;
/**
 * Fires an intent to spin up the "file chooser" UI and select an image.
 */
private void performFileSearch() {
    // ACTION_OPEN_DOCUMENT is the intent to choose a file via the system's
    // file browser.
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);

    // Filter to only show results that can be "opened", such as a
    // file (as opposed to a list of contacts or timezones).
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    // Filter to show only text files.
    intent.setType("text/plain");

    startActivityForResult(intent, EDIT_REQUEST_CODE);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent resultData){
    if(requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK){
        Uri uri = null;
        if (resultData!= null){
            uri = resultData.getData();


        }
    }
}
}

2 个答案:

答案 0 :(得分:0)

我想这会对你有所帮助:

String text = readText(uri);

private String readText(Uri uri) {
    File f = new File(uri.toString());
    FileInputStream inputStream = null;
    try {
        inputStream = new FileInputStream(f);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    int i;
    try {
        i = inputStream.read();
        while (i != -1) {
            byteArrayOutputStream.write(i);
            i = inputStream.read();
        }
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    return byteArrayOutputStream.toString();
}

如果您有任何疑问,请与我联系。

答案 1 :(得分:0)

为打开的uri打开一个InputStream,然后像使用FileInputStream一样从流中读取。

<form action="#" id="formParking" enctype="multipart/form-data">