如何在OnActivityResult后获取TXT内容并传递至下一个Activity
Hey there! Let's get your TXT file content loaded into the next Activity's EditText. I'll walk you through fixing your code step by step.
First, a quick cleanup note: you've defined two constants (READ_REQUEST_CODE and EDIT_REQUEST_CODE) both set to 42. That's a recipe for confusion later, so let's use a single, clear request code instead.
Updated MainActivity Code
Here's the full MainActivity with logic to read the TXT file content and pass it to Main2Activity:
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 java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class MainActivity extends AppCompatActivity { // Single consistent request code to avoid mix-ups private static final int READ_TEXT_FILE_REQUEST = 42; private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = findViewById(R.id.button); button.setOnClickListener(view -> performFileSearch()); } /** * Opens system file chooser for selecting text files */ private void performFileSearch() { Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); intent.addCategory(Intent.CATEGORY_OPENABLE); intent.setType("text/plain"); startActivityForResult(intent, READ_TEXT_FILE_REQUEST); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent resultData) { super.onActivityResult(requestCode, resultCode, resultData); // Validate request and result if (requestCode == READ_TEXT_FILE_REQUEST && resultCode == Activity.RESULT_OK) { if (resultData != null) { Uri fileUri = resultData.getData(); if (fileUri != null) { // Read file content into a String String fileContent = readTextFromUri(fileUri); // Pass content to Main2Activity Intent intent = new Intent(this, Main2Activity.class); intent.putExtra("TEXT_CONTENT", fileContent); startActivity(intent); } } } } /** * Helper method to read text from a file Uri */ private String readTextFromUri(Uri uri) { StringBuilder contentBuilder = new StringBuilder(); // Use try-with-resources to auto-close streams and avoid leaks try (InputStream inputStream = getContentResolver().openInputStream(uri); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) { String line; while ((line = reader.readLine()) != null) { contentBuilder.append(line).append("\n"); } } catch (IOException e) { e.printStackTrace(); } return contentBuilder.toString(); } }
Main2Activity Code to Receive and Display Content
Now update Main2Activity to grab the text content and populate your EditText:
package com.texttospeech; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.EditText; public class Main2Activity extends AppCompatActivity { private EditText contentEditText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); // Replace with your actual EditText ID from layout contentEditText = findViewById(R.id.your_edit_text_id); // Retrieve the text content from the intent String textContent = getIntent().getStringExtra("TEXT_CONTENT"); if (textContent != null) { contentEditText.setText(textContent); } } }
Quick Notes to Keep in Mind
- Ensure
Main2Activityis declared in yourAndroidManifest.xml(you probably already have this, but double-check!). - The
readTextFromUrimethod uses try-with-resources to safely handle file streams, which is the recommended practice to avoid resource leaks. - For very large TXT files, consider reading the content asynchronously (with coroutines or AsyncTask) to avoid blocking the main thread, but this code works great for most regular text files.
内容的提问来源于stack exchange,提问作者MURUGAN MURUGAN
相关产品推荐
相关产品推荐

