我正在创建一个写入.txt文件的应用程序,并在每个“保存”结束时,我想要输入日期和时间。
这是我的代码,它将时间/日期转换为字符串,然后将其保存到文件中。
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
我遇到的问题是每次我节省时间都不会更新。 每一行有相同的时间和日期? 任何人都可以帮忙吗? 问候
答案 0 :(得分: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("");
}
答案 1 :(得分:1)
您总是在onCreate()
上仅创建一次的datetime对象上写入时间。您应该每次都在onClick()
获取当前时间。
为此,您应该将格式化程序作为类对象,然后在每次写入文件时创建新日期:
out.write(txtData.getText() + "," + txtData2.getText() +
"," + dateFormat.format(new Date());
请注意new Date()
会自动获取当前时间和日期。