我正在做一个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();
}
}
}
}
3条答案
按热度按时间r6vfmomb1#
您为获得的uri打开一个InputStream,然后像使用FileInputStream一样从流中读取。
yyyllmsg2#
我想这会对你有帮助:
String text = readText(uri);
如果你有任何问题请告诉我。
4dbbbstv3#
我遇到的问题是类无法识别getContentResolver(),但后来我意识到我是在片段中,因此您需要首先传递上下文: