1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
| //Activity主程式
import java.sql.Date;
import java.text.SimpleDateFormat;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class SaveTestActivity extends Activity {
/** Called when the activity is first created. */
private ActionLogHelper helper;
private SimpleDateFormat df=new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.helper=new ActionLogHelper(this);
Button saveBt=(Button)findViewById(R.id.saveBtn);
saveBt.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
addActionLog("mike");
queryAndPrintActionLogs();
}
});
}
//此為資料庫寫入
private void addActionLog(String action){
SQLiteDatabase db=this.helper.getWritableDatabase();//寫入必須用getWritableDatabase()
//放資料進入
ContentValues values =new ContentValues();
values.put("name", action);
values.put("time", System.currentTimeMillis());
db.insertOrThrow(ActionLogHelper.TABLE_NAME, null, values);
}
//取資料庫資料
private void queryAndPrintActionLogs(){
SQLiteDatabase db=this.helper.getReadableDatabase(); //因為取資料所以要
//用getReadableDatabase()
Cursor cursor=db.query(ActionLogHelper.TABLE_NAME, new String[]{
"id","name","time"
}, null, null, null, null, "time DESC");
this.startManagingCursor(cursor);
StringBuilder data=new StringBuilder();
while(cursor.moveToNext()){
data.append(cursor.getLong(0));
data.append(" - ");
data.append(cursor.getString(1));
data.append(" @ ");
data.append(df.format(new Date(cursor.getLong(2))));
data.append("\n");
}
TextView msg=(TextView)this.findViewById(R.id.textView1);
msg.setText(data.toString());
}
}
|