· 8 years ago · May 05, 2018, 04:46 PM
1===========================================================================================================================
2
3
4//This is the database creation
5
6public class LogDb {
7
8 public static final String KEY_ROWID = "_id";
9 public static final String KEY_DATE = "date";
10 public static final String KEY_WORKOUT = "workout";
11 public static final String KEY_MUSCLE = "muscle";
12
13 private static final String LOG_TAG = "LogDb";
14 public static final String SQLITE_TABLE = "Log";
15
16 private static final String DATABASE_CREATE =
17 "CREATE TABLE if not exists "+ SQLITE_TABLE + " (" +
18 KEY_ROWID + " integer PRIMARY KEY autoincrement, " +
19 KEY_DATE + "," +
20 KEY_WORKOUT + ", " +
21 KEY_MUSCLE + ", " +
22 " UNIQUE ("+KEY_DATE+"));";
23
24 public static void onCreate(SQLiteDatabase db) {
25 Log.w(LOG_TAG, DATABASE_CREATE);
26 db.execSQL(DATABASE_CREATE);
27 }
28
29 public static void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
30 Log.w(LOG_TAG, "Upgrading database from version "+oldVersion+" to "+newVersion+", which will destroy all old data");
31 db.execSQL("DROP TABLE IF EXISTS " + SQLITE_TABLE);
32 onCreate(db);
33 }
34
35}
36
37===========================================================================================================================
38
39
40//This is the class where the list is displayed and contains the button to add to the list.
41
42public class LogActivity extends Activity implements
43 LoaderManager.LoaderCallbacks<Cursor>{
44
45 private SimpleCursorAdapter dataAdapter;
46
47 @Override
48 public void onCreate(Bundle savedInstanceState) {
49 super.onCreate(savedInstanceState);
50 setContentView(R.layout.activity_log);
51
52 displayListView();
53
54 Button add = (Button) findViewById(R.id.add);
55 add.setOnClickListener(new View.OnClickListener() {
56
57 public void onClick(View v) {
58 // starts a new Intent to add a workout
59 Intent workoutEdit = new Intent(getBaseContext(), WorkoutEdit.class);
60 Bundle bundle = new Bundle();
61 bundle.putString("mode", "add");
62 workoutEdit.putExtras(bundle);
63 startActivity(workoutEdit);
64 }
65 });
66
67 }
68
69 @Override
70 protected void onResume() {
71 super.onResume();
72 //Starts a new or restarts an existing Loader in this manager
73 getLoaderManager().restartLoader(0, null, this);
74 }
75
76 private void displayListView() {
77
78
79 // The desired columns to be bound
80 String[] columns = new String[] {
81 LogDb.KEY_DATE,
82 LogDb.KEY_WORKOUT,
83 LogDb.KEY_MUSCLE
84 };
85
86 // the XML defined views which the data will be bound to
87 int[] to = new int[] {
88 R.id.date,
89 R.id.workout,
90 R.id.muscle,
91 };
92
93 // create an adapter from the SimpleCursorAdapter
94 dataAdapter = new SimpleCursorAdapter(
95 this,
96 R.layout.workout_info,
97 null,
98 columns,
99 to,
100 0);
101
102 // get reference to the ListView
103 ListView listView = (ListView) findViewById(R.id.workoutList);
104 // Assign adapter to ListView
105 listView.setAdapter(dataAdapter);
106 //Ensures a loader is initialized and active.
107 getLoaderManager().initLoader(0, null, this);
108
109
110 listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
111 @Override
112 public void onItemClick(AdapterView<?> listView, View view,
113 int position, long id) {
114 // Get the cursor, positioned to the corresponding row in the result set
115 Cursor cursor = (Cursor) listView.getItemAtPosition(position);
116
117 // display the selected country
118 String countryCode =
119 cursor.getString(cursor.getColumnIndexOrThrow(LogDb.KEY_DATE));
120 Toast.makeText(getApplicationContext(),
121 countryCode, Toast.LENGTH_SHORT).show();
122
123 String rowId =
124 cursor.getString(cursor.getColumnIndexOrThrow(LogDb.KEY_ROWID));
125
126 // starts a new Intent to update/delete a workout
127 // pass in row Id to create the Content URI for a single row
128 Intent workoutEdit = new Intent(getBaseContext(), WorkoutEdit.class);
129 Bundle bundle = new Bundle();
130 bundle.putString("mode", "update");
131 bundle.putString("rowId", rowId);
132 workoutEdit.putExtras(bundle);
133 startActivity(workoutEdit);
134
135 }
136 });
137
138 }
139
140 // This is called when a new Loader needs to be created.
141 @Override
142 public Loader<Cursor> onCreateLoader(int id, Bundle args) {
143 String[] projection = {
144 LogDb.KEY_ROWID,
145 LogDb.KEY_DATE,
146 LogDb.KEY_WORKOUT,
147 LogDb.KEY_MUSCLE};
148 CursorLoader cursorLoader = new CursorLoader(this,
149 MyContentProvider.CONTENT_URI, projection, null, null, null);
150 return cursorLoader;
151 }
152
153 @Override
154 public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
155 // Swap the new cursor in. (The framework will take care of closing the
156 // old cursor once we return.)
157 dataAdapter.swapCursor(data);
158 }
159
160 @Override
161 public void onLoaderReset(Loader<Cursor> loader) {
162 // This is called when the last Cursor provided to onLoadFinished()
163 // above is about to be closed. We need to make sure we are no
164 // longer using it.
165 dataAdapter.swapCursor(null);
166 }
167
168 @Override
169 public boolean onCreateOptionsMenu(Menu menu) {
170 getMenuInflater().inflate(R.menu.main_menu, menu);
171 return true;
172 }
173}
174
175===========================================================================================================================
176
177//This is the class for the Content Provider
178
179public class MyContentProvider extends ContentProvider {
180
181 private MyDatabaseHelper dbHelper;
182
183 private static final int ALL_WORKOUTS = 1;
184 private static final int SINGLE_WORKOUT = 2;
185
186 private static final String AUTHORTIY = "com.example.jordan.trainr3.contentprovider";
187
188 public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORTIY + "/workouts");
189
190 private static final UriMatcher uriMatcher;
191 static {
192 uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
193 uriMatcher.addURI(AUTHORTIY, "workouts", ALL_WORKOUTS);
194 uriMatcher.addURI(AUTHORTIY, "workouts/#", SINGLE_WORKOUT);
195 }
196
197 @Override
198 public boolean onCreate(){
199 dbHelper = new MyDatabaseHelper(getContext());
200 return false;
201 }
202
203 @Override
204 public String getType(Uri uri){
205
206 switch (uriMatcher.match(uri)){
207 case ALL_WORKOUTS:
208 return "vnd.android.cursor.dir/vnd.com.example.jordan.trainr3.contentprovider.workouts";
209 case SINGLE_WORKOUT:
210 return "vnd.android.cursor.item/vnd.com.example.jordan.trainr3.contentprovider.workouts";
211 default:
212 throw new IllegalArgumentException("Unsupported URI: "+ uri);
213 }
214 }
215
216 @Override
217 public Uri insert(Uri uri, ContentValues values){
218
219 SQLiteDatabase db = dbHelper.getWritableDatabase();
220 switch (uriMatcher.match(uri)) {
221 case ALL_WORKOUTS:
222 break;
223 default:
224 throw new IllegalArgumentException("Unsupported URI: " + uri);
225 }
226 long id = db.insert(LogDb.SQLITE_TABLE, null, values);
227 getContext().getContentResolver().notifyChange(uri, null);
228 return Uri.parse(CONTENT_URI + "/" + id);
229 }
230
231 @Override
232 public Cursor query(Uri uri, String[] projection, String selection,
233 String[] selectionArgs, String sortOrder) {
234
235 SQLiteDatabase db = dbHelper.getWritableDatabase();
236 SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
237 queryBuilder.setTables(LogDb.SQLITE_TABLE);
238
239 switch (uriMatcher.match(uri)) {
240 case ALL_WORKOUTS:
241 //do nothing
242 break;
243 case SINGLE_WORKOUT:
244 String id = uri.getPathSegments().get(1);
245 queryBuilder.appendWhere(LogDb.KEY_ROWID + "=" + id);
246 break;
247 default:
248 throw new IllegalArgumentException("Unsupported URI: " + uri);
249 }
250
251 Cursor cursor = queryBuilder.query(db, projection, selection,
252 selectionArgs, null, null, sortOrder);
253 return cursor;
254
255 }
256
257 @Override
258 public int delete(Uri uri, String selection, String[] selectionArgs) {
259
260 SQLiteDatabase db = dbHelper.getWritableDatabase();
261 switch (uriMatcher.match(uri)) {
262 case ALL_WORKOUTS:
263 //do nothing
264 break;
265 case SINGLE_WORKOUT:
266 String id = uri.getPathSegments().get(1);
267 selection = LogDb.KEY_ROWID + "=" + id
268 + (!TextUtils.isEmpty(selection) ?
269 " AND (" + selection + ')' : "");
270 break;
271 default:
272 throw new IllegalArgumentException("Unsupported URI: " + uri);
273 }
274 int deleteCount = db.delete(LogDb.SQLITE_TABLE, selection, selectionArgs);
275 getContext().getContentResolver().notifyChange(uri, null);
276 return deleteCount;
277 }
278
279 @Override
280 public int update(Uri uri, ContentValues values, String selection,
281 String[] selectionArgs) {
282 SQLiteDatabase db = dbHelper.getWritableDatabase();
283 switch (uriMatcher.match(uri)) {
284 case ALL_WORKOUTS:
285 //do nothing
286 break;
287 case SINGLE_WORKOUT:
288 String id = uri.getPathSegments().get(1);
289 selection = LogDb.KEY_ROWID + "=" + id
290 + (!TextUtils.isEmpty(selection) ?
291 " AND (" + selection + ')' : "");
292 break;
293 default:
294 throw new IllegalArgumentException("Unsupported URI: " + uri);
295 }
296 int updateCount = db.update(LogDb.SQLITE_TABLE, values, selection, selectionArgs);
297 getContext().getContentResolver().notifyChange(uri, null);
298 return updateCount;
299 }
300
301}
302
303===========================================================================================================================
304
305//This is the class where items are added to the db.
306
307public class WorkoutEdit extends Activity implements View.OnClickListener {
308
309 private Spinner muscleList;
310 private Button save, delete;
311 private String mode;
312 private EditText date, name;
313 private String id;
314
315 @Override
316 public void onCreate(Bundle savedInstanceState) {
317 super.onCreate(savedInstanceState);
318 setContentView(R.layout.detail_page);
319
320 // get the values passed to the activity from the calling activity
321 // determine the mode - add, update or delete
322 if (this.getIntent().getExtras() != null){
323 Bundle bundle = this.getIntent().getExtras();
324 mode = bundle.getString("mode");
325 }
326
327 // get references to the buttons and attach listeners
328 save = (Button) findViewById(R.id.save);
329 save.setOnClickListener(this);
330 delete = (Button) findViewById(R.id.delete);
331 delete.setOnClickListener(this);
332
333 date = (EditText) findViewById(R.id.date);
334 name = (EditText) findViewById(R.id.name);
335
336
337 // create a dropdown for users to select various muscles
338 muscleList = (Spinner) findViewById(R.id.muscleList);
339 ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
340 R.array.muscle_array, android.R.layout.simple_spinner_item);
341 adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
342 muscleList.setAdapter(adapter);
343
344 // if in add mode disable the delete option
345 if(mode.trim().equalsIgnoreCase("add")){
346 delete.setEnabled(false);
347 }
348 // get the rowId for the specific workout
349 else{
350 Bundle bundle = this.getIntent().getExtras();
351 id = bundle.getString("rowId");
352 loadWorkoutInfo();
353 }
354
355 }
356
357 public void onClick(View v) {
358
359 // get values from the spinner and the input text fields
360 String myMuscle = muscleList.getSelectedItem().toString();
361 String myDate = date.getText().toString();
362 String myName = name.getText().toString();
363
364 // check for blanks
365 if(myDate.trim().equalsIgnoreCase("")){
366 Toast.makeText(getBaseContext(), "Please ENTER date", Toast.LENGTH_LONG).show();
367 return;
368 }
369
370 // check for blanks
371 if(myName.trim().equalsIgnoreCase("")){
372 Toast.makeText(getBaseContext(), "Please ENTER workout name", Toast.LENGTH_LONG).show();
373 return;
374 }
375
376
377 switch (v.getId()) {
378 case R.id.save:
379 ContentValues values = new ContentValues();
380 values.put(LogDb.KEY_DATE, myDate);
381 values.put(LogDb.KEY_WORKOUT, myName);
382 values.put(LogDb.KEY_MUSCLE, myMuscle);
383
384 // insert a record
385 if(mode.trim().equalsIgnoreCase("add")){
386 getContentResolver().insert(MyContentProvider.CONTENT_URI, values);
387 }
388 // update a record
389 else {
390 Uri uri = Uri.parse(MyContentProvider.CONTENT_URI + "/" + id);
391 getContentResolver().update(uri, values, null, null);
392 }
393 finish();
394 break;
395
396 case R.id.delete:
397 // delete a record
398 Uri uri = Uri.parse(MyContentProvider.CONTENT_URI + "/" + id);
399 getContentResolver().delete(uri, null, null);
400 finish();
401 break;
402
403 // More buttons go here (if any) ...
404
405 }
406 }
407
408 // based on the rowId get all information from the Content Provider
409 // about that workout
410 private void loadWorkoutInfo(){
411
412 String[] projection = {
413 LogDb.KEY_ROWID,
414 LogDb.KEY_DATE,
415 LogDb.KEY_WORKOUT,
416 LogDb.KEY_MUSCLE};
417 Uri uri = Uri.parse(MyContentProvider.CONTENT_URI + "/" + id);
418 Cursor cursor = getContentResolver().query(uri, projection, null, null,
419 null);
420 if (cursor != null) {
421 cursor.moveToFirst();
422 String myDate = cursor.getString(cursor.getColumnIndexOrThrow(LogDb.KEY_DATE));
423 String myWorkout = cursor.getString(cursor.getColumnIndexOrThrow(LogDb.KEY_WORKOUT));
424 String myMuscle = cursor.getString(cursor.getColumnIndexOrThrow(LogDb.KEY_MUSCLE));
425 date.setText(myDate);
426 name.setText(myWorkout);
427 muscleList.setSelection(getIndex(muscleList, myMuscle));
428 }
429
430
431 }
432
433 // this sets the spinner selection based on the value
434 private int getIndex(Spinner spinner, String myString){
435
436 int index = 0;
437
438 for (int i=0;i<spinner.getCount();i++){
439 if (spinner.getItemAtPosition(i).equals(myString)){
440 index = i;
441 }
442 }
443 return index;
444 }
445
446
447}
448
449===========================================================================================================================
450
451//This is the class which initiates the DB.
452
453public class MyDatabaseHelper extends SQLiteOpenHelper {
454
455 private static final String DATABASE_NAME = "TheBody";
456 private static final int DATABASE_VERSION = 1;
457
458 MyDatabaseHelper(Context context) {
459 super(context, DATABASE_NAME, null, DATABASE_VERSION);
460 }
461
462 @Override
463 public void onCreate(SQLiteDatabase db){
464 LogDb.onCreate(db);
465 }
466
467 @Override
468 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
469 LogDb.onUpgrade(db, oldVersion, newVersion);
470 }
471}