存储文件中的数据并将其传递给新活动

时间:2013-12-02 16:06:25

标签: android android-activity android-edittext

下面的代码用于从edittext获取字符串并将其存储在一个文件中,这仅适用于1个edittext,如果我使用两个edittext它不起作用,我也希望在另一个活动上显示结果。< / p>

public class MainActivity extends Activity {
     File myInternalFile;
     File myExternalFile;
    private String filename = "MySampleFile.txt";
    private String filepath = "MyFileStorage";

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

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

public void saveInternalHandler(View view) 
 {
    EditText myInputText = (EditText) findViewById(R.id.myInputText);
    TextView responseText = (TextView) findViewById(R.id.responseText);
    ContextWrapper contextWrapper = new 
    ContextWrapper(getApplicationContext());
    File directory = contextWrapper.getDir(filepath, 
    Context.MODE_PRIVATE);
    myInternalFile = new File(directory , filename);

try {

    FileOutputStream fos = new FileOutputStream(myInternalFile);
    fos.write(myInputText.getText().toString().getBytes());
    fos.close();
 } 

catch (IOException e) {
    e.printStackTrace();
 }
    myInputText.setText("");
    responseText.setText("MySampleFile.txt saved to Internal Storage...");
 }

public void getInternalHandler(View view) 
 {
    EditText myInputText = (EditText) findViewById(R.id.myInputText);
    TextView responseText = (TextView) findViewById(R.id.responseText);
    String myData = "";

try {

    FileInputStream fis = new FileInputStream(myInternalFile);
    DataInputStream in = new DataInputStream(fis);
    BufferedReader br = new BufferedReader(new 
    InputStreamReader(in));
    String strLine;
    while ((strLine = br.readLine()) != null) {
    myData = myData + strLine;
 }
    in.close();
 } 
catch (IOException e) { e.printStackTrace();
 }
    myInputText.setText(myData);
    responseText.setText("MySampleFile.txt data retrieved from Internal Storage...");
 }
}

1 个答案:

答案 0 :(得分:0)

关于如何使用两个EditTexts的更多细节会很好。但我的猜测是你发现只显示第二个文本,这是因为当你打电话时

myInternalFile = new File(directory , filename);

第二次在directory创建 new 文件,其名称与旧文件相同,即您要覆盖旧文件。您需要myInternalFile作为全局变量。

至于如何在活动之间传递数据,特别是字符串,这是一个很好的资源: http://www.androidhive.info/2011/08/how-to-switch-between-activities-in-android/