im making an app that writes to a .txt file and at the end of each “save” i want to put the date and time.
this is my code that turns the time/date into a string then saves it to file.
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
The problem im having is every time i save the time does not update.
each row has the same time and date?
can anybody help?
regards
You always write the time on datetime object that is created only once in the
onCreate(). You should get the current time each time inonClick().To do this, you should se the formatter as class object and then create new Date every time when writing to file:
Notice that
new Date()automatically gets the current time and date.