· 8 years ago · Jan 10, 2018, 11:02 AM
1Edit Screen Code
2package com.example.patrick.collectordatabase;
3
4import android.content.DialogInterface;
5import android.content.Intent;
6import android.support.v7.app.AlertDialog;
7import android.support.v7.app.AppCompatActivity;
8import android.os.Bundle;
9import android.util.Log;
10import android.view.View;
11
12public class HomeScreen extends AppCompatActivity {
13 CollectorDatabaseHandler dbHandler;
14 public boolean deleteConfirm ;
15 @Override
16 protected void onCreate(Bundle savedInstanceState) {
17 super.onCreate(savedInstanceState);
18 setContentView(R.layout.activity_home_screen);
19 dbHandler = new CollectorDatabaseHandler(this, null, null, 1);
20 }
21
22 public void deleteDatabase(){
23 String dMessage = "Are you sure you want to delete the database." +
24 " This means that you will have to type it all in again. Press Yes to delete.";
25 AlertDialog.Builder syAlert= new AlertDialog.Builder(this);
26 syAlert.setMessage(dMessage);
27
28 syAlert.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
29 @Override
30 public void onClick(DialogInterface dialogInterface, int i) {
31 deleteConfirm = true;
32 Log.d("USER = ", "" + String.valueOf(deleteConfirm));
33 dbHandler.deleteDatabaseContents();
34 }});
35 syAlert.setNegativeButton("No", new DialogInterface.OnClickListener(){
36 @Override
37 public void onClick(DialogInterface dialogInterface, int i) {
38
39 }});
40 syAlert.show();
41 }
42
43 //---------------------------------------------------------------------------------------
44 //Buttons to go to other screens
45 public void editButtonClicked(View view){
46 Intent intent = new Intent(HomeScreen.this, EditScreen.class);
47 finish();
48 startActivity(intent);
49 }
50 public void viewButtonClicked(View view){
51 Intent intent = new Intent(HomeScreen.this, ViewScreen.class);
52 finish();
53 startActivity(intent);
54 }
55 public void deleteDatabaseButtonClicked(View view){
56 deleteDatabase();
57 }
58
59 public void statisticsDatabaseButtonClicked(View view){
60 Intent intent = new Intent(HomeScreen.this, StatisticsView.class);
61 finish();
62 startActivity(intent);
63
64 }
65 public void searchButtonClicked(View view){
66 Intent intent = new Intent(HomeScreen.this, SearchScreen.class);
67 finish();
68 startActivity(intent);
69 }
70}
71
72Edit Screen Code
73package com.example.patrick.collectordatabase;
74
75import android.annotation.TargetApi;
76import android.content.DialogInterface;
77import android.content.Intent;
78import android.content.pm.PackageManager;
79import android.graphics.Bitmap;
80import android.os.Build;
81import android.provider.MediaStore;
82import android.support.v7.app.AlertDialog;
83import android.support.v7.app.AppCompatActivity;
84import android.os.Bundle;
85import android.view.View;
86import android.widget.EditText;
87import android.widget.ImageButton;
88import android.widget.ImageView;
89import android.widget.TextView;
90import android.widget.Toast;
91import android.util.Log;
92import java.io.File;
93import java.io.FileOutputStream;
94
95import android.os.Environment;
96
97public class EditScreen extends AppCompatActivity {
98
99 //All the text views for the edit screen that I will need to call and change
100 CollectorDatabaseHandler dbHandler;
101
102 EditText nameStore;
103 EditText idStore;
104 EditText variantStore;
105 EditText companyStore;
106 EditText yearMadeStore;
107 EditText countryStore;
108 EditText priceAvStore;
109 EditText priceBoughtStore;
110 EditText yearBoStore;
111 EditText amountStore;
112 EditText rarityStore;
113 ImageView pictureView;
114
115 Boolean deleteFileIfExist;
116 Boolean saveUserPhoto;
117 String id;
118 static final int REQUEST_IMAGE_CAPTURE = 1;
119 private static final int REQUEST_EXTERNAL_STORAGE = 1;
120 private static String[] PEMISSIONS_STORAGE = {
121 android.Manifest.permission.READ_EXTERNAL_STORAGE,
122 android.Manifest.permission.WRITE_EXTERNAL_STORAGE
123 };
124
125 @Override
126 protected void onCreate(Bundle savedInstanceState) {
127 super.onCreate(savedInstanceState);
128 setContentView(R.layout.activity_edit_screen);
129 //Database call
130 dbHandler = new CollectorDatabaseHandler(this, null, null, 1);
131 //Initialise the image button that will send the picture to the database
132 //Disable Camera function
133 //pictureView.setEnabled(hasCamera());
134 //Initialise the variables use for the text we are going to be editing
135 nameStore = (EditText) findViewById(R.id.nameStore);
136 idStore = (EditText) findViewById(R.id.idStore);
137 variantStore = (EditText) findViewById(R.id.variantStore);
138 companyStore = (EditText) findViewById(R.id.companyStore);
139 yearMadeStore = (EditText) findViewById(R.id.yearMadeStore);
140 countryStore = (EditText) findViewById(R.id.countryStore);
141 priceAvStore = (EditText) findViewById(R.id.priceAvStore);
142 priceBoughtStore = (EditText) findViewById(R.id.priceBoughtStore);
143 yearBoStore = (EditText) findViewById(R.id.yearBoStore);
144 amountStore = (EditText) findViewById(R.id.amountStore);
145 rarityStore = (EditText) findViewById(R.id.rarityStore);
146
147 pictureView = (ImageView)findViewById(R.id.pictureView);
148 if (shouldAskPermissions()) {
149 askPermissions();
150 }
151 }
152 //-----------------------------------------
153 //Checks input
154 //Check inputs enter to make sure they are correctly inputed.
155 public boolean checkInput() {
156 return textBoxMatchesRegex(nameStore, null) && textBoxMatchesRegex(idStore, "[0-9]+") &&
157 textBoxMatchesRegex(variantStore, null) && textBoxMatchesRegex(companyStore, null) &&
158 textBoxMatchesRegex(yearMadeStore, "[0-9]+") && textBoxMatchesRegex(countryStore, null) &&
159 textBoxMatchesRegex(priceAvStore, "[0-9.]+") && textBoxMatchesRegex(priceBoughtStore, "[0-9.]+") &&
160 textBoxMatchesRegex(yearBoStore, "[0-9.]+") && textBoxMatchesRegex(amountStore, "[0-9]+") &&
161 textBoxMatchesRegex(rarityStore, "[0-9]+");
162 }
163 // If regex is null, just ensure the textView isn't empty...
164 public boolean textBoxMatchesRegex(TextView textView, String regex) {
165 String userInput = textView.getText().toString();
166 if (userInput == null) {
167 return false;
168 }
169 if (regex == null) {
170 // If the regex is null, just make sure the string contains something...
171 return !userInput.isEmpty();
172 }
173 return userInput.matches(regex);
174 }
175 //----------------------------------------------------------------------------------------------
176 //Setters
177 public CollectorItem createCollectorItemFromInput() {
178 //Variables setter to go into the database
179 CollectorItem collectorItem = new CollectorItem();
180 collectorItem.id = idStore.getText().toString() + "." + variantStore.getText().toString();
181 collectorItem.name = nameStore.getText().toString();
182 collectorItem.company = companyStore.getText().toString();
183 collectorItem.yearMade = Integer.valueOf(yearMadeStore.getText().toString());
184 collectorItem.countryMade = countryStore.getText().toString();
185 collectorItem.priceAverage = Float.valueOf(priceAvStore.getText().toString());
186 collectorItem.priceBought = Float.valueOf(priceBoughtStore.getText().toString());
187 collectorItem.yearBought = Integer.valueOf(yearBoStore.getText().toString());
188 collectorItem.amountGot = Integer.valueOf(amountStore.getText().toString());
189 collectorItem.rarity = Integer.valueOf(rarityStore.getText().toString());
190 return collectorItem;
191 }
192
193 //----------------------------------------------------------------------------------------------
194 //Clears the text boxes ready for next input
195 public void clearBoxes() {
196 idStore.setText("");
197 variantStore.setText("");
198 nameStore.setText("");
199 companyStore.setText("");
200 yearMadeStore.setText("");
201 countryStore.setText("");
202 priceAvStore.setText("");
203 priceBoughtStore.setText("");
204 yearBoStore.setText("");
205 amountStore.setText("");
206 rarityStore.setText("");
207 }
208 //-------------------------------------------------------------------------------
209 //All functions that require a different screen
210 public void homeButtonClicked(View view) {
211 Intent intent = new Intent(EditScreen.this, HomeScreen.class);
212 finish();
213 startActivity(intent);
214 }
215
216 public void viewDatabaseButtonClicked(View view) {
217 Intent intent = new Intent(EditScreen.this, ViewScreen.class);
218 finish();
219 startActivity(intent);
220 }
221
222 public void statisticsDatabaseButtonClicked(View view) {
223 Intent intent = new Intent(EditScreen.this, StatisticsView.class);
224 finish();
225 startActivity(intent);
226 }
227 //------------------------------------------------------------------------
228 // Functions that will require pop up menu
229 protected void displayMessageFailed(String dMessage) {
230 AlertDialog.Builder syAlert = new AlertDialog.Builder(this);
231 syAlert.setMessage(dMessage);
232 syAlert.setPositiveButton("Okay", new DialogInterface.OnClickListener() {
233 @Override
234 public void onClick(DialogInterface dialogInterface, int i) {
235 }
236 });
237 syAlert.show();
238 }
239
240 public void showToastSuccessful(String dMessage) {
241 Toast.makeText(this, dMessage, Toast.LENGTH_LONG).show();
242 }
243 //------------------------------------------------------------------------
244 //Camera Code
245 /*Required to get the permission to use the camera and save the file in the location that
246 I want it to be saved in
247 */
248 protected boolean shouldAskPermissions() {
249 return (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1);
250 }
251
252 @TargetApi(23)
253 protected void askPermissions() {
254 String[] permissions = {
255 "android.permission.READ_EXTERNAL_STORAGE",
256 "android.permission.WRITE_EXTERNAL_STORAGE"
257 };
258 int requestCode = 200;
259 requestPermissions(permissions, requestCode);
260 }
261
262 //Check if the user has a camera
263 private boolean hasCamera() {
264 return getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);
265 }
266
267 //Launching the camera
268 public void takePhoto() {
269 if (hasCamera()) {
270 id = idStore.getText().toString() + variantStore.getText().toString();
271 Log.d("IDSET? ", "" + id);
272 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
273 startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
274 Log.d("ENDCAMERA", ":)");
275 } else {
276 displayMessageFailed("Can not find a camera on the device.");
277 }
278 }
279
280 //Return the image taken
281 @Override
282 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
283 if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
284 //Image data
285 Bundle extras = data.getExtras();
286 Bitmap photo = (Bitmap) extras.get("data");
287 displayPhotoMessage("Is the photo you have taken the Id and Variant you have typed into the textbook. If this isn't right press no so the image doesn't save",photo);
288 Log.d("Save image", String.valueOf(saveUserPhoto));
289 }
290 }
291
292 protected void displayPhotoMessage(String displayMessage, final Bitmap photo){
293 saveUserPhoto =false;
294 AlertDialog.Builder syAlert= new AlertDialog.Builder(this);
295 syAlert.setMessage(displayMessage);
296 syAlert.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
297 @Override
298 public void onClick(DialogInterface dialogInterface, int i) {
299 saveUserPhoto = true;
300 Bitmap userPhoto = photo;
301 saveUserImageCall(userPhoto);
302 }});
303 syAlert.setNegativeButton("No", new DialogInterface.OnClickListener(){
304 @Override
305 public void onClick(DialogInterface dialogInterface, int i) {
306 saveUserPhoto = false;
307 Bitmap userPhoto = photo;
308 saveUserImageCall(userPhoto);
309 }});
310 syAlert.show();
311 }
312
313 public void saveUserImageCall(Bitmap photo){
314 if(saveUserPhoto){
315 saveImage(photo, id);
316 if (photo != null) {
317 pictureView.setImageBitmap(photo);
318 }
319 }else{
320 displayMessageFailed("Image not taken on user request");
321 }
322 }
323
324 private String getImageFilenameWith(String identifier) {
325 return "Image-" + identifier + ".jpg";
326 }
327
328 //Get thr file directory of the image
329 private File getFileWith(String identifier) {
330 String rootDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
331 File myDir = new File(rootDir + "/CollectorDatabase");
332 myDir.mkdirs();
333
334 String filename = getImageFilenameWith(identifier);
335 File file = new File(rootDir, filename);
336
337 if (file.exists()) {
338 displayDeleteQuestionMessage("A picture already exist, do you want to delete and replace it?", file);
339 }
340 return file;
341 }
342
343 protected void displayDeleteQuestionMessage(String displayMessage, final File file){
344 AlertDialog.Builder syAlert= new AlertDialog.Builder(this);
345 syAlert.setMessage(displayMessage);
346 syAlert.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
347 @Override
348 public void onClick(DialogInterface dialogInterface, int i) {
349 deleteFileIfExist = true;
350 returnFileIf(file);
351 }});
352 syAlert.setNegativeButton("No", new DialogInterface.OnClickListener(){
353 @Override
354 public void onClick(DialogInterface dialogInterface, int i) {
355 deleteFileIfExist = false;
356 returnFileIf(file);
357 }});
358 syAlert.show();
359 }
360
361 private File returnFileIf(File file) {
362 if (deleteFileIfExist) {
363 file.delete();
364 return file;
365 } else {
366 displayMessageFailed("Image cannot be saved as the file location and name is in used by an image");
367 }
368 return file;
369 }
370
371 //Saving the image to the phone and or SD card (SD card is preferred)
372 private void saveImage(Bitmap image, String identifier) {
373 File imageFile = getFileWith(identifier);
374 try {
375 FileOutputStream outputStream = new FileOutputStream(imageFile);
376 image.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
377 outputStream.flush();
378 outputStream.close();
379 } catch (Exception exception) {
380 }
381 }
382 //-----------------------------------------------------------------------
383 //Add information from the text boxes to the database
384
385 protected void addPhoto(){
386 AlertDialog.Builder syAlert= new AlertDialog.Builder(this);
387 syAlert.setMessage("Want to take a photo of the item you are adding to the database?");
388 syAlert.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
389 @Override
390 public void onClick(DialogInterface dialogInterface, int i) {
391 takePhoto();
392 showToastSuccessful("Successfully added");
393 clearBoxes();
394 }});
395 syAlert.setNegativeButton("No", new DialogInterface.OnClickListener(){
396 @Override
397 public void onClick(DialogInterface dialogInterface, int i) {
398 showToastSuccessful("Successfully added");
399 clearBoxes();
400 }});
401 syAlert.show();
402 }
403
404 public void addButtonClicked (View view) {
405 Boolean inputTrue = checkInput();
406 if (inputTrue) {
407 Log.d ("INPUT TRUE","");
408
409 Boolean check = dbHandler.add(createCollectorItemFromInput());
410 Log.d("CHECK4", "FAILED =" + String.valueOf(check));
411 if (!check) {
412 addPhoto();
413
414 } else {
415 String dmessage = "There is already a item in the database with the id and " +
416 "variant typed in. Please check to make sure you haven't mistyped";
417 displayMessageFailed(dmessage);
418 }
419 }else {
420 Log.d ("INPUT FALSE","");
421 String dmessage = "You have not type in a valid input in at least one of the fields";
422 displayMessageFailed(dmessage);
423 }
424 }
425
426 //Delete the information related to the database
427 public void deleteButtonClicked(View view){
428 Boolean check = dbHandler.delete(createCollectorItemFromInput());
429 if (check == true) {
430 showToastSuccessful("Successfully Deleted");
431 clearBoxes();
432 } else {
433 String dmessage = "The item you want to delete can't be found";
434 displayMessageFailed(dmessage);
435 }
436 }
437
438
439}
440
441View Screen
442package com.example.patrick.collectordatabase;
443
444import android.annotation.TargetApi;
445import android.content.DialogInterface;
446import android.content.Intent;
447import android.content.pm.PackageManager;
448import android.graphics.Bitmap;
449import android.graphics.BitmapFactory;
450import android.graphics.Color;
451import android.os.Build;
452import android.os.Environment;
453import android.provider.MediaStore;
454import android.support.v4.view.GestureDetectorCompat;
455import android.os.Bundle;
456import android.support.v7.app.AlertDialog;
457import android.support.v7.app.AppCompatActivity;
458import android.util.Log;
459import android.view.GestureDetector;
460import android.view.MotionEvent;
461import android.widget.Button;
462import android.widget.ImageButton;
463import android.widget.ImageView;
464import android.widget.TextView;
465import android.view.View;
466import android.widget.Toast;
467
468import java.io.File;
469import java.io.FileOutputStream;
470
471public class ViewScreen extends AppCompatActivity {
472 private GestureDetectorCompat gestureObject;
473 private int current = 0;
474
475 CollectorDatabaseHandler dbHandler;
476 GlobalVariables globalVariables = GlobalVariables.getInstance();
477
478 TextView idStore;
479 TextView variantStore;
480 TextView nameStore;
481 TextView companyStore;
482 TextView yearMadeStore;
483 TextView countryStore;
484 TextView priceAvStore;
485 TextView priceBoughtStore;
486 TextView yearBoStore;
487 TextView amountStore;
488 TextView rarityStore;
489 ImageButton pictureView;
490 Button editorButton;
491 CollectorItem item;
492
493 Boolean editor = false;
494
495 Boolean deleteFileIfExist;
496 Boolean saveUserPhoto;
497 String id;
498 static final int REQUEST_IMAGE_CAPTURE = 1;
499 private static final int REQUEST_EXTERNAL_STORAGE = 1;
500 private static String[] PEMISSIONS_STORAGE = {
501 android.Manifest.permission.READ_EXTERNAL_STORAGE,
502 android.Manifest.permission.WRITE_EXTERNAL_STORAGE
503 };
504
505 @Override
506 protected void onCreate(Bundle savedInstanceState) {
507 super.onCreate(savedInstanceState);
508 setContentView(R.layout.activity_view_screen);
509
510 //setEnableView();
511
512 gestureObject = new GestureDetectorCompat(this, new Gesture());
513 dbHandler = new CollectorDatabaseHandler(this, null, null, 1);
514
515 //Initialise the image button that will send the picture to the database
516 pictureView = (ImageButton) findViewById(R.id.pictureView);
517 //Disable Camera function
518 pictureView.setEnabled(hasCamera());
519 //Initialise the variables use for the text
520
521 idStore = (TextView) findViewById(R.id.idStore);
522 variantStore = (TextView) findViewById(R.id.variantStore);
523 nameStore = (TextView) findViewById(R.id.nameStore);
524 companyStore = (TextView) findViewById(R.id.companyStore);
525 yearMadeStore = (TextView) findViewById(R.id.yearMadeStore);
526 countryStore = (TextView) findViewById(R.id.countryStore);
527 priceAvStore = (TextView) findViewById(R.id.priceAvStore);
528 priceBoughtStore = (TextView) findViewById(R.id.priceBoughtStore);
529 yearBoStore = (TextView) findViewById(R.id.yearBoStore);
530 amountStore = (TextView) findViewById(R.id.amountStore);
531 rarityStore = (TextView) findViewById(R.id.rarityStore);
532
533 editorButton = (Button) findViewById(R.id.editorButton);
534 current = 0;
535 if (shouldAskPermissions()) {
536 askPermissions();
537 }
538
539
540 //Make sure the database isn't empty
541 int count = dbHandler.getCount();
542
543 if (count > 0) {
544 if (globalVariables.searchItemIndex != -1){
545 current = globalVariables.searchItemIndex;
546 globalVariables.searchItemIndex = -1;
547 }
548 setEditVariablesFrom(dbHandler.getCurrentRow(current));
549 } else {
550 displayDialogInterface("Cannot find the database. Make sure you have got a least one field in the database. All fields will remain empty until they is at least an item in the database. ");
551 }
552
553 }
554
555
556 ///Camera Code
557 /*Required to get the permission to use the camera and save the file in the location that
558 I want it to be saved in
559 */
560 protected boolean shouldAskPermissions() {
561 return (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1);
562 }
563
564 @TargetApi(23)
565 protected void askPermissions() {
566 String[] permissions = {
567 "android.permission.READ_EXTERNAL_STORAGE",
568 "android.permission.WRITE_EXTERNAL_STORAGE"
569 };
570 int requestCode = 200;
571 requestPermissions(permissions, requestCode);
572 }
573
574 //Check if the user has a camera
575 private boolean hasCamera() {
576 return getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);
577 }
578
579 // Functions that will require pop up menu
580 protected void displayMessageFailed(String dMessage) {
581 AlertDialog.Builder syAlert = new AlertDialog.Builder(this);
582 syAlert.setMessage(dMessage);
583 syAlert.setPositiveButton("Okay", new DialogInterface.OnClickListener() {
584 @Override
585 public void onClick(DialogInterface dialogInterface, int i) {
586 }
587 });
588 syAlert.show();
589 }
590
591 public void pictureButtonClicked(View view){
592 takePhoto();
593 }
594 //Launching the camera
595 public void takePhoto() {
596 if (hasCamera()) {
597 id = idStore.getText().toString() + variantStore.getText().toString();
598 Log.d("IDSET? ", "" + id);
599 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
600 startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
601 Log.d("ENDCAMERA", ":)");
602 } else {
603 displayMessageFailed("Can not find a camera on the device.");
604 }
605 }
606
607 //Return the image taken
608 @Override
609 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
610 if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
611 //Image data
612 Bundle extras = data.getExtras();
613 Bitmap photo = (Bitmap) extras.get("data");
614 displayPhotoMessage("Is the photo you have taken the Id and Variant you have typed into the textbook. If this isn't right press no so the image doesn't save",photo);
615 }
616 }
617
618 protected void displayPhotoMessage(String displayMessage, final Bitmap photo){
619 saveUserPhoto =false;
620 AlertDialog.Builder syAlert= new AlertDialog.Builder(this);
621 syAlert.setMessage(displayMessage);
622 syAlert.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
623 @Override
624 public void onClick(DialogInterface dialogInterface, int i) {
625 saveUserPhoto = true;
626 Bitmap userPhoto = photo;
627 saveUserImageCall(userPhoto);
628 }});
629 syAlert.setNegativeButton("No", new DialogInterface.OnClickListener(){
630 @Override
631 public void onClick(DialogInterface dialogInterface, int i) {
632 saveUserPhoto = false;
633 Bitmap userPhoto = photo;
634 saveUserImageCall(userPhoto);
635 }});
636 syAlert.show();
637 }
638
639 public void saveUserImageCall(Bitmap photo){
640 if(saveUserPhoto){
641 saveImage(photo, id);
642 if (photo != null) {
643 pictureView.setImageBitmap(photo);
644 }
645 }else{
646 displayMessageFailed("Image not taken on user request");
647 }
648 }
649
650 private String getImageFilenameWith(String identifier) {
651 return "Image-" + identifier + ".jpg";
652 }
653
654 //Get thr file directory of the image
655 private File getFileWith(String identifier) {
656 String rootDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
657 File myDir = new File(rootDir + "/CollectorDatabase");
658 myDir.mkdirs();
659
660 String filename = getImageFilenameWith(identifier);
661 File file = new File(rootDir, filename);
662 if (file.exists()) {
663 displayDeleteQuestionMessage("A picture already exist, do you want to delete and replace it?", file);
664 }
665 return file;
666 }
667
668 protected void displayDeleteQuestionMessage(String displayMessage, final File file){
669 AlertDialog.Builder syAlert= new AlertDialog.Builder(this);
670 syAlert.setMessage(displayMessage);
671 syAlert.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
672 @Override
673 public void onClick(DialogInterface dialogInterface, int i) {
674 deleteFileIfExist = true;
675 returnFileIf(file);
676 }});
677 syAlert.setNegativeButton("No", new DialogInterface.OnClickListener(){
678 @Override
679 public void onClick(DialogInterface dialogInterface, int i) {
680 deleteFileIfExist = false;
681 returnFileIf(file);
682 }});
683 syAlert.show();
684 }
685
686 private File returnFileIf(File file) {
687 if (deleteFileIfExist) {
688 file.delete();
689 return file;
690 } else {
691 displayMessageFailed("Image cannot be saved as the file location and name is in used by an image");
692 }
693 return file;
694 }
695
696 //Saving the image to the phone and or SD card (SD card is preferred)
697 private void saveImage(Bitmap image, String identifier) {
698 File imageFile = getFileWith(identifier);
699 try {
700 FileOutputStream outputStream = new FileOutputStream(imageFile);
701 image.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
702 outputStream.flush();
703 outputStream.close();
704 } catch (Exception exception) {
705 Log.d("FILE SAVING", "Exception handled 'ere");
706 }
707 }
708
709 //Calling a saved image
710 private File getSaveFileWith(String saveIdentifer){
711 String rootDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
712 File myDir = new File(rootDir + "/CollectorDatabase");
713 myDir.mkdirs();
714
715 String filename = getSavedImageFilenameWith(saveIdentifer);
716 File savefile = new File(rootDir, filename);
717
718 return savefile;
719 }
720
721 private String getSavedImageFilenameWith(String identifier) {
722 return "Image-" + identifier + ".jpg";
723 }
724
725 //Get Image
726 public void getSavedImage(String id){
727 File file = getSaveFileWith(id);
728 Bitmap savedImage = BitmapFactory.decodeFile(file.getAbsolutePath());
729 if (savedImage != null) {
730 pictureView.setImageBitmap(Bitmap.createScaledBitmap(savedImage, 400, 400, false));
731 } else {
732 pictureView.setImageDrawable(null);
733 pictureView.setBackgroundColor(Color.rgb(255,255,255));
734 }
735 }
736
737 //EDIT CODE
738 //Edit any field by the id/variant
739 public boolean checkInput() {
740 return textBoxMatchesRegex(nameStore, null) && textBoxMatchesRegex(idStore, "[0-9]+") &&
741 textBoxMatchesRegex(variantStore, null) && textBoxMatchesRegex(companyStore, null) &&
742 textBoxMatchesRegex(yearMadeStore, "[0-9]+") && textBoxMatchesRegex(countryStore, null) &&
743 textBoxMatchesRegex(priceAvStore, "[0-9.]+") && textBoxMatchesRegex(priceBoughtStore, "[0-9.]+") &&
744 textBoxMatchesRegex(yearBoStore, "[0-9.]+") && textBoxMatchesRegex(amountStore, "[0-9]+") &&
745 textBoxMatchesRegex(rarityStore, "[0-9]+");
746 }
747 // If regex is null, just ensure the textView isn't empty...
748 public boolean textBoxMatchesRegex(TextView textView, String regex) {
749 String userInput = textView.getText().toString();
750 if (userInput == null) {
751 return false;
752 }
753 if (regex == null) {
754 // If the regex is null, just make sure the string contains something...
755 return !userInput.isEmpty();
756 }
757 return userInput.matches(regex);
758 }
759
760 //Control if the textboxes are enable or disable
761 public void editorButtonClicked(View view){
762 if (editor == false){
763 editor = true;
764 setEnableView();
765 editorButton.setText("Editor(On)");
766 } else {
767 editor = false;
768 setEnableView();
769 editorButton.setText("Editor(Off)");
770 setEditVariablesFrom(dbHandler.getCurrentRow(current));
771 }
772 }
773
774 //Enable/Disable textboxes so they can't be edited by mistakes
775 public void setEnableView(){
776 idStore.setEnabled(editor);
777 variantStore.setEnabled(editor);
778 nameStore.setEnabled(editor);
779 companyStore.setEnabled(editor);
780 yearMadeStore.setEnabled(editor);
781 countryStore.setEnabled(editor);
782 priceAvStore.setEnabled(editor);
783 priceBoughtStore.setEnabled(editor);
784 yearBoStore.setEnabled(editor);
785 amountStore.setEnabled(editor);
786 rarityStore.setEnabled(editor);
787 }
788 public void editButtonClicked(View view){
789 if (editor == true) {
790 Boolean validInput = checkInput();
791
792 if (validInput) {
793 Boolean check = dbHandler.edit(createCollectorItemFromInput());
794 if (check == true) {
795 showToastSuccessful("Successfully edited.");
796 } else {
797 displayMessageFailed("Can't find item in the database with the id and variant you entered. Please check to make sure it is typed in correctly?");
798 }
799 } else {
800 displayMessageFailed("You have not type in a vaild input in one of the fields");
801 }
802 } else {
803
804 displayMessageFailed("Please press the Editor button to edit an item in the database.");
805 }
806 }
807
808 public CollectorItem createCollectorItemFromInput() {
809 //Variables setter to go into the database
810 CollectorItem collectorItem = new CollectorItem();
811 collectorItem.id = idStore.getText().toString() + "." + variantStore.getText().toString();
812 collectorItem.name = nameStore.getText().toString();
813 collectorItem.company = companyStore.getText().toString();
814 collectorItem.yearMade = Integer.valueOf(yearMadeStore.getText().toString());
815 collectorItem.countryMade = countryStore.getText().toString();
816 collectorItem.priceAverage = Float.valueOf(priceAvStore.getText().toString());
817 collectorItem.priceBought = Float.valueOf(priceBoughtStore.getText().toString());
818 collectorItem.yearBought = Integer.valueOf(yearBoStore.getText().toString());
819 collectorItem.amountGot = Integer.valueOf(amountStore.getText().toString());
820 collectorItem.rarity = Integer.valueOf(rarityStore.getText().toString());
821 return collectorItem;
822 }
823
824 public void showToastSuccessful(String dMessage) {
825 Toast.makeText(this, dMessage, Toast.LENGTH_LONG).show();
826 }
827 //------------------------------------------------------------------------------------------------------------------------------
828 public void setEditVariablesFrom(CollectorItem item) {
829 String [] id = item.id.split("\\.");
830 idStore.setText(id[0]);
831 variantStore.setText(id[1]);
832 String imageId = (idStore.getText().toString()+variantStore.getText().toString()).replace(" ", "");
833 getSavedImage(imageId);
834 nameStore.setText(item.name);
835 companyStore.setText(item.company);
836 yearMadeStore.setText(String.valueOf(item.yearMade));
837 countryStore.setText(item.countryMade);
838
839 String formatPriceAv = String.format("%.02f",item.priceAverage);
840 String formatPriceBought = String.format("%.02f",item.priceBought);
841 priceAvStore.setText(formatPriceAv);
842 priceBoughtStore.setText(formatPriceBought);
843
844 yearBoStore.setText(String.valueOf(item.yearBought));
845 amountStore.setText(String.valueOf(item.amountGot));
846 rarityStore.setText(String.valueOf(item.rarity));
847 }
848
849 //----------------------------
850 public void statisticsDatabaseButtonClicked (View view){
851 Intent intent = new Intent(ViewScreen.this,StatisticsView.class);
852 finish();
853 startActivity(intent);
854 }
855
856 public void editDatabaseClicked(View view){
857 Intent intent = new Intent(ViewScreen.this,EditScreen.class);
858 finish();
859 startActivity(intent);
860
861 }
862 public void homeButtonClicked(View view){
863 Intent intent = new Intent(ViewScreen.this,HomeScreen.class);
864 finish();
865 startActivity(intent);
866
867 }
868//----------------------------------
869 //SWIPE FUNCTION
870 public boolean onTouchEvent(MotionEvent event){
871 this.gestureObject.onTouchEvent(event);
872 return super.onTouchEvent(event);
873 }
874 protected void displayDialogInterface(String dMessage){
875 AlertDialog.Builder syAlert= new AlertDialog.Builder(this);
876 syAlert.setMessage(dMessage);
877 syAlert.setPositiveButton("Okay", new DialogInterface.OnClickListener(){
878 @Override
879 public void onClick(DialogInterface dialogInterface, int i) {
880 }});
881 syAlert.show();
882 }
883
884 //create the gesture object class
885 class Gesture extends GestureDetector.SimpleOnGestureListener {
886 //Right to left Swipes
887 public void onBackwardSwipe() {
888 if (current == 0) {
889 displayDialogInterface("You are at the start of the database");
890 return;
891 }
892 current -= 1;
893 setEditVariablesFrom(dbHandler.getCurrentRow(current));
894 }
895
896 //Left to Right Swipes
897 public void onForwardSwipe() {
898 int databaseEndIndex = dbHandler.getCount() - 1;
899 if (current == databaseEndIndex) {
900 displayDialogInterface("You have got to the end of the database");
901 return;
902 }
903 current += 1;
904 setEditVariablesFrom(dbHandler.getCurrentRow(current));
905 }
906
907 @Override
908 //Detects the swipe being done
909 public boolean onFling(MotionEvent event1, MotionEvent event2, float velocityX, float velocityY) {
910 if (velocityX >= 0) {
911 onBackwardSwipe();
912 } else {
913 onForwardSwipe();
914 }
915 return true;
916 }
917 }
918
919
920}
921Statistics page
922package com.example.patrick.collectordatabase;
923
924import android.content.DialogInterface;
925import android.content.Intent;
926import android.support.v7.app.AlertDialog;
927import android.support.v7.app.AppCompatActivity;
928import android.os.Bundle;
929import android.util.Log;
930import android.view.View;
931import android.widget.TextView;
932
933public class StatisticsView extends AppCompatActivity {
934 CollectorDatabaseHandler dbHandler;
935
936 TextView totalNumberStore;
937 TextView totalPricePaidStore;
938 TextView totalWorthStore;
939 TextView highestValueStore;
940
941 @Override
942 protected void onCreate(Bundle savedInstanceState) {
943 super.onCreate(savedInstanceState);
944 setContentView(R.layout.activity_statistics_view);
945 dbHandler = new CollectorDatabaseHandler(this, null, null, 1);
946
947 totalNumberStore = (TextView)findViewById(R.id.totalNumberStore);
948 totalPricePaidStore = (TextView)findViewById(R.id.totalPricePaidStore);
949 totalWorthStore = (TextView)findViewById(R.id.totalWorthStore);
950 highestValueStore=(TextView)findViewById(R.id.highestValueStore);
951
952 int count = dbHandler.getCount();
953 if (count > 0){
954
955 displayResults();
956 }else{
957 String dMessage = "Cannot find the database. Make sure you have got a least one field in the database. All fields will remain empty until they is at least an item in the database. ";
958 loadError(dMessage);
959 }
960 }
961 //Display search results
962 public void displayResults(){
963
964 float totalPricePaid = dbHandler.totalCostPaid();
965 float avPriceTotal = dbHandler.worth();
966 String highestValue = dbHandler.findHighestValue();
967 int total = dbHandler.getTotalCount();
968
969 totalNumberStore.setText(String.valueOf(total));
970 highestValueStore.setText(highestValue);
971
972 String formatTotalPricePaid= String.format("%.02f",totalPricePaid);
973 String formatAvPriceTotal= String.format("%.02f",avPriceTotal);
974 totalPricePaidStore.setText("£"+formatTotalPricePaid);
975 totalWorthStore.setText("£"+formatAvPriceTotal);
976 }
977 //Message if there isn't a database with at least one entry
978 protected void loadError(String dMessage){
979 AlertDialog.Builder syAlert= new AlertDialog.Builder(this);
980 syAlert.setMessage(dMessage);
981 syAlert.setPositiveButton("Okay", new DialogInterface.OnClickListener(){
982 @Override
983 public void onClick(DialogInterface dialogInterface, int i) {
984 }});
985 syAlert.show();
986 }
987
988 public void homeButtonClicked(View view){
989 Intent intent = new Intent(StatisticsView.this, HomeScreen.class);
990 finish();
991 startActivity(intent);
992 }
993 public void viewDatabaseButtonClicked(View view){
994 Intent intent = new Intent(StatisticsView.this, ViewScreen.class);
995 finish();
996 startActivity(intent);
997 }
998
999 public void editDatabaseButtonClicked(View view){
1000 Intent intent = new Intent(StatisticsView.this, EditScreen.class);
1001 finish();
1002 startActivity(intent);
1003 }
1004}
1005
1006Search Screen
1007package com.example.patrick.collectordatabase;
1008
1009import android.content.DialogInterface;
1010import android.content.Intent;
1011import android.provider.Settings;
1012import android.support.v7.app.AlertDialog;
1013import android.support.v7.app.AppCompatActivity;
1014import android.os.Bundle;
1015import android.util.Log;
1016import android.view.View;
1017import android.widget.EditText;
1018
1019public class SearchScreen extends AppCompatActivity {
1020
1021 CollectorItem collectorItem;
1022 CollectorDatabaseHandler dbHandler;
1023 GlobalVariables globalVariables = GlobalVariables.getInstance();
1024
1025 EditText idSearchStore;
1026 EditText variantSearchStore;
1027
1028 @Override
1029 protected void onCreate(Bundle savedInstanceState) {
1030 super.onCreate(savedInstanceState);
1031 setContentView(R.layout.activity_search_screen);
1032 dbHandler = new CollectorDatabaseHandler(this, null, null, 1);
1033 idSearchStore = (EditText) findViewById(R.id.idSearchStore);
1034 variantSearchStore = (EditText) findViewById(R.id.variantSearchStore);
1035 }
1036
1037 public void homeButtonClicked(View view){
1038 Intent intent = new Intent(SearchScreen.this, HomeScreen.class);
1039 finish();
1040 startActivity(intent);
1041 }
1042 public void viewDatabaseButtonClicked(View view){
1043 Intent intent = new Intent(SearchScreen.this,ViewScreen.class);
1044 finish();
1045 startActivity(intent);
1046 }
1047
1048 public void editDatabaseButtonClicked(View view){
1049 Intent intent = new Intent(SearchScreen.this, EditScreen.class);
1050 finish();
1051 startActivity(intent);
1052 }
1053
1054 //Search Function
1055 public void searchButtonClicked(View view){
1056 String id = idSearchStore.getText().toString() + "." + variantSearchStore.getText().toString();
1057 int searchForId = dbHandler.checkInDatabaseSearch(id);
1058 if (searchForId == -1){
1059 //If the program can't finds the id the user is looking for
1060 String dmessage = "Can't find the Id you are looking for.";
1061 displayMessageFailed(dmessage);
1062 }else{
1063 //If the program finds the id the user is looking for
1064 globalVariables.searchItemIndex = searchForId;
1065
1066 Intent intent = new Intent(SearchScreen.this,ViewScreen.class);
1067 finish();
1068 startActivity(intent);
1069 }
1070 }
1071 protected void displayMessageFailed(String dMessage) {
1072 AlertDialog.Builder syAlert = new AlertDialog.Builder(this);
1073 syAlert.setMessage(dMessage);
1074 syAlert.setPositiveButton("Okay", new DialogInterface.OnClickListener() {
1075 @Override
1076 public void onClick(DialogInterface dialogInterface, int i) {
1077 }
1078 });
1079 syAlert.show();
1080 }
1081}
1082
1083CollectorDatabaseHandler Code
1084package com.example.patrick.collectordatabase;
1085
1086import android.database.sqlite.SQLiteDatabase;
1087import android.database.sqlite.SQLiteOpenHelper;
1088import android.database.Cursor;
1089import android.content.Context;
1090import android.content.ContentValues;
1091import android.util.Log;
1092
1093
1094public class CollectorDatabaseHandler extends SQLiteOpenHelper{
1095 CollectorItem COLLECTORITEM;
1096 HomeScreen homeScreen;
1097
1098 private static final int DATABASE_VERSION = 6;
1099
1100 private static final String DATABASE_NAME = "collectorDB.db";
1101 private static final String TABLE_COLLECTOR = "collector";
1102
1103
1104 private static final String COLUMN_ID = "_id";
1105 private static final String COLUMN_NAME = "_name";
1106 private static final String COLUMN_COMPANY = "_company";
1107 private static final String COLUMN_YEARMADE = "_yearMade";
1108 private static final String COLUMN_COUNTRY = "_countryMade";
1109 private static final String COLUMN_AVPRICE = "_priceAverage";
1110 private static final String COLUMN_YEARBOUGHT = "_yearBought";
1111 private static final String COLUMN_PRICEBOUGHT = "_priceBought";
1112 private static final String COLUMN_AMOUNTGOT = "_amountGot";
1113 private static final String COLUMN_RARITY= "_rarity";
1114 public String first = "";
1115
1116
1117 public CollectorDatabaseHandler (Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
1118 super(context, DATABASE_NAME, factory, DATABASE_VERSION);
1119 }
1120
1121 @Override
1122 public void onCreate(SQLiteDatabase db) {
1123 String query = "CREATE TABLE " + TABLE_COLLECTOR + "(" +
1124 COLUMN_ID + " STRING PRIMARY KEY, " +
1125 COLUMN_NAME + " TEXT, " +
1126 COLUMN_COMPANY + " TEXT, " +
1127 COLUMN_YEARMADE + " INTEGER, " +
1128 COLUMN_COUNTRY + " TEXT, " +
1129 COLUMN_AVPRICE + " FLOAT, " +
1130 COLUMN_YEARBOUGHT + " INTEGER, " +
1131 COLUMN_PRICEBOUGHT + " FLOAT, " +
1132 COLUMN_AMOUNTGOT + " INTEGER, " +
1133 COLUMN_RARITY + " INTEGER " +
1134 ");";
1135 db.execSQL(query);
1136 }
1137
1138 @Override
1139 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
1140 }
1141 //----------------------------------------------------------------------------------
1142
1143 public void deleteDatabase(SQLiteDatabase db, int oldVersion, int newVersion) {
1144 db.execSQL("DROP TABLE IF EXISTS " + TABLE_COLLECTOR);
1145 onCreate(db);
1146 }
1147
1148 public void deleteDatabaseContents() {
1149 deleteDatabase(getWritableDatabase(), 6, 7);
1150 }
1151
1152 //----------------------------------------------------------------------------------------
1153 public Boolean add(CollectorItem item){
1154 COLLECTORITEM = item;
1155 //Check ID and Variant is not in database
1156 Boolean check = checkInDatabase(item);
1157 if (!check) {;
1158 // Put data from input into database
1159 ContentValues values = new ContentValues();
1160 values.put(COLUMN_ID, item.id);
1161 values.put(COLUMN_NAME, item.name);
1162 values.put(COLUMN_COMPANY, item.company);
1163 values.put(COLUMN_YEARMADE, item.yearMade);
1164 values.put(COLUMN_COUNTRY, item.countryMade);
1165 values.put(COLUMN_AVPRICE, item.priceAverage);
1166 values.put(COLUMN_YEARBOUGHT, item.yearBought);
1167 values.put(COLUMN_PRICEBOUGHT, item.priceBought);
1168 values.put(COLUMN_AMOUNTGOT, item.amountGot);
1169 values.put(COLUMN_RARITY, item.rarity);
1170 SQLiteDatabase db = getWritableDatabase();
1171 db.insert(TABLE_COLLECTOR, null, values);
1172 db.close();
1173 }
1174 return check;
1175 }
1176
1177 public Boolean delete(CollectorItem item){
1178 //Check ID and Variant is in database
1179 COLLECTORITEM = item;
1180 //Check ID and Variant is not in database
1181 Boolean check = checkInDatabase(item);
1182
1183 if (check) {
1184 SQLiteDatabase db = getWritableDatabase();
1185 db.execSQL("DELETE FROM " + TABLE_COLLECTOR + " WHERE " + COLUMN_ID + "=\"" + item.id + "\";");
1186 db.close();
1187 }
1188 return check;
1189 }
1190
1191 public Boolean edit(CollectorItem item) {
1192 //Check ID and Variant is in database
1193 COLLECTORITEM = item;
1194 boolean check = checkInDatabase(item);
1195 if (check) {
1196 String id = String.valueOf(item.id);
1197 SQLiteDatabase db = getWritableDatabase();
1198 ContentValues values = new ContentValues();
1199 values.put(COLUMN_ID, item.id);
1200 values.put(COLUMN_NAME, item.name);
1201 values.put(COLUMN_COMPANY, item.company);
1202 values.put(COLUMN_YEARMADE, item.yearMade);
1203 values.put(COLUMN_COUNTRY, item.countryMade);
1204 values.put(COLUMN_AVPRICE, item.priceAverage);
1205 values.put(COLUMN_YEARBOUGHT, item.yearBought);
1206 values.put(COLUMN_PRICEBOUGHT, item.priceBought);
1207 values.put(COLUMN_AMOUNTGOT, item.amountGot);
1208 values.put(COLUMN_RARITY, item.rarity);
1209 db.update(TABLE_COLLECTOR, values, "_id = ?", new String[]{id});
1210 db.close();
1211 }
1212 return check;
1213 }
1214
1215
1216//All the checks
1217 //--------------------------------------------------------------------------------------------
1218//Get all id from the database
1219 public boolean checkInDatabase(CollectorItem item){
1220 boolean check = false;
1221 String allId ="";
1222 SQLiteDatabase db = getReadableDatabase();
1223 String query = "SELECT * FROM " + TABLE_COLLECTOR + " WHERE " + " 1";
1224 Cursor c =db.rawQuery(query, null);
1225 c.moveToFirst();
1226
1227 while (!c.isAfterLast() ){
1228 if (c.getString(c.getColumnIndex("_id")) != null){
1229 allId = (c.getString(c.getColumnIndex("_id")));
1230 if (allId.matches(item.id) ){
1231 check = true;
1232 }
1233 }
1234 c.moveToNext();
1235 }
1236 db.close();
1237 c.close();
1238 return check;
1239 }
1240
1241 public int checkInDatabaseSearch(String id){
1242 int current = -1;
1243 int currentReturn = -1;
1244 String allId ="";
1245 SQLiteDatabase db = getReadableDatabase();
1246 String query = "SELECT * FROM " + TABLE_COLLECTOR + " WHERE " + " 1" + " ORDER BY " + COLUMN_ID + " ASC";
1247 Cursor c =db.rawQuery(query, null);
1248 c.moveToFirst();
1249
1250 while (!c.isAfterLast() ){
1251 if (c.getString(c.getColumnIndex("_id")) != null){
1252 allId = (c.getString(c.getColumnIndex("_id")));
1253 current += 1;
1254 if (allId.matches(id) ){
1255 currentReturn = current;
1256 break;
1257 }
1258 }
1259 c.moveToNext();
1260 }
1261 db.close();
1262 c.close();
1263 return currentReturn;
1264 }
1265//----------------------------------------------------------------------------
1266 public CollectorItem getCurrentRow(int current){
1267 CollectorItem collectorItem = new CollectorItem();
1268 SQLiteDatabase db = getReadableDatabase();
1269 String query = "SELECT * FROM " + TABLE_COLLECTOR + " WHERE "+ "1 " + " ORDER BY " + COLUMN_ID + " ASC" ;
1270 Cursor c = db.rawQuery(query, null);
1271 //Finds the row with the correct Primary Key if found. If it can't be find, it will print a error message.
1272 c.moveToFirst();//Points to first item in find
1273 int count = c.getCount();
1274 //Go back or forward depending on direction and direction of last item called
1275 if (current < -1){
1276 c.moveToFirst();
1277 } else if (current > count-1){
1278 c.moveToLast();
1279 } else {
1280 c.moveToPosition(current);
1281 }
1282 //Finds the item fields
1283 collectorItem.id = c.getString(c.getColumnIndex("_id"));
1284 collectorItem.name = c.getString(c.getColumnIndex("_name"));
1285 collectorItem.company = c.getString(c.getColumnIndex("_company"));
1286 collectorItem.yearMade = c.getInt(c.getColumnIndex("_yearMade"));
1287 collectorItem.countryMade = c.getString(c.getColumnIndex("_countryMade"));
1288 collectorItem.priceAverage = c.getFloat(c.getColumnIndex("_priceAverage"));
1289 collectorItem.priceBought = c.getFloat(c.getColumnIndex("_priceBought"));
1290 collectorItem.yearBought = c.getInt(c.getColumnIndex("_yearBought"));
1291 collectorItem.amountGot = c.getInt(c.getColumnIndex("_amountGot"));
1292 collectorItem.rarity = c.getInt(c.getColumnIndex("_rarity"));
1293 return collectorItem;
1294 }
1295 public int getCount(){
1296 SQLiteDatabase db = getReadableDatabase();
1297 String query = "SELECT * FROM " + TABLE_COLLECTOR + " WHERE "+ "1 " ;
1298 Cursor c = db.rawQuery(query, null);
1299 int count = c.getCount();
1300 c.close();
1301 return count;
1302 }
1303
1304 //Queries ---------------------------------------------------
1305 //Total Count of items
1306 public int getTotalCount(){
1307 int totalAmount = 0;
1308 SQLiteDatabase db = getReadableDatabase();
1309 String query = "SELECT * FROM " + TABLE_COLLECTOR + " WHERE "+ "1 " + " ORDER BY " + COLUMN_AMOUNTGOT + " ASC" ;
1310 Cursor c = db.rawQuery(query,null);
1311 c.moveToFirst();
1312 while (!c.isAfterLast() ){
1313 if (c.getString(c.getColumnIndex("_id")) != null){
1314 totalAmount = totalAmount + c.getInt(c.getColumnIndex("_amountGot"));
1315 c.moveToNext();
1316 }
1317 }
1318 c.moveToNext();
1319 db.close();
1320 c.close();
1321 return totalAmount;
1322 }
1323 //Total Cost
1324 public float totalCostPaid(){
1325 float total = 0;
1326 SQLiteDatabase db = getReadableDatabase();
1327 String query = "SELECT * FROM " + TABLE_COLLECTOR + " WHERE "+ "1 " + " ORDER BY " + COLUMN_PRICEBOUGHT + " ASC" ;
1328 Cursor c = db.rawQuery(query,null);
1329 c.moveToFirst();
1330 while (!c.isAfterLast() ){
1331 if (c.getString(c.getColumnIndex("_id")) != null){
1332 total = total + c.getFloat(c.getColumnIndex("_priceBought"))*(c.getInt(c.getColumnIndex("_amountGot")));
1333 c.moveToNext();
1334 }
1335 }
1336 c.moveToNext();
1337
1338 db.close();
1339 c.close();
1340 return total;
1341 }
1342 //Total worth
1343 public float worth(){
1344 //Worth of collection
1345 float total = 0;
1346 SQLiteDatabase db = getReadableDatabase();
1347 String query = "SELECT * FROM " + TABLE_COLLECTOR + " WHERE "+ "1 " + " ORDER BY " + COLUMN_AVPRICE + " DESC" ;
1348 Cursor c = db.rawQuery(query,null);
1349 //Find the most valuable smurf
1350 c.moveToFirst();
1351
1352 first = c.getString(c.getColumnIndex("_id"));
1353
1354 //Get the total
1355 while (!c.isAfterLast() ){
1356 if (c.getString(c.getColumnIndex("_id")) != null){
1357 total = total + (c.getFloat(c.getColumnIndex("_priceAverage")) * c.getInt(c.getColumnIndex("_amountGot")));
1358 c.moveToNext();
1359 }
1360 }
1361 c.moveToNext();
1362 db.close();
1363 c.close();
1364 return total;
1365 }
1366 //Highest Value
1367 public String findHighestValue(){
1368 return first;
1369 }
1370
1371}
1372
1373CollectorItem Code
1374package com.example.patrick.collectordatabase;
1375
1376//Acts as a store to get variables between code files wittout the need to declear them ein every file they are needed in.
1377public class CollectorItem {
1378
1379 public String name;
1380 public String id;
1381 public String company;
1382 public int yearMade;
1383 public String countryMade;
1384 public float priceAverage;
1385 public float priceBought;
1386 public int yearBought;
1387 public int amountGot;
1388 public int rarity;
1389
1390 //Creates a item to set the fields above entered by a user or gotten from the db
1391 public String createAddItemStatementFrom(CollectorItem item) {
1392 return "";
1393 }
1394}
1395
1396GlobalVariables
1397package com.example.patrick.collectordatabase;
1398
1399//Keep variables needed between screens (As the variable are drop to save memory space
1400public class GlobalVariables {
1401 private static GlobalVariables instance = null;
1402 public int searchItemIndex = -1;
1403 protected GlobalVariables() {
1404 // Exists only to defeat instantiation.
1405 }
1406 public static GlobalVariables getInstance() {
1407 if(instance == null) {
1408 instance = new GlobalVariables();
1409 }
1410 return instance;
1411 }
1412}