· 9 years ago · Nov 23, 2016, 12:08 AM
1public class SQLiteCrudExample extends ListActivity {
2 //DB name
3 private final String dbName = "Android";
4 //Table name
5 private final String tableName = "Versions";
6 //String array has list Android versions which will be populated in the list
7 private final String[] versionNames= new String[]{"Cupcake", "Donut", "Eclair", "Froyo", "Gingerbread", "Honeycomb", "Ice Cream Sandwich", "Jelly Bean", "Kitkat"};
8 @Override
9 public void onCreate(Bundle savedInstanceState) {
10 super.onCreate(savedInstanceState);
11 ArrayList<String> results = new ArrayList<String>();
12 //Declare SQLiteDatabase object
13 SQLiteDatabase sampleDB = null;
14
15 try {
16 //Instantiate sampleDB object
17 sampleDB = this.openOrCreateDatabase(dbName, MODE_PRIVATE, null);
18 //Create table using execSQL
19 sampleDB.execSQL("CREATE TABLE IF NOT EXISTS " + tableName + " (versionname VARCHAR);");
20 //Insert Android versions into table created
21 for(String ver: versionNames){
22 sampleDB.execSQL("INSERT INTO " + tableName + " Values ('"+ver+"');");
23 }
24
25 //Create Cursor object to read versions from the table
26 Cursor c = sampleDB.rawQuery("SELECT versionname FROM " + tableName, null);
27 //If Cursor is valid
28 if (c != null ) {
29 //Move cursor to first row
30 if (c.moveToFirst()) {
31 do {
32 //Get version from Cursor
33 String firstName = c.getString(c.getColumnIndex("versionname"));
34 //Add the version to Arraylist 'results'
35 results.add(firstName);
36 }while (c.moveToNext()); //Move to next row
37 }
38 }
39
40 //Set the ararylist to Android UI List
41 this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,results));
42
43 } catch (SQLiteException se ) {
44 Toast.makeText(getApplicationContext(), "Couldn't create or open the database", Toast.LENGTH_LONG).show();
45 } finally {
46 if (sampleDB != null) {
47 sampleDB.execSQL("DELETE FROM " + tableName);
48 sampleDB.close();
49 }
50 }
51 }
52}
53
54package com.bict.lab.customtodo;
55
56import android.app.Activity;
57import android.app.DatePickerDialog;
58import android.content.ContentValues;
59import android.database.Cursor;
60import android.net.Uri;
61import android.os.Bundle;
62import android.text.TextUtils;
63import android.view.View;
64import android.widget.Button;
65import android.widget.DatePicker;
66import android.widget.EditText;
67import android.widget.Spinner;
68import android.widget.Toast;
69
70import java.text.SimpleDateFormat;
71import java.util.Calendar;
72import java.util.Locale;
73
74public class DetailToDo extends Activity{
75
76 private Spinner mCategory;
77 private EditText mTitleText;
78 private EditText mBodyText;
79 private EditText mDueDate;
80
81 private Uri todoUri;
82
83 //private EditText toDateEtxt;
84 private DatePickerDialog toDatePickerDialog;
85 private SimpleDateFormat dateFormatter;
86
87 @Override
88 protected void onCreate(Bundle savedInstanceState) {
89 super.onCreate(savedInstanceState);
90 setContentView(R.layout.activity_detail_to_do);
91
92 mCategory = (Spinner)findViewById(R.id.category);
93 mTitleText = (EditText) findViewById(R.id.edit_todo_summary);
94 mBodyText = (EditText) findViewById(R.id.edit_todo_description);
95 mDueDate = (EditText) findViewById(R.id.edit_todo_duedate);
96 Button confirmButton = (Button) findViewById(R.id.edit_todo_button);
97
98 Bundle extras = getIntent().getExtras();
99
100 // check from the saved Instance
101 todoUri = (savedInstanceState == null) ? null : (Uri) savedInstanceState
102 .getParcelable(ContentToDo.CONTENT_ITEM_TYPE);
103 // Or passed from the other activity
104 if (extras != null) {
105 todoUri = extras
106 .getParcelable(ContentToDo.CONTENT_ITEM_TYPE);
107
108 fillData(todoUri);
109 }
110
111 confirmButton.setOnClickListener(new View.OnClickListener() {
112 public void onClick(View view) {
113 if (TextUtils.isEmpty(mTitleText.getText().toString())) {
114 makeToast();
115 } else {
116 setResult(RESULT_OK);
117 finish();
118 }
119 }
120
121 });
122
123 dateFormatter = new SimpleDateFormat("dd-MM-yyyy", Locale.US);
124
125 setDateTimeField();
126 }
127
128 private void setDateTimeField() {
129 Calendar newCalendar = Calendar.getInstance();
130 toDatePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
131
132 public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
133 Calendar newDate = Calendar.getInstance();
134 newDate.set(year, monthOfYear, dayOfMonth);
135 mDueDate.setText(dateFormatter.format(newDate.getTime()));
136 }
137
138 },newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
139
140 mDueDate.setOnFocusChangeListener(new View.OnFocusChangeListener() {
141 @Override
142 public void onFocusChange(View view, boolean b) {
143 if (b){
144 toDatePickerDialog.show();
145 }
146 }
147 });
148 }
149
150 private void fillData(Uri uri) {
151 String[] projection = { TblToDoDB.COLUMN_SUMMARY,
152 TblToDoDB.COLUMN_DESCRIPTION, TblToDoDB.COLUMN_CATEGORY, TblToDoDB.COLUMN_DUEDATE };
153 Cursor cursor = getContentResolver().query(uri, projection, null, null,
154 null);
155 if (cursor != null) {
156 cursor.moveToFirst();
157 String category = cursor.getString(cursor
158 .getColumnIndexOrThrow(TblToDoDB.COLUMN_CATEGORY));
159
160 for (int i = 0; i < mCategory.getCount(); i++) {
161
162 String s = (String) mCategory.getItemAtPosition(i);
163 if (s.equalsIgnoreCase(category)) {
164 mCategory.setSelection(i);
165 }
166 }
167
168 mTitleText.setText(cursor.getString(cursor
169 .getColumnIndexOrThrow(TblToDoDB.COLUMN_SUMMARY)));
170 mBodyText.setText(cursor.getString(cursor
171 .getColumnIndexOrThrow(TblToDoDB.COLUMN_DESCRIPTION)));
172 mDueDate.setText(cursor.getString(cursor
173 .getColumnIndexOrThrow(TblToDoDB.COLUMN_DUEDATE)));
174
175 // always close the cursor
176 cursor.close();
177 }
178 }
179
180 protected void onSaveInstanceState(Bundle outState) {
181 super.onSaveInstanceState(outState);
182 saveState();
183 outState.putParcelable(ContentToDo.CONTENT_ITEM_TYPE, todoUri);
184 }
185 @Override
186 protected void onPause() {
187 super.onPause();
188 saveState();
189 }
190 private void saveState() {
191 String category = (String) mCategory.getSelectedItem();
192 String summary = mTitleText.getText().toString();
193 String description = mBodyText.getText().toString();
194 String duedate = mDueDate.getText().toString();
195
196 // only save if either summary or description
197 // is available
198
199 if (description.length() == 0 && summary.length() == 0) {
200 return;
201 }
202
203 ContentValues values = new ContentValues();
204 values.put(TblToDoDB.COLUMN_CATEGORY, category);
205 values.put(TblToDoDB.COLUMN_SUMMARY, summary);
206 values.put(TblToDoDB.COLUMN_DESCRIPTION, description);
207 values.put(TblToDoDB.COLUMN_DUEDATE, duedate);
208
209 if (todoUri == null) {
210 // New todo
211 todoUri = getContentResolver().insert(ContentToDo.CONTENT_URI, values);
212 } else {
213 // Update todo
214 getContentResolver().update(todoUri, values, null, null);
215 }
216 }
217 private void makeToast() {
218 Toast.makeText(DetailToDo.this, "Please maintain a summary",
219 Toast.LENGTH_LONG).show();
220 }
221}
222
223package com.bict.lab.customtodo;
224
225import android.content.ContentProvider;
226import android.content.ContentResolver;
227import android.content.ContentValues;
228import android.content.UriMatcher;
229import android.database.Cursor;
230import android.database.sqlite.SQLiteDatabase;
231import android.database.sqlite.SQLiteQueryBuilder;
232import android.net.Uri;
233import android.text.TextUtils;
234
235import java.util.Arrays;
236import java.util.HashSet;
237
238/**
239 * Created by 1381832 on 7/11/2016.
240 */
241public class ContentToDo extends ContentProvider {
242 // database
243 private DbHelper database;
244
245 // used for the UriMatcher
246 private static final int TODOS = 10;
247 private static final int TODO_ID = 20;
248
249 private static final String AUTHORITY = "com.bict.lab.customtodo";
250
251 private static final String BASE_PATH = "todos";
252 public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH);
253
254 public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/todos";
255
256 public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/todo";
257
258 private static final UriMatcher sURIMatcher = new UriMatcher(UriMatcher.NO_MATCH);
259 static {
260 sURIMatcher.addURI(AUTHORITY, BASE_PATH, TODOS);
261 sURIMatcher.addURI(AUTHORITY, BASE_PATH + "/#", TODO_ID);
262 }
263
264 @Override
265 public int delete(Uri uri, String selection, String[] selectionArgs){
266 int uriType = sURIMatcher.match(uri);
267 SQLiteDatabase sqlDB = database.getWritableDatabase();
268 int rowsDeleted = 0;
269 switch (uriType) {
270 case TODOS:
271 rowsDeleted = sqlDB.delete(TblToDoDB.TABLE_TODO, selection, selectionArgs);
272 break;
273 case TODO_ID:
274 String id = uri.getLastPathSegment();
275 if (TextUtils.isEmpty(selection)) {
276 rowsDeleted = sqlDB.delete(TblToDoDB.TABLE_TODO,
277 TblToDoDB.COLUMN_ID + "=" + id, null);
278 } else {
279 rowsDeleted = sqlDB.delete(TblToDoDB.TABLE_TODO, TblToDoDB.COLUMN_ID + "=" + id + " and " + selection, selectionArgs);
280 }
281 break;
282 default:
283
284 throw new IllegalArgumentException("Unknown URI: " + uri);
285 }
286 getContext().getContentResolver().notifyChange(uri, null);
287 return rowsDeleted;
288 }
289
290 @Override
291 public String getType(Uri arg0) {
292 // TODO Auto-generated method stub
293 return null;
294 }
295
296 @Override
297 public Uri insert(Uri uri, ContentValues values) {
298 int uriType = sURIMatcher.match(uri);
299 SQLiteDatabase sqlDB = database.getWritableDatabase();
300 //int rowsDeleted = 0;
301 long id = 0;
302 switch (uriType) {
303 case TODOS:
304 id = sqlDB.insert(TblToDoDB.TABLE_TODO, null, values);
305 break;
306 default:
307 throw new IllegalArgumentException("Unknown URI: " + uri);
308 }
309 getContext().getContentResolver().notifyChange(uri, null);
310 return Uri.parse(BASE_PATH + "/" + id);
311 }
312
313 @Override
314 public boolean onCreate() {
315 database = new DbHelper(getContext());
316 return false;
317 }
318
319 @Override
320 public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
321 // Using SQLiteQueryBuilder instead of query() method
322 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
323
324// check if the caller has requested a column which does not exist
325 checkColumns(projection);
326
327 // Set the table
328 queryBuilder.setTables(TblToDoDB.TABLE_TODO);
329
330 int uriType = sURIMatcher.match(uri);
331 switch (uriType) {
332 case TODOS:
333 break;
334 case TODO_ID:
335 // adding the ID to the original query
336 queryBuilder.appendWhere(TblToDoDB.COLUMN_ID + "=" + uri.getLastPathSegment());
337 break;
338
339 default:
340 throw new IllegalArgumentException("Unknown URI: " + uri);
341 }
342
343 SQLiteDatabase db = database.getWritableDatabase();
344 Cursor cursor = queryBuilder.query(db, projection, selection,
345 selectionArgs, null, null, sortOrder);
346// make sure that potential listeners are getting notified
347 cursor.setNotificationUri(getContext().getContentResolver(), uri);
348
349 return cursor;
350 }
351
352 @Override
353 public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
354
355 int uriType = sURIMatcher.match(uri);
356 SQLiteDatabase sqlDB = database.getWritableDatabase();
357 int rowsUpdated = 0;
358 switch (uriType) {
359 case TODOS:
360 rowsUpdated = sqlDB.update(TblToDoDB.TABLE_TODO,
361 values,
362 selection,
363 selectionArgs);
364 break;
365 case TODO_ID:
366 String id = uri.getLastPathSegment();
367 if (TextUtils.isEmpty(selection)) {
368 rowsUpdated = sqlDB.update(TblToDoDB.TABLE_TODO,
369 values,
370 TblToDoDB.COLUMN_ID + "=" + id,
371 null);
372 } else {
373 rowsUpdated = sqlDB.update(TblToDoDB.TABLE_TODO,
374 values,
375 TblToDoDB.COLUMN_ID + "=" + id
376 + " and "
377 + selection,
378 selectionArgs);
379 }
380 break;
381 default:
382 throw new IllegalArgumentException("Unknown URI: " + uri);
383 }
384 getContext().getContentResolver().notifyChange(uri, null);
385 return rowsUpdated;
386 }
387 private void checkColumns(String[] projection) {
388 String[] available = { TblToDoDB.COLUMN_CATEGORY,
389 TblToDoDB.COLUMN_SUMMARY, TblToDoDB.COLUMN_DESCRIPTION, TblToDoDB.COLUMN_DUEDATE,
390 TblToDoDB.COLUMN_ID };
391 if (projection != null) {
392 HashSet<String> requestedColumns = new HashSet<String>(Arrays.asList(projection));
393
394 HashSet<String> availableColumns = new HashSet<String>(Arrays.asList(available));
395 // check if all columns which are requested are available
396 if (!availableColumns.containsAll(requestedColumns)) {
397 throw new IllegalArgumentException("Unknown columns in projection");
398 }
399 }
400 }
401}
402
403
404
405
406
407
408
409package com.bict.lab.customtodo;
410
411import android.content.Context;
412import android.database.sqlite.SQLiteDatabase;
413import android.database.sqlite.SQLiteOpenHelper;
414
415/**
416 * Created by 1381832 on 7/11/2016.
417 */
418public class DbHelper extends SQLiteOpenHelper {
419
420 private static final String DATABASE_NAME = "TblToDoDB.db";
421 private static final int DATABASE_VERSION = 1;
422
423 public DbHelper(Context context) {
424 super(context, DATABASE_NAME, null, DATABASE_VERSION);
425 }
426
427 // Method is called during creation of the database
428 @Override
429 public void onCreate(SQLiteDatabase database) {
430 TblToDoDB.onCreate(database);
431 }
432
433 // Method is called during an upgrade of the database,
434 // e.g. if you increase the database version
435 @Override
436 public void onUpgrade(SQLiteDatabase database, int oldVersion,
437 int newVersion) {
438 TblToDoDB.onUpgrade(database, oldVersion, newVersion);
439 }
440}
441
442
443package com.bict.lab.customtodo;
444
445import android.database.sqlite.SQLiteDatabase;
446import android.util.Log;
447
448/**
449 * Created by 1381832 on 7/11/2016.
450 */
451public class TblToDoDB {
452 public static final String TABLE_TODO = "todo";
453 public static final String COLUMN_ID = "_id";
454 public static final String COLUMN_CATEGORY = "category";
455 public static final String COLUMN_SUMMARY = "summary";
456 public static final String COLUMN_DESCRIPTION = "description";
457 public static final String COLUMN_DUEDATE = "due_date";
458
459 // Database creation SQL statement
460 private static final String DATABASE_CREATE = "create table "
461 + TABLE_TODO
462 + "("
463 + COLUMN_ID + " integer primary key autoincrement, "
464 + COLUMN_CATEGORY + " text not null, "
465 + COLUMN_SUMMARY + " text not null,"
466 + COLUMN_DUEDATE + " text not null,"
467 + COLUMN_DESCRIPTION
468 + " text not null"
469 + ");";
470
471 public static void onCreate(SQLiteDatabase database) {
472 database.execSQL(DATABASE_CREATE);
473 }
474
475 public static void onUpgrade(SQLiteDatabase database, int oldVersion,
476 int newVersion) {
477 Log.w(TblToDoDB.class.getName(), "Upgrading database from version "
478 + oldVersion + " to " + newVersion
479 + ", which will destroy all old data");
480 database.execSQL("DROP TABLE IF EXISTS " + TABLE_TODO);
481 onCreate(database);
482 }
483}
484
485
486
487package com.bict.lab.customtodo;
488
489import android.app.ListActivity;
490import android.app.LoaderManager;
491import android.content.CursorLoader;
492import android.content.Intent;
493import android.content.Loader;
494import android.database.Cursor;
495import android.net.Uri;
496import android.os.Build;
497import android.os.Bundle;
498import android.support.annotation.RequiresApi;
499import android.view.ContextMenu;
500import android.view.Menu;
501import android.view.MenuItem;
502import android.view.View;
503import android.widget.AdapterView;
504import android.widget.ListView;
505import android.widget.SimpleCursorAdapter;
506
507
508
509@RequiresApi(api = Build.VERSION_CODES.N)
510public class MainToDo extends ListActivity implements LoaderManager.LoaderCallbacks<Cursor> {
511 private static final int DELETE_ID = Menu.FIRST + 1;
512 // private Cursor cursor;
513 private SimpleCursorAdapter adapter;
514
515
516 @Override
517 protected void onCreate(Bundle savedInstanceState) {
518 super.onCreate(savedInstanceState);
519 setContentView(R.layout.activity_main_to_do);
520 this.getListView().setDividerHeight(2);
521 fillData();
522 registerForContextMenu(getListView());
523
524
525 }
526
527
528
529
530
531
532 @Override
533 public boolean onCreateOptionsMenu(Menu menu) {
534 // Inflate the menu; this adds items to the action bar if it is present.
535 getMenuInflater().inflate(R.menu.menu_main_to_do, menu);
536 return true;
537
538
539 }
540
541 @Override
542 public boolean onOptionsItemSelected(MenuItem item) {
543 // Handle action bar item clicks here. The action bar will
544 // automatically handle clicks on the Home/Up button, so long
545 // as you specify a parent activity in AndroidManifest.xml.
546 switch (item.getItemId()) {
547 case R.id.insert:
548 createTodo();
549 return true;
550 }
551
552
553 return super.onOptionsItemSelected(item);
554 }
555
556 @Override
557 public boolean onContextItemSelected(MenuItem item) {
558 switch (item.getItemId()) {
559 case DELETE_ID:
560 AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
561 Uri uri = Uri.parse(ContentToDo.CONTENT_URI + "/" + info.id);
562 getContentResolver().delete(uri, null, null);
563 fillData();
564 return true;
565 }
566 return super.onContextItemSelected(item);
567 }
568
569 private void createTodo() {
570 Intent i = new Intent(this, DetailToDo.class);
571 startActivity(i);
572 }
573
574 // Opens the second activity if an entry is clicked
575 @Override
576 protected void onListItemClick(ListView l, View v, int position, long id) {
577 super.onListItemClick(l, v, position, id);
578 Intent i = new Intent(this, DetailToDo.class);
579 Uri todoUri = Uri.parse(ContentToDo.CONTENT_URI + "/" + id);
580 i.putExtra(ContentToDo.CONTENT_ITEM_TYPE, todoUri);
581
582 startActivity(i);
583 }
584
585 private void fillData() {
586 // Fields from the database, Must include the _id column for the adapter to work
587 String[] from = new String[] { TblToDoDB.COLUMN_SUMMARY,
588 };
589
590 // Fields on the UI to which we map
591 int[] to = new int[] {
592 R.id.label,
593 };
594
595 getLoaderManager().initLoader(0, null, this);
596 adapter = new SimpleCursorAdapter(this, R.layout.row_todo, null,from,to, 0);
597
598 setListAdapter(adapter);
599 }
600
601 @Override
602 public void onCreateContextMenu(ContextMenu menu, View v,
603 ContextMenu.ContextMenuInfo menuInfo) {
604 super.onCreateContextMenu(menu, v, menuInfo);
605 menu.add(0, DELETE_ID, 0, R.string.menu_delete);
606 }
607
608 // creates a new loader after the initLoader () call
609 @Override
610 public Loader<Cursor> onCreateLoader(int id, Bundle args) {
611
612 String[] projection = { TblToDoDB.COLUMN_ID, TblToDoDB.COLUMN_SUMMARY, TblToDoDB.COLUMN_DUEDATE };
613 CursorLoader cursorLoader = new CursorLoader(this,
614 ContentToDo.CONTENT_URI, projection, null, null, null);
615 return cursorLoader;
616 }
617
618 @Override
619 public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
620 adapter.swapCursor(data);
621 }
622
623 @Override
624 public void onLoaderReset(Loader<Cursor> loader) {
625 // data is not available anymore, delete reference
626 adapter.swapCursor(null);
627 }
628
629
630}