2011-11-02 92 views
1

即時製作一個應用程序寫入.txt文件,並在每個「保存」結束時,我想把日期和時間。Android - 時間不更新

這是我的代碼,將時間/日期變成一個字符串,然後將其保存到文件。

public class SaveFile extends Activity { 

EditText txtData; 
EditText txtData2; 
Button btnWriteSDFile; 
Button btnDelete; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.form); 

SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss"); 
    Date date = new Date(System.currentTimeMillis()); 
    final String datetime = dateFormat.format(date); 

txtData = (EditText) findViewById(R.id.input1); 
txtData2 = (EditText) findViewById(R.id.input2); 

btnWriteSDFile = (Button) findViewById(R.id.save); 
btnWriteSDFile.setOnClickListener(new OnClickListener() { 

public void onClick(View v) { 
    // write on SD card file data in the text box 

    try { 
     BufferedWriter out = new BufferedWriter(new FileWriter("/sdcard/data_file.txt", true)); 
     out.write(txtData.getText() + "," + txtData2.getText() + "," + datetime.toString()); 
     out.write("\r\n"); 
     out.close(); 
     Toast.makeText(v.getContext(),"Saved",Toast.LENGTH_SHORT).show(); 
    } catch (Exception e) { 
     Toast.makeText(v.getContext(), e.getMessage(),Toast.LENGTH_SHORT).show(); 
    } 


     txtData.setText(""); 
     txtData2.setText(""); 


}// onClick 
}); // btnWriteSDFile 

}// onCreate 

}// AndSDcard 

即時通訊存在的問題是我每次保存時間不更新。 每一行有相同的時間和日期? 任何人都可以幫忙嗎? 關於

+1

只是擡起頭來,您正在主線程上寫入SDCard。當數據很小時,它可能不會成爲大多數設備上的問題,但是如果有大量數據要寫入,設備正忙於使用SDCard作爲其他內容等,則會導致ANR。 – FunkTheMonk

回答

1

,你老是寫所創建僅在onCreate()一次DateTime對象上的時間。您應該每次在onClick()獲得當前時間。

要寫入文件的時候做到這一點,你應該瑟格式化爲類對象,然後創建新的日期,每次:

out.write(txtData.getText() + "," + txtData2.getText() + 
      "," + dateFormat.format(new Date()); 

注意new Date()自動獲取當前的時間和日期。

+0

工作對待,非常感謝 – Leigh8347

1

您正在獲取當前時間並重新使用它。你應該得到的當前時間的事件處理中:

public void onClick(View v) { 
    // write on SD card file data in the text box  
    try { 
     BufferedWriter out = new BufferedWriter(new FileWriter("/sdcard/data_file.txt", true)); 
     Date date = new Date(System.currentTimeMillis()); 
     final String datetime = dateFormat.format(date);  
     out.write(txtData.getText() + "," + 
        txtData2.getText() + "," + 
        datetime.toString()); 
     out.write("\r\n"); 
     out.close(); 
     Toast.makeText(v.getContext(),"Saved",Toast.LENGTH_SHORT).show(); 
    } catch (Exception e) { 
     Toast.makeText(v.getContext(), e.getMessage(),Toast.LENGTH_SHORT).show(); 
    } 

    txtData.setText(""); 
    txtData2.setText(""); 
}