2013-03-27 66 views
0

我正在努力如何使用edittext保存對我的file.txt的更改。到目前爲止,我的代碼將允許我打開文本文件,但是在關閉它時,它不會保存已做出的更改。該文本文件正在打開到另一個活動中,並將在方向更改時以及最小化時保存更改。我嘗試了大量不同的解決方案,但我無法理解如何存儲已做出的更改。如何從Edittext將信息保存到原始文件中android

public class Editor extends Activity { 
private String Text; 
private String Folder; 
private String toast; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_editor); 
    Bundle extras = getIntent().getExtras(); 
    this.Text = extras.getString ("txt"); 
    this.Folder = extras.getString("s"); 
    this.toast = (Folder + "/" + Text); 
    Toast.makeText(this, toast, Toast.LENGTH_SHORT).show(); 
    File sdcard = Environment.getExternalStorageDirectory(); 
    File file = new File(sdcard + "/NoteTaker/" + Folder + "/" + Text); 
    StringBuilder text = new StringBuilder(); 
    try { 
    BufferedReader br = new BufferedReader(new FileReader(file)); 
    String line; 
    while ((line = br.readLine()) != null) { 
    text.append(line); 
    text.append('\n'); 
    } 
    } 
    catch (IOException e) { 
    } 
    TextView tv = (TextView)findViewById(R.id.editText1); 
    tv.setText(text); 
    getActionBar().setDisplayHomeAsUpEnabled(true); 

} 

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

回答

1

如果你perfoming讀操作,然後使用InputStream

如果你perfoming寫操作,然後使用OuptputStream

這裏是one of your solution

+0

OMG謝謝。我一直在尋找這個好幾個小時,試圖把它整理出來,它終於可以運作 – 2013-03-27 16:19:59

+0

它是我的榮幸。 :) – QuokMoon 2013-03-27 16:50:41

0

這可能是你在找什麼:

public void onPause(){ 
    super.onPause(); 

    try{ 
     OutputStreamWriter out=new OutputStreamWriter(openFileOutput(NOTES, 0)); 

     out.write(editor.getText().toString()); 
     out.close(); 
    } 
    catch (Throwable t) { 
     Toast.makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG).show(); 
    } 
} 

您將需要改變NOTES變量您file_name.txt並不管你的EditText的名字是編輯器。

+0

我上改變編輯得到一個錯誤到EditText。錯誤是無法對非靜態線程進行靜態引用。我試圖創建: EditText =編輯; 在頂部並使用它,但仍然是一個錯誤。 – 2013-03-27 16:04:28

+0

EditText是佈局上的文本框,其中包含要保存到文件中的信息,除非您沒有用戶輸入自己的數據,在這種情況下,您將不會有EditText文本框。你定義一個EditText爲:'EditText myText =(EditText)findViewById(R.id.name_of_edittext_from_layout_xml);' – TronicZomB 2013-03-27 17:04:17

相關問題