Lập trình Android: TodoList dùng SQLite
04/08/2012
FacebookTwitterDeliciousStumbleuponDiggMyspaceLinkedInZingmegovnlinkhay


1 ứng dụng dùng SQLite nhỏ và đơn giản cho các bạn muốn lập trình CSDL Project: Project name: Todo_list Build Target: Android 2.1 Application name: Todo_list Package name: com.dac Create Activity: ToDoList Các bạn tạo thêm 1 file myDbHelper làm đối tượng xử lý SQLite: PHP Code:  
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
package com.dac;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class myDbHelper extends SQLiteOpenHelper {
    ///////Ten va version cua Database:
    private static final String DB_NAME = "TDList";
    private static final int DB_VERSION = 1;
    ///////Bang va cac cot trong bang
    public static final String TABLE_NAME = "list1";
    public static final String COL_ITEM = "cItem";
    public static final String COL_DATE = "cDate";
    ///////Cau lenh tao bang:
    private static final String STRING_CREATE = "CREATE TABLE "+TABLE_NAME +" (_id INTEGER PRIMARY KEY AUTOINCREMENT, "
        + COL_ITEM +" TEXT, " +COL_DATE +" DATE);";
    public myDbHelper(Context context) {
        super(context,DB_NAME,null,DB_VERSION);
        // TODO Auto-generated constructor stub
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        /////////Tao table
        db.execSQL(STRING_CREATE);
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int onlVersion, int newVersion) {
        // TODO Auto-generated method stub
        /////Xoa bang va tao lai neu co'
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }
}
Trong file Activity:
PHP Code:
package com.dac;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.view. Menu;
import android.view.MenuItem;
import android.view.ContextMenu;
import android.widget.AdapterView;
public class ToDoList extends Activity {
    static final private int ADD_NEW_TODO = Menu.FIRST;
    static final private int REMOVE_TODO = Menu.FIRST+1;
    private boolean  addingNew = false;
    ListView myListView ;
    private EditText myEditText;
    ///////////Phan DataBase
    myDbHelper mHelper;
    SQLiteDatabase mDb;
    Cursor mCursor;
    SimpleCursorAdapter mAdapter;
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // TODO Auto-generated method stub
        super.onCreateOptionsMenu(menu);
        MenuItem itemAdd = menu.add(0, ADD_NEW_TODO, Menu.NONE, R.string.add_new);
        MenuItem itemRem = menu.add(0,REMOVE_TODO,Menu.NONE,R.string.remove);
        itemAdd.setIcon(R.drawable.add_icon);
        itemRem.setIcon(R.drawable.remove_icon);
        itemAdd.setShortcut('0', 'a');
        itemRem.setShortcut('1','r');
        return true;
    }
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Inflate your view
        setContentView(R.layout.main);
        // Get references to UI
       myListView = (ListView)findViewById(R.id.myListView);
       myEditText = (EditText) findViewById(R.id.myEditText);
       //////////Database:
       myEditText.setOnKeyListener(new OnKeyListener() {
         public boolean onKey(View v, int keyCode, KeyEvent event) {
                   if (event.getAction() == KeyEvent.ACTION_DOWN)
                       if (keyCode == KeyEvent.KEYCODE_ENTER){
                           ////////////Phan DataBase:
                           ContentValues cv = new ContentValues(2);
                           cv.put(myDbHelper.COL_ITEM, myEditText.getText().toString());
                           SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy - HH:mm:ss");
                           cv.put(myDbHelper.COL_DATE, df.format(new Date()));
                           mDb.insert(myDbHelper.TABLE_NAME, null, cv);
                           mCursor. requery();
                           mAdapter.notifyDataSetChanged();
                           myEditText.setText(null);
                           cancelAdd();
                           return true;
                       }
                   return false;
               }
           });
       registerForContextMenu(myListView);
       ////////////Phan Database:
       mHelper = new myDbHelper(this);
    }
    private void cancelAdd()
    {
        addingNew = false;
        myEditText.setVisibility(View.GONE);
    }
    private void removeItem(int id)
    {
        mCursor.moveToPosition(id);
        String rowID = mCursor.getString(0);
        mDb.delete(myDbHelper.TABLE_NAME, "_id = ?", new String[] {rowID});
        mCursor.requery();
        mAdapter.notifyDataSetChanged();
    }
    private void addNewItem()
    {
        addingNew = true;
        myEditText.setVisibility(View.VISIBLE);
        myEditText.requestFocus();
    }
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        super.onContextItemSelected(item);
        switch (item.getItemId()) {
        case (REMOVE_TODO):
            AdapterView.AdapterContextMenuInfo m;
            m = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
            int index = m.position;
            removeItem(index);
            return true;
        }
        return false;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        super.onOptionsItemSelected(item);
        int index = myListView.getSelectedItemPosition();
        switch (item.getItemId()) {
        case (REMOVE_TODO):
            {
                if(addingNew)
                    cancelAdd();
                else {
                    removeItem(index);
                }
                return true;
            }
        case (ADD_NEW_TODO):
            {
                addNewItem();
                return true;
            }
        }
        return false;
    }
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        // TODO Auto-generated method stub
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.setHeaderTitle("Selected To Do Item");
    menu.add(0,REMOVE_TODO,Menu.NONE,R.string.remove);
    }
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // TODO Auto-generated method stub
        super.onPrepareOptionsMenu(menu);
        int idx = myListView.getSelectedItemPosition();
        String removeTitle = getString(addingNew?R.string.cancel:R.string.remove);
        MenuItem removeItem = menu.findItem(REMOVE_TODO);
        removeItem.setTitle(removeTitle);
        removeItem.setVisible(addingNew