您的onClick方法更改为这样的事情:
public void onClick(View v) {
Utils.appendLog(this, txtData.getText() + "," + dateFormat.format(new Date());
}
,并创建一个utils的类这些方法:
public class Utils {
public static void appendLog(Context ctx, String text) {
File logFile = new File(ctx.getFilesDir(), Constants.YOUR_FILENAME);
if (!logFile.exists()) {
try {
logFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
// BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(Utils.generateId(ctx) + "," + text);
buf.newLine();
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static int generateId(Context ctx) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
int id = prefs.getInt("MyId", 1);
Editor e = prefs.edit();
e.putInt("MyId", id +1);
e.commit();
return id;
}
}
短暂而甜蜜!这很好,非常感谢 – Leigh8347