commit 5556f86444d9043541024e08dd3d346e1c905041 Author: Yiğit Çolakoğlu Date: Thu Jun 21 01:38:06 2018 +0300 0Init diff --git a/Barcode_Reader_Python/.gitkeep b/Barcode_Reader_Python/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/Barcode_Reader_Python/arduino-i2c/arduino-i2c.ino b/Barcode_Reader_Python/arduino-i2c/arduino-i2c.ino new file mode 100644 index 0000000..a0ce31b --- /dev/null +++ b/Barcode_Reader_Python/arduino-i2c/arduino-i2c.ino @@ -0,0 +1,60 @@ +#include + +#define SLAVE_ADDRESS 0x04 +int number = 0; +int state = 0; + +void setup() { + pinMode(13, OUTPUT); + Serial.begin(9600); // start serial for output + // initialize i2c as slave + Wire.begin(SLAVE_ADDRESS); + + + + // define callbacks for i2c communication + Wire.onReceive(receiveData); + Wire.onRequest(sendData); + + + + Serial.println("Ready!"); +} + +void loop() { + + delay(100); +} + +// callback for received data +void receiveData(int byteCount) { + + while (Wire.available()) { + + + number = Wire.read(); + Serial.println(number); + if (number == 1) { + + if (state == 0) { + Serial.println("LED ON"); + state = 1; + } + else { + Serial.println("LED OFF"); + state = 0; + } + + } + } + +} + +// callback for sending data +void sendData() { + Wire.write(number); + Serial.println("Sending..."); + Wire.begin(0x08); + delay(100); + +} diff --git a/Barcode_Reader_Python/barcodes.csv b/Barcode_Reader_Python/barcodes.csv new file mode 100644 index 0000000..2d1c7a1 --- /dev/null +++ b/Barcode_Reader_Python/barcodes.csv @@ -0,0 +1 @@ +2018-06-15 23:18:13.020993,2 diff --git a/Barcode_Reader_Python/database_actions.py b/Barcode_Reader_Python/database_actions.py new file mode 100755 index 0000000..901111a --- /dev/null +++ b/Barcode_Reader_Python/database_actions.py @@ -0,0 +1,35 @@ +import pyrebase + +config = { + "apiKey": "AIzaSyD3bXRjLxEAVOKtj8hpjO4iI3Nn32F7agU", + "authDomain": "foodcloud-f6eb1.firebaseapp.com", + "databaseURL": "https://foodcloud-f6eb1.firebaseio.com/", + "storageBucket": "foodcloud-f6eb1.appspot.com" +} + +firebase = pyrebase.initialize_app(config) + +auth = firebase.auth() + +user = auth.sign_in_with_email_and_password('yigitcolakohlu@gmail.com', 'Ygtclksbl1') + +db = firebase.database() + + +data_format_prod = {'Prod_Name':None, 'BBD':None,'Nutrients':[],'Calories':0,'Allergens':[],'Problematic':False,'Process':None, 'ED':None} +data_format_proc = {'Harvested':{'Date':'','Location':'','Product':''},'Transport1':{'Duration':0,'Moved to,from':'-','Condition':True,'Stopped':False},'Process':{'Location':'','Processes':''},'Transport2':{'Duration':0,'Moved to,from':'-','Condition':0,'Stopped':False},'Packaging':{'Location':'','Material':'','Cancerogen':True}} + +data_2_prod = {'Prod_Name':"Chocolate", 'BBD':"28.01.2019",'Nutrients':['Lactose','Glucose','Cocoa'],'Calories':180,'Cooked':False,'Allergens':[""],'Problematic':False,'Process':''} +data_1_prod = {'Prod_Name':"Milk", 'BBD':"24.08.2018",'Nutrients':['Protein','Fat','Lactose','Glucose'],'Calories':120,'Cooked':False,'Allergens':['Lactose'],'Problematic':False,'Process':'Pastorized'} +data_2_proc = {'Harvested':{'Date':'24.04.2018','Location':'','Product':''},'Transport1':{'Duration':0,'Moved to,from':'-','Condition':0,'Stopped':False},'Process':{'Location':'','Processes':''},'Transport1':{'Duration':0,'Moved to,from':'-','Condition':0,'Stopped':False},'Packaging':{'Location':'','Material':'','Cancerogen':''}} +database_content = db.child("Products").get().val() + +def getDate(product): + return str((database_content[int(product)]['BBD'])) + + + + +#db.child("Products").child("1").set(data_1_prod) +#db.child("Products").child("2").set(data_2_prod) + diff --git a/Barcode_Reader_Python/database_actions.pyc b/Barcode_Reader_Python/database_actions.pyc new file mode 100644 index 0000000..488df92 Binary files /dev/null and b/Barcode_Reader_Python/database_actions.pyc differ diff --git a/Barcode_Reader_Python/pi@192.168.1.25 b/Barcode_Reader_Python/pi@192.168.1.25 new file mode 100755 index 0000000..29dccd4 --- /dev/null +++ b/Barcode_Reader_Python/pi@192.168.1.25 @@ -0,0 +1,45 @@ +from pyzbar import pyzbar +import argparse +import cv2 +import time +import database_actions + +dates = [] +reps = 0 +barcodes = None +prevcode = None +exp_date = [] +cam = cv2.VideoCapture(0) +while(reps<2): + while(barcodes == None or barcodes == []): + ret , image = cam.read() + barcodes = pyzbar.decode(image) + cv2.imshow("Image", image) + if cv2.waitKey(1) & 0xFF == ord('q'): + break + + for barcode in barcodes: + + (x, y, w, h) = barcode.rect + cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2) + barcodeData = barcode.data.decode("utf-8") + barcodeType = barcode.type + if(barcodeData != prevcode): + + text = "{} ({})".format(barcodeData, barcodeType) + cv2.putText(image, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, + 0.5, (0, 0, 255), 2) + + print("[INFO] Found {} barcode: {}".format(barcodeType, barcodeData)) + dates.append(database_actions.getDate(barcodeData)) + exp_date.append(int(barcodeData)) + reps += 1 + + prevcode = barcodeData + barcodes = None + cv2.imshow("Image", image) + if cv2.waitKey(1) & 0xFF == ord('q'): + break + +print dates + diff --git a/Barcode_Reader_Python/raspberry_zbar.py b/Barcode_Reader_Python/raspberry_zbar.py new file mode 100644 index 0000000..4b69b41 --- /dev/null +++ b/Barcode_Reader_Python/raspberry_zbar.py @@ -0,0 +1,71 @@ +# import the necessary packages +from imutils.video import VideoStream +from pyzbar import pyzbar +import argparse +import datetime +import imutils +import time +import cv2 + +# construct the argument parser and parse the arguments +ap = argparse.ArgumentParser() +ap.add_argument("-o", "--output", type=str, default="barcodes.csv", + help="path to output CSV file containing barcodes") +args = vars(ap.parse_args()) + +# initialize the video stream and allow the camera sensor to warm up +print("[INFO] starting video stream...") +# vs = VideoStream(src=0).start() +vs = VideoStream().start() +time.sleep(2.0) + +# open the output CSV file for writing and initialize the set of +# barcodes found thus far +csv = open(args["output"], "w") +found = set() +# loop over the frames from the video stream +while True: + # grab the frame from the threaded video stream and resize it to + # have a maximum width of 400 pixels + frame = vs.read() + frame = imutils.resize(frame, width=400) + + # find the barcodes in the frame and decode each of the barcodes + barcodes = pyzbar.decode(frame) + # loop over the detected barcodes + for barcode in barcodes: + # extract the bounding box location of the barcode and draw + # the bounding box surrounding the barcode on the image + (x, y, w, h) = barcode.rect + cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2) + + # the barcode data is a bytes object so if we want to draw it + # on our output image we need to convert it to a string first + barcodeData = barcode.data.decode("utf-8") + barcodeType = barcode.type + + # draw the barcode data and barcode type on the image + text = "{} ({})".format(barcodeData, barcodeType) + cv2.putText(frame, text, (x, y - 10), + cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2) + + # if the barcode text is currently not in our CSV file, write + # the timestamp + barcode to disk and update the set + if barcodeData not in found: + csv.write("{},{}\n".format(datetime.datetime.now(), + barcodeData)) + csv.flush() + found.add(barcodeData) + # show the output frame + cv2.imshow("Barcode Scanner", frame) + key = cv2.waitKey(1) & 0xFF + + # if the `q` key was pressed, break from the loop + if key == ord("q"): + break + +# close the output CSV file do a bit of cleanup +print("[INFO] cleaning up...") +csv.close() +cv2.destroyAllWindows() +vs.stop() \ No newline at end of file diff --git a/Barcode_Reader_Python/sort_calc_base_1hand.py b/Barcode_Reader_Python/sort_calc_base_1hand.py new file mode 100644 index 0000000..bfd6257 --- /dev/null +++ b/Barcode_Reader_Python/sort_calc_base_1hand.py @@ -0,0 +1,106 @@ +import sort_date +exp_date , dates_orig = sort_date.calcDate() +shelf_back = exp_date[:] +try: + expired = exp_date.count(-1) + for i in range(expired): + shelf_back.pop(shelf_back.index(-1)) + + shelf_new = sorted(shelf_back) + for i in range(expired): + shelf_new.append(-1) +except ValueError: + print('') +exp_date.append(None) +shelf_new.append(None) +repeats = 0 +correct_locs = [] +temp = None +moved_item = None +moved_item_loc = None + + +print "\n\n\n//////////////////////////////////////////////////////////////////////////////" +print(" {} ".format(exp_date)) +print(" {} ".format(shelf_new)) +print "/////////////////////////////////////////////////////////////////////////////\n\n\n" + +def backArray(myArray): + global shelf_back + shelf_back = [] + for i in range(len(myArray)): + shelf_back.append(myArray[i]) + +def eqArray(myArray): + global exp_date + exp_date = [] + for i in range(len(myArray)): + exp_date.append(myArray[i]) + + +def place(): + global exp_date + global shelf_new + global repeats + global shelf_back + repeats += 1 + backArray(exp_date) + + if (exp_date[len(exp_date)-1] != None): + empty_loc = exp_date.index(None) + moved_item_loc = exp_date.index(shelf_new[empty_loc]) + reps=0 + while True: + reps += 1 + if(moved_item_loc in correct_locs): + exp_date.pop(moved_item_loc) + moved_item_loc = exp_date.index(shelf_new[empty_loc]) + reps + continue + break + eqArray(shelf_back) + moved_item = exp_date[moved_item_loc] + if(exp_date[moved_item_loc] != shelf_new[moved_item_loc]): + exp_date[moved_item_loc] = None + exp_date[empty_loc] = moved_item + correct_locs.append(empty_loc) + + + print " Moved item {0} to location {1}. Location {2} is now empty!".format(moved_item,empty_loc + 1, moved_item_loc + 1) + print "============================================================================" + else: + print " Leaving item {0} in location {1}. Location {2} is still empty!".format(moved_item, moved_item_loc + 1,empty_loc + 1) + print "============================================================================" + correct_locs.append(moved_item_loc) + place() + else: + return + + + + +while True: + if(repeats < len(exp_date)): + for i in range(len(exp_date)): + if(exp_date[len(exp_date)-1] == None): + if(exp_date[i] == shelf_new[i]): + continue + else: + exp_date[len(exp_date)-1] = exp_date[i] + print '\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!' + print ' TEMP IS EMPTY, MOVING {0} FROM LOCATION {1} TO THE TEMP'.format(exp_date[i],i+1) + print '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n' + print "============================================================================" + exp_date[i] = None + + + else: + break + place() + +try: + print('***********************************************************************************') + print(' The last {} items have expired, throwing them away.'.format(len(exp_date)-shelf_new.index(-1)-1)) + print('***********************************************************************************') +except ValueError: + print(" No items have expired") + print('***********************************************************************************') diff --git a/Barcode_Reader_Python/sort_calc_base_2handed.py b/Barcode_Reader_Python/sort_calc_base_2handed.py new file mode 100755 index 0000000..6320ed2 --- /dev/null +++ b/Barcode_Reader_Python/sort_calc_base_2handed.py @@ -0,0 +1,60 @@ +exp_date = [1,1,7,6,3,9,10,2,8] +shelf_new = sorted(exp_date) +print shelf_new +moves = {} +cont = 1 +reps = 0 +prev_processed = [] +lastloc = None +check = False +curpro = 0 +lastpro = 0 +proreps = 0 +for i in range(len(shelf_new)): + curpro = shelf_new[i] + + if(curpro == lastpro): + proreps += 1 + else: + proreps = 0 + moves[i] = shelf_new.index(exp_date[i]) + proreps + + lastpro = curpro +print exp_date +print shelf_new +print moves +length = len(moves) +print('\n') +while(reps < length): + if(reps != 0): + curloc = min(moves, key=lambda x:abs(x-curloc)) + else: + curloc = next(iter(moves.values())) + while(cont == 1): + check = curloc in prev_processed + + + if(moves[curloc] in prev_processed): + print curloc, + moves.pop(curloc) + print('\n=========================================\n' ) + cont = 0 + reps += 1 + continue + else: + if(curloc == moves[curloc]): + cont = 0 + reps += 1 + moves.pop(curloc) + print('\n=========================================' ) + print(str(curloc) + ' location correct!') + print('=========================================' ) + continue + print curloc, + print " -> ", + lastloc = curloc + prev_processed.append(curloc) + curloc = moves[curloc] + moves.pop(lastloc) + reps += 1 + cont = 1 diff --git a/Barcode_Reader_Python/sort_date.py b/Barcode_Reader_Python/sort_date.py new file mode 100755 index 0000000..786dc49 --- /dev/null +++ b/Barcode_Reader_Python/sort_date.py @@ -0,0 +1,117 @@ +def dateComp(date_one,date_two): + date_one_id = date_one.split('.') + date_two_id = date_two.split('.') + if(int(date_one_id[2]) > int(date_two_id[2])): + return True + elif(int(date_one_id[2]) == int(date_two_id[2])): + if(int(date_one_id[1]) > int(date_two_id[1])): + return True + elif(int(date_one_id[1]) == int(date_two_id[1])): + if(int(date_one_id[0]) > int(date_two_id[0])): + return True + elif(int(date_one_id[0]) == int(date_two_id[0])): + return True + return False + +def addItem(list_bas,item,item_loc): + new_list = list_bas[0:item_loc] + new_list.append(item) + for i in range(len(list_bas) - item_loc): + new_list.append(list_bas[item_loc + i]) + return new_list +def expDate(current_date,prod_dates): + thrown_away = [] + thrown_locs = [] + thrown_number = 0 + for i in range(len(prod_dates)): + if(dateComp(current_date,prod_dates[i])): + thrown_away.append(prod_dates[i]) + thrown_locs.append(i) + + for i in range(len(thrown_locs)): + prod_dates.pop(thrown_locs[i]-thrown_number) + thrown_number += 1 + +def dateSort(current_date,prod_dates): + loc = None + sorted_dates = [] + prev_placed = True + + for i in range(len(prod_dates)): + if(dateComp(prod_dates[i],current_date)): + sorted_dates.append(prod_dates[i]) + loc = i + break + + + + for i in range(len(prod_dates)): + if(loc == i): + continue + prev_placed = True + for j in range(len(sorted_dates)): + if(prev_placed): + if(j==0): + if(dateComp(sorted_dates[j],prod_dates[i])): + sorted_dates = addItem(sorted_dates,prod_dates[i],0) + prev_placed = False + continue + if(j == len(sorted_dates) - 1 ): + if(dateComp(prod_dates[i],sorted_dates[j])): + sorted_dates = addItem(sorted_dates,prod_dates[i],len(sorted_dates)) + else: + sorted_dates = addItem(sorted_dates,prod_dates[i],len(sorted_dates)-1) + continue + + if(dateComp(prod_dates[i],sorted_dates[j])): + if(dateComp(sorted_dates[j+1],prod_dates[i])): + sorted_dates = addItem(sorted_dates,prod_dates[i],j+1) + prev_placed = False + continue + if(dateComp(sorted_dates[j],prod_dates[i])): + if(dateComp(prod_dates[i],sorted_dates[j-1])): + sorted_dates = addItem(sorted_dates,prod_dates[i],i) + prev_placed = False + continue + + return sorted_dates + +def dateToint(sorted_dates,unsorted_dates,date_current): + date_num = 0 + prev_date = None + sorted_dateInt = [] + unsorted_dateInt = [] + + for i in range(len(sorted_dates)): + if(dateComp(date_current,sorted_dates[i])): + sorted_dateInt.append(-1) + continue + if(prev_date == sorted_dates[i]): + sorted_dateInt.append(date_num) + continue + date_num += 1 + sorted_dateInt.append(date_num) + prev_date = sorted_dates[i] + + for i in unsorted_dates: + unsorted_dateInt.append(sorted_dateInt[sorted_dates.index(i)]) + + return unsorted_dateInt + +def listDif(list1,list2): + listOrig = list1 + for i in list2: + if(i in listOrig): + listOrig.pop(listOrig.index(i)) + + return listOrig + + +def calcDate(): + date_cur = '23.06.2018' + exp_dates = ['23.06.2019','22.06.2019','11.06.2018','24.06.2018','23.08.2018','23.04.2018'] + exp_dates_process = exp_dates[:] + sorted_date = dateSort(date_cur,exp_dates_process) + date_int = dateToint(sorted_date,exp_dates,date_cur) + return date_int,sorted_date + diff --git a/Barcode_Reader_Python/zbar.py b/Barcode_Reader_Python/zbar.py new file mode 100755 index 0000000..4c6cfe5 --- /dev/null +++ b/Barcode_Reader_Python/zbar.py @@ -0,0 +1,38 @@ +# import the necessary packages +from pyzbar import pyzbar +import argparse +import cv2 + +# construct the argument parser and parse the arguments +ap = argparse.ArgumentParser() +ap.add_argument("-i", "--image", required=True, + help="path to input image") +args = vars(ap.parse_args()) +# load the input image +image = cv2.imread(args["image"]) + +# find the barcodes in the image and decode each of the barcodes +barcodes = pyzbar.decode(image) +# loop over the detected barcodes +for barcode in barcodes: + # extract the bounding box location of the barcode and draw the + # bounding box surrounding the barcode on the image + (x, y, w, h) = barcode.rect + cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2) + + # the barcode data is a bytes object so if we want to draw it on + # our output image we need to convert it to a string first + barcodeData = barcode.data.decode("utf-8") + barcodeType = barcode.type + + # draw the barcode data and barcode type on the image + text = "{} ({})".format(barcodeData, barcodeType) + cv2.putText(image, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, + 0.5, (0, 0, 255), 2) + + # print the barcode type and data to the terminal + print("[INFO] Found {} barcode: {}".format(barcodeType, barcodeData)) + +# show the output image +cv2.imshow("Image", image) +cv2.waitKey(0) diff --git a/Barcode_Reader_Python/zbar_live.py b/Barcode_Reader_Python/zbar_live.py new file mode 100755 index 0000000..29dccd4 --- /dev/null +++ b/Barcode_Reader_Python/zbar_live.py @@ -0,0 +1,45 @@ +from pyzbar import pyzbar +import argparse +import cv2 +import time +import database_actions + +dates = [] +reps = 0 +barcodes = None +prevcode = None +exp_date = [] +cam = cv2.VideoCapture(0) +while(reps<2): + while(barcodes == None or barcodes == []): + ret , image = cam.read() + barcodes = pyzbar.decode(image) + cv2.imshow("Image", image) + if cv2.waitKey(1) & 0xFF == ord('q'): + break + + for barcode in barcodes: + + (x, y, w, h) = barcode.rect + cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2) + barcodeData = barcode.data.decode("utf-8") + barcodeType = barcode.type + if(barcodeData != prevcode): + + text = "{} ({})".format(barcodeData, barcodeType) + cv2.putText(image, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, + 0.5, (0, 0, 255), 2) + + print("[INFO] Found {} barcode: {}".format(barcodeType, barcodeData)) + dates.append(database_actions.getDate(barcodeData)) + exp_date.append(int(barcodeData)) + reps += 1 + + prevcode = barcodeData + barcodes = None + cv2.imshow("Image", image) + if cv2.waitKey(1) & 0xFF == ord('q'): + break + +print dates + diff --git a/Ev3_Code/.gitkeep b/Ev3_Code/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/FoodCloud.apk b/FoodCloud.apk new file mode 100644 index 0000000..10c73ea Binary files /dev/null and b/FoodCloud.apk differ diff --git a/FoodCloud/.gitignore b/FoodCloud/.gitignore new file mode 100644 index 0000000..5edb4ee --- /dev/null +++ b/FoodCloud/.gitignore @@ -0,0 +1,10 @@ +*.iml +.gradle +/local.properties +/.idea/libraries +/.idea/modules.xml +/.idea/workspace.xml +.DS_Store +/build +/captures +.externalNativeBuild diff --git a/FoodCloud/.idea/assetWizardSettings.xml b/FoodCloud/.idea/assetWizardSettings.xml new file mode 100644 index 0000000..260b6e4 --- /dev/null +++ b/FoodCloud/.idea/assetWizardSettings.xml @@ -0,0 +1,19 @@ + + + + + + \ No newline at end of file diff --git a/FoodCloud/.idea/caches/build_file_checksums.ser b/FoodCloud/.idea/caches/build_file_checksums.ser new file mode 100644 index 0000000..e6e0ba6 Binary files /dev/null and b/FoodCloud/.idea/caches/build_file_checksums.ser differ diff --git a/FoodCloud/.idea/codeStyles/Project.xml b/FoodCloud/.idea/codeStyles/Project.xml new file mode 100644 index 0000000..30aa626 --- /dev/null +++ b/FoodCloud/.idea/codeStyles/Project.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/FoodCloud/.idea/gradle.xml b/FoodCloud/.idea/gradle.xml new file mode 100644 index 0000000..7ac24c7 --- /dev/null +++ b/FoodCloud/.idea/gradle.xml @@ -0,0 +1,18 @@ + + + + + + \ No newline at end of file diff --git a/FoodCloud/.idea/misc.xml b/FoodCloud/.idea/misc.xml new file mode 100644 index 0000000..c0f68ed --- /dev/null +++ b/FoodCloud/.idea/misc.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/FoodCloud/.idea/runConfigurations.xml b/FoodCloud/.idea/runConfigurations.xml new file mode 100644 index 0000000..7f68460 --- /dev/null +++ b/FoodCloud/.idea/runConfigurations.xml @@ -0,0 +1,12 @@ + + + + + + \ No newline at end of file diff --git a/FoodCloud/.project b/FoodCloud/.project new file mode 100644 index 0000000..b3398ad --- /dev/null +++ b/FoodCloud/.project @@ -0,0 +1,17 @@ + + + FoodCloud + Project FoodCloud created by Buildship. + + + + + org.eclipse.buildship.core.gradleprojectbuilder + + + + + + org.eclipse.buildship.core.gradleprojectnature + + diff --git a/FoodCloud/.settings/org.eclipse.buildship.core.prefs b/FoodCloud/.settings/org.eclipse.buildship.core.prefs new file mode 100644 index 0000000..e889521 --- /dev/null +++ b/FoodCloud/.settings/org.eclipse.buildship.core.prefs @@ -0,0 +1,2 @@ +connection.project.dir= +eclipse.preferences.version=1 diff --git a/FoodCloud/app/.classpath b/FoodCloud/app/.classpath new file mode 100644 index 0000000..3589094 --- /dev/null +++ b/FoodCloud/app/.classpath @@ -0,0 +1,6 @@ + + + + + + diff --git a/FoodCloud/app/.gitignore b/FoodCloud/app/.gitignore new file mode 100644 index 0000000..796b96d --- /dev/null +++ b/FoodCloud/app/.gitignore @@ -0,0 +1 @@ +/build diff --git a/FoodCloud/app/.project b/FoodCloud/app/.project new file mode 100644 index 0000000..ac485d7 --- /dev/null +++ b/FoodCloud/app/.project @@ -0,0 +1,23 @@ + + + app + Project app created by Buildship. + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.buildship.core.gradleprojectbuilder + + + + + + org.eclipse.jdt.core.javanature + org.eclipse.buildship.core.gradleprojectnature + + diff --git a/FoodCloud/app/.settings/org.eclipse.buildship.core.prefs b/FoodCloud/app/.settings/org.eclipse.buildship.core.prefs new file mode 100644 index 0000000..b1886ad --- /dev/null +++ b/FoodCloud/app/.settings/org.eclipse.buildship.core.prefs @@ -0,0 +1,2 @@ +connection.project.dir=.. +eclipse.preferences.version=1 diff --git a/FoodCloud/app/build.gradle b/FoodCloud/app/build.gradle new file mode 100644 index 0000000..930d108 --- /dev/null +++ b/FoodCloud/app/build.gradle @@ -0,0 +1,34 @@ +apply plugin: 'com.android.application' + +android { + compileSdkVersion 27 + defaultConfig { + applicationId "gq.yigit.foodcloud" + minSdkVersion 24 + targetSdkVersion 27 + versionCode 1 + versionName "1.0" + testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" + } + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } +} + +dependencies { + implementation fileTree(include: ['*.jar'], dir: 'libs') + implementation 'com.google.firebase:firebase-database:16.0.1' + implementation 'com.android.support:appcompat-v7:27.1.1' + implementation 'com.android.support.constraint:constraint-layout:1.1.0' + implementation 'com.google.firebase:firebase-auth:16.0.1' + implementation 'com.android.support:wear:27.1.1' + testImplementation 'junit:junit:4.12' + androidTestImplementation 'com.android.support.test:runner:1.0.2' + androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' + api 'com.google.firebase:firebase-core:16.0.0' + compileOnly 'com.google.android.wearable:wearable:2.3.0' +} +apply plugin: 'com.google.gms.google-services' diff --git a/FoodCloud/app/google-services.json b/FoodCloud/app/google-services.json new file mode 100644 index 0000000..a649dcb --- /dev/null +++ b/FoodCloud/app/google-services.json @@ -0,0 +1,51 @@ +{ + "project_info": { + "project_number": "554038090297", + "firebase_url": "https://foodcloud-f6eb1.firebaseio.com", + "project_id": "foodcloud-f6eb1", + "storage_bucket": "foodcloud-f6eb1.appspot.com" + }, + "client": [ + { + "client_info": { + "mobilesdk_app_id": "1:554038090297:android:88c7b9f7692bb439", + "android_client_info": { + "package_name": "gq.yigit.foodcloud" + } + }, + "oauth_client": [ + { + "client_id": "554038090297-ur5brtr21n2p50hkuiprgbct2l6q76e5.apps.googleusercontent.com", + "client_type": 3 + }, + { + "client_id": "554038090297-ur5brtr21n2p50hkuiprgbct2l6q76e5.apps.googleusercontent.com", + "client_type": 3 + } + ], + "api_key": [ + { + "current_key": "AIzaSyBELWHmzgjrtJdUQZiITbnfSQpQgcZt7-Y" + } + ], + "services": { + "analytics_service": { + "status": 1 + }, + "appinvite_service": { + "status": 2, + "other_platform_oauth_client": [ + { + "client_id": "554038090297-ur5brtr21n2p50hkuiprgbct2l6q76e5.apps.googleusercontent.com", + "client_type": 3 + } + ] + }, + "ads_service": { + "status": 2 + } + } + } + ], + "configuration_version": "1" +} \ No newline at end of file diff --git a/FoodCloud/app/proguard-rules.pro b/FoodCloud/app/proguard-rules.pro new file mode 100644 index 0000000..f1b4245 --- /dev/null +++ b/FoodCloud/app/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile diff --git a/FoodCloud/app/src/androidTest/java/gq/yigit/foodcloud/ExampleInstrumentedTest.java b/FoodCloud/app/src/androidTest/java/gq/yigit/foodcloud/ExampleInstrumentedTest.java new file mode 100644 index 0000000..09a8ee8 --- /dev/null +++ b/FoodCloud/app/src/androidTest/java/gq/yigit/foodcloud/ExampleInstrumentedTest.java @@ -0,0 +1,26 @@ +package gq.yigit.foodcloud; + +import android.content.Context; +import android.support.test.InstrumentationRegistry; +import android.support.test.runner.AndroidJUnit4; + +import org.junit.Test; +import org.junit.runner.RunWith; + +import static org.junit.Assert.*; + +/** + * Instrumented test, which will execute on an Android device. + * + * @see Testing documentation + */ +@RunWith(AndroidJUnit4.class) +public class ExampleInstrumentedTest { + @Test + public void useAppContext() { + // Context of the app under test. + Context appContext = InstrumentationRegistry.getTargetContext(); + + assertEquals("gq.yigit.foodcloud", appContext.getPackageName()); + } +} diff --git a/FoodCloud/app/src/main/AndroidManifest.xml b/FoodCloud/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..24d0de8 --- /dev/null +++ b/FoodCloud/app/src/main/AndroidManifest.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + Set to true if your app is Standalone, that is, it does not require the handheld + app to run. + --> + + + + + \ No newline at end of file diff --git a/FoodCloud/app/src/main/java/com/google/zxing/integration/android/IntentIntegrator.java b/FoodCloud/app/src/main/java/com/google/zxing/integration/android/IntentIntegrator.java new file mode 100644 index 0000000..f6026bd --- /dev/null +++ b/FoodCloud/app/src/main/java/com/google/zxing/integration/android/IntentIntegrator.java @@ -0,0 +1,285 @@ +package com.google.zxing.integration.android; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import android.app.Activity; +import android.app.AlertDialog; +import android.content.ActivityNotFoundException; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.content.pm.ResolveInfo; +import android.net.Uri; +import android.os.Bundle; +import android.util.Log; + +public class IntentIntegrator { + + public static final int REQUEST_CODE = 0x0000c0de; // Only use bottom 16 bits + private static final String TAG = IntentIntegrator.class.getSimpleName(); + + public static final String DEFAULT_TITLE = "Install Barcode Scanner?"; + public static final String DEFAULT_MESSAGE = + "This application requires Barcode Scanner. Would you like to install it?"; + public static final String DEFAULT_YES = "Yes"; + public static final String DEFAULT_NO = "No"; + + private static final String BS_PACKAGE = "com.google.zxing.client.android"; + private static final String BSPLUS_PACKAGE = "com.srowen.bs.android"; + + // supported barcode formats + public static final Collection PRODUCT_CODE_TYPES = list("UPC_A", "UPC_E", "EAN_8", "EAN_13", "RSS_14"); + public static final Collection ONE_D_CODE_TYPES = + list("UPC_A", "UPC_E", "EAN_8", "EAN_13", "CODE_39", "CODE_93", "CODE_128", + "ITF", "RSS_14", "RSS_EXPANDED"); + public static final Collection QR_CODE_TYPES = Collections.singleton("QR_CODE"); + public static final Collection DATA_MATRIX_TYPES = Collections.singleton("DATA_MATRIX"); + + public static final Collection ALL_CODE_TYPES = null; + + public static final List TARGET_BARCODE_SCANNER_ONLY = Collections.singletonList(BS_PACKAGE); + public static final List TARGET_ALL_KNOWN = list( + BS_PACKAGE, // Barcode Scanner + BSPLUS_PACKAGE, // Barcode Scanner+ + BSPLUS_PACKAGE + ".simple" // Barcode Scanner+ Simple + // What else supports this intent? + ); + + private final Activity activity; + private String title; + private String message; + private String buttonYes; + private String buttonNo; + private List targetApplications; + private final Map moreExtras; + + public IntentIntegrator(Activity activity) { + this.activity = activity; + title = DEFAULT_TITLE; + message = DEFAULT_MESSAGE; + buttonYes = DEFAULT_YES; + buttonNo = DEFAULT_NO; + targetApplications = TARGET_ALL_KNOWN; + moreExtras = new HashMap(3); + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public void setTitleByID(int titleID) { + title = activity.getString(titleID); + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + public void setMessageByID(int messageID) { + message = activity.getString(messageID); + } + + public String getButtonYes() { + return buttonYes; + } + + public void setButtonYes(String buttonYes) { + this.buttonYes = buttonYes; + } + + public void setButtonYesByID(int buttonYesID) { + buttonYes = activity.getString(buttonYesID); + } + + public String getButtonNo() { + return buttonNo; + } + + public void setButtonNo(String buttonNo) { + this.buttonNo = buttonNo; + } + + public void setButtonNoByID(int buttonNoID) { + buttonNo = activity.getString(buttonNoID); + } + + public Collection getTargetApplications() { + return targetApplications; + } + + public final void setTargetApplications(List targetApplications) { + if (targetApplications.isEmpty()) { + throw new IllegalArgumentException("No target applications"); + } + this.targetApplications = targetApplications; + } + + public void setSingleTargetApplication(String targetApplication) { + this.targetApplications = Collections.singletonList(targetApplication); + } + + public Map getMoreExtras() { + return moreExtras; + } + + public final void addExtra(String key, Object value) { + moreExtras.put(key, value); + } + + + public final AlertDialog initiateScan() { + return initiateScan(ALL_CODE_TYPES); + } + + public final AlertDialog initiateScan(Collection desiredBarcodeFormats) { + Intent intentScan = new Intent(BS_PACKAGE + ".SCAN"); + intentScan.addCategory(Intent.CATEGORY_DEFAULT); + + // check which types of codes to scan for + if (desiredBarcodeFormats != null) { + // set the desired barcode types + StringBuilder joinedByComma = new StringBuilder(); + for (String format : desiredBarcodeFormats) { + if (joinedByComma.length() > 0) { + joinedByComma.append(','); + } + joinedByComma.append(format); + } + intentScan.putExtra("SCAN_FORMATS", joinedByComma.toString()); + } + + + String targetAppPackage = findTargetAppPackage(intentScan); + if (targetAppPackage == null) { + return showDownloadDialog(); + } + intentScan.setPackage(targetAppPackage); + intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); + intentScan.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); + attachMoreExtras(intentScan); + startActivityForResult(intentScan, REQUEST_CODE); + return null; + } + + + protected void startActivityForResult(Intent intent, int code) { + activity.startActivityForResult(intent, code); + } + + private String findTargetAppPackage(Intent intent) { + PackageManager pm = activity.getPackageManager(); + List availableApps = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); + if (availableApps != null) { + for (ResolveInfo availableApp : availableApps) { + String packageName = availableApp.activityInfo.packageName; + if (targetApplications.contains(packageName)) { + return packageName; + } + } + } + return null; + } + + private AlertDialog showDownloadDialog() { + AlertDialog.Builder downloadDialog = new AlertDialog.Builder(activity); + downloadDialog.setTitle(title); + downloadDialog.setMessage(message); + downloadDialog.setPositiveButton(buttonYes, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) { + String packageName = targetApplications.get(0); + Uri uri = Uri.parse("market://details?id=" + packageName); + Intent intent = new Intent(Intent.ACTION_VIEW, uri); + try { + activity.startActivity(intent); + } catch (ActivityNotFoundException anfe) { + // Hmm, market is not installed + Log.w(TAG, "Google Play is not installed; cannot install " + packageName); + } + } + }); + downloadDialog.setNegativeButton(buttonNo, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialogInterface, int i) {} + }); + return downloadDialog.show(); + } + + public static IntentResult parseActivityResult(int requestCode, int resultCode, Intent intent) { + if (requestCode == REQUEST_CODE) { + if (resultCode == Activity.RESULT_OK) { + String contents = intent.getStringExtra("SCAN_RESULT"); + String formatName = intent.getStringExtra("SCAN_RESULT_FORMAT"); + byte[] rawBytes = intent.getByteArrayExtra("SCAN_RESULT_BYTES"); + int intentOrientation = intent.getIntExtra("SCAN_RESULT_ORIENTATION", Integer.MIN_VALUE); + Integer orientation = intentOrientation == Integer.MIN_VALUE ? null : intentOrientation; + String errorCorrectionLevel = intent.getStringExtra("SCAN_RESULT_ERROR_CORRECTION_LEVEL"); + return new IntentResult(contents, + formatName, + rawBytes, + orientation, + errorCorrectionLevel); + } + return new IntentResult(); + } + return null; + } + + public final AlertDialog shareText(CharSequence text, CharSequence type) { + Intent intent = new Intent(); + intent.addCategory(Intent.CATEGORY_DEFAULT); + intent.setAction(BS_PACKAGE + ".ENCODE"); + intent.putExtra("ENCODE_TYPE", type); + intent.putExtra("ENCODE_DATA", text); + String targetAppPackage = findTargetAppPackage(intent); + if (targetAppPackage == null) { + return showDownloadDialog(); + } + intent.setPackage(targetAppPackage); + intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); + intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); + attachMoreExtras(intent); + activity.startActivity(intent); + return null; + } + + private static List list(String... values) { + return Collections.unmodifiableList(Arrays.asList(values)); + } + + private void attachMoreExtras(Intent intent) { + for (Map.Entry entry : moreExtras.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + // Kind of hacky + if (value instanceof Integer) { + intent.putExtra(key, (Integer) value); + } else if (value instanceof Long) { + intent.putExtra(key, (Long) value); + } else if (value instanceof Boolean) { + intent.putExtra(key, (Boolean) value); + } else if (value instanceof Double) { + intent.putExtra(key, (Double) value); + } else if (value instanceof Float) { + intent.putExtra(key, (Float) value); + } else if (value instanceof Bundle) { + intent.putExtra(key, (Bundle) value); + } else { + intent.putExtra(key, value.toString()); + } + } + } +} \ No newline at end of file diff --git a/FoodCloud/app/src/main/java/com/google/zxing/integration/android/IntentResult.java b/FoodCloud/app/src/main/java/com/google/zxing/integration/android/IntentResult.java new file mode 100644 index 0000000..0fe4e83 --- /dev/null +++ b/FoodCloud/app/src/main/java/com/google/zxing/integration/android/IntentResult.java @@ -0,0 +1,67 @@ + + +package com.google.zxing.integration.android; + + +public final class IntentResult { + + private final String contents; + private final String formatName; + private final byte[] rawBytes; + private final Integer orientation; + private final String errorCorrectionLevel; + + IntentResult() { + this(null, null, null, null, null); + } + + IntentResult(String contents, + String formatName, + byte[] rawBytes, + Integer orientation, + String errorCorrectionLevel) { + this.contents = contents; + this.formatName = formatName; + this.rawBytes = rawBytes; + this.orientation = orientation; + this.errorCorrectionLevel = errorCorrectionLevel; + } + + + public String getContents() { + return contents; + } + + + public String getFormatName() { + return formatName; + } + + + public byte[] getRawBytes() { + return rawBytes; + } + + + public Integer getOrientation() { + return orientation; + } + + + public String getErrorCorrectionLevel() { + return errorCorrectionLevel; + } + + @Override + public String toString() { + StringBuilder dialogText = new StringBuilder(100); + dialogText.append("Format: ").append(formatName).append('\n'); + dialogText.append("Contents: ").append(contents).append('\n'); + int rawBytesLength = rawBytes == null ? 0 : rawBytes.length; + dialogText.append("Raw bytes: (").append(rawBytesLength).append(" bytes)\n"); + dialogText.append("Orientation: ").append(orientation).append('\n'); + dialogText.append("EC level: ").append(errorCorrectionLevel).append('\n'); + return dialogText.toString(); + } + +} \ No newline at end of file diff --git a/FoodCloud/app/src/main/java/gq/yigit/foodcloud/GetInfo.java b/FoodCloud/app/src/main/java/gq/yigit/foodcloud/GetInfo.java new file mode 100644 index 0000000..89a28c3 --- /dev/null +++ b/FoodCloud/app/src/main/java/gq/yigit/foodcloud/GetInfo.java @@ -0,0 +1,16 @@ +package gq.yigit.foodcloud; + +import android.support.v7.app.AppCompatActivity; +import android.os.Bundle; +import android.webkit.WebView; + +public class GetInfo extends AppCompatActivity { + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_get_info); + WebView myWebView = (WebView) findViewById(R.id.info); + myWebView.loadUrl("https://www.welthungerhilfe.org/our-work/approaches/food-security-standard/"); + } +} diff --git a/FoodCloud/app/src/main/java/gq/yigit/foodcloud/LearnMore.java b/FoodCloud/app/src/main/java/gq/yigit/foodcloud/LearnMore.java new file mode 100644 index 0000000..2719449 --- /dev/null +++ b/FoodCloud/app/src/main/java/gq/yigit/foodcloud/LearnMore.java @@ -0,0 +1,99 @@ +package gq.yigit.foodcloud; + +import android.content.Intent; +import android.support.v7.app.AppCompatActivity; +import android.os.Bundle; +import android.util.Log; +import android.view.View; +import android.widget.Button; +import android.widget.ImageView; +import android.widget.TextView; +import android.widget.Toast; + +import com.google.firebase.database.DataSnapshot; +import com.google.firebase.database.DatabaseError; +import com.google.firebase.database.DatabaseReference; +import com.google.firebase.database.FirebaseDatabase; +import com.google.firebase.database.ValueEventListener; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +public class LearnMore extends AppCompatActivity implements View.OnClickListener { + private static final String TAG = "MainActivity"; + public String prod_loc_more; + public ImageView factory; + public ImageView farm; + public ImageView packaging; + public ImageView trans1; + public ImageView trans2; + public ImageView factory_cond; + public ImageView farm_cond; + public ImageView packaging_cond; + public ImageView trans1_cond; + public ImageView trans2_cond; + public Button back_to_main; + public Map someMap; + public String prod_loc; + Map map = new HashMap(); + FirebaseDatabase database = FirebaseDatabase.getInstance(); + DatabaseReference myRef = database.getReference(); + + @Override + protected void onCreate(Bundle savedInstanceState) { + Bundle extras = getIntent().getExtras(); + if (extras != null) { + prod_loc_more = extras.getString("key"); + //The key argument here must match that used in the other activity + } + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_learn_more); + factory = (ImageView) findViewById(R.id.factory); + factory.setOnClickListener(this); + farm = (ImageView) findViewById(R.id.farm); + farm.setOnClickListener(this); + packaging = (ImageView) findViewById(R.id.packaging); + packaging.setOnClickListener(this); + trans1 = (ImageView) findViewById(R.id.trans1); + trans1.setOnClickListener(this); + trans2 = (ImageView) findViewById(R.id.trans2); + trans2.setOnClickListener(this); + back_to_main = (Button) findViewById(R.id.go_back_to_main); + back_to_main.setOnClickListener(this); + + } + + public void onClick(View v){ + if(v.getId() == R.id.go_back_to_main){ + Intent i = new Intent(LearnMore.this, MainActivity.class); + startActivity(i); + } + myRef.addValueEventListener(new ValueEventListener() { + @Override + public void onDataChange(DataSnapshot dataSnapshot) { + Bundle extras = getIntent().getExtras(); + if (extras != null) { + prod_loc = extras.getString("key"); + //The key argument here must match that used in the other activity + } + // This method is called once with the initial value and again + // whenever data at this location is updated. + someMap = (Map) dataSnapshot.getValue(); + ArrayList al1 = new ArrayList(); + al1 = (ArrayList) someMap.get("Production"); + al1.remove(0); + + + } + + @Override + public void onCancelled(DatabaseError error) { + // Failed to read value + Log.w(TAG, "Failed to read value.", error.toException()); + } + + }); + } + +} diff --git a/FoodCloud/app/src/main/java/gq/yigit/foodcloud/MainActivity.java b/FoodCloud/app/src/main/java/gq/yigit/foodcloud/MainActivity.java new file mode 100644 index 0000000..5e43c12 --- /dev/null +++ b/FoodCloud/app/src/main/java/gq/yigit/foodcloud/MainActivity.java @@ -0,0 +1,61 @@ +package gq.yigit.foodcloud; + +import android.support.v7.app.AppCompatActivity; +import android.os.Bundle; + +import com.google.zxing.integration.android.IntentIntegrator; +import com.google.zxing.integration.android.IntentResult; +import android.content.Intent; +import android.view.View; +import android.view.View.OnClickListener; +import android.widget.Button; +import android.widget.TextView; +import android.widget.Toast; + +public class MainActivity extends AppCompatActivity implements OnClickListener { + int cnt = 0; + private Button scanBtn; + private Button infoBtn; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_main); + + scanBtn = (Button)findViewById(R.id.scan_button); + + scanBtn.setOnClickListener(this); + infoBtn = (Button)findViewById(R.id.info_button); + + infoBtn.setOnClickListener(this); + } + + public void onClick(View v){ + if (v.getId() == R.id.scan_button) { + IntentIntegrator scanIntegrator = new IntentIntegrator(this); + scanIntegrator.initiateScan(); + + } + if (v.getId() == R.id.info_button) { + startActivity(new Intent(MainActivity.this, GetInfo.class)); + + } + + + } + + public void onActivityResult(int requestCode, int resultCode, Intent intent) { + IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent); + if (scanningResult != null) { + String scanContent = scanningResult.getContents(); + Intent i = new Intent(MainActivity.this, ProductInfo.class); + i.putExtra("key",scanContent); + startActivity(i); + } + else{ + Toast toast = Toast.makeText(getApplicationContext(), + "No scan data received!", Toast.LENGTH_SHORT); + toast.show(); + } + } +} diff --git a/FoodCloud/app/src/main/java/gq/yigit/foodcloud/ProductInfo.java b/FoodCloud/app/src/main/java/gq/yigit/foodcloud/ProductInfo.java new file mode 100644 index 0000000..e174707 --- /dev/null +++ b/FoodCloud/app/src/main/java/gq/yigit/foodcloud/ProductInfo.java @@ -0,0 +1,157 @@ +package gq.yigit.foodcloud; + +import android.content.Intent; +import android.support.v7.app.AppCompatActivity; +import android.os.Bundle; +import android.util.Log; +import android.view.View; +import android.widget.TextView; +import android.widget.Button; +import com.google.firebase.database.*; +import java.util.HashMap; +import java.util.Map; +import java.util.ArrayList; +import android.view.View.OnClickListener; + +public class ProductInfo extends AppCompatActivity implements OnClickListener { + private static final String TAG = "MainActivity"; + private TextView Name; + private TextView Cal; + private TextView Cooked; + private TextView Nutrients; + private TextView BBD; + private TextView Processed; + private TextView Problematic; + private TextView Allergens; + private String name; + private String cal; + private String cooked; + private ArrayList nutrients; + private String bbd; + private String processed; + private String problematic; + private ArrayList allergens; + public ArrayList Prods; + public Map someMap; + public HashMap Prod; + private Button scanBtn; + private Button jrnyBtn; + public String prod_loc; + public String allergens_print = new String(); + public String nutrients_print = new String(); + + + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_product_info); + + } + + @Override + public void onClick(View v){ + if (v.getId() == R.id.button) { + Intent i = new Intent(ProductInfo.this, MainActivity.class); + startActivity(i); + }if (v.getId() == R.id.journey) { + Intent i = new Intent(ProductInfo.this, LearnMore.class); + i.putExtra("key", prod_loc); + startActivity(i); + } + } + + public void onStart(){ + super.onStart(); + setContentView(R.layout.activity_product_info); + Map map = new HashMap(); + FirebaseDatabase database = FirebaseDatabase.getInstance(); + DatabaseReference myRef = database.getReference(); + scanBtn = (Button)findViewById(R.id.button); + scanBtn.setOnClickListener(this); + jrnyBtn = (Button)findViewById(R.id.journey); + jrnyBtn.setOnClickListener(this); + myRef.addValueEventListener(new ValueEventListener() { + @Override + public void onDataChange(DataSnapshot dataSnapshot) { + Bundle extras = getIntent().getExtras(); + if (extras != null) { + prod_loc = extras.getString("key"); + //The key argument here must match that used in the other activity + } + // This method is called once with the initial value and again + // whenever data at this location is updated. + someMap = (Map) dataSnapshot.getValue(); + ArrayList al1 = new ArrayList(); + al1 = (ArrayList) someMap.get("Products"); + al1.remove(0); + Prods = al1; + Prod = (HashMap)al1.get((Integer.parseInt(prod_loc))-1); + Log.d(TAG,"Value is : " + al1.get((Integer.parseInt(prod_loc))-1)); + Log.d(TAG,Prod.get("Calories").getClass().toString()); + name = Prod.get("Prod_Name").toString(); + cal = Prod.get("Calories").toString(); + cooked = Prod.get("Cooked").toString(); + nutrients = (ArrayList)Prod.get("Nutrients"); + bbd = Prod.get("BBD").toString(); + processed = Prod.get("Process").toString(); + allergens = (ArrayList)Prod.get("Allergens"); + problematic = Prod.get("Problematic").toString(); + Name = (TextView) findViewById(R.id.name); + Name.setText("Name : " + name); + Cal = (TextView) findViewById(R.id.Calories); + Cal.setText("Calories : " + cal); + Allergens = (TextView) findViewById(R.id.allergens); + allergens_print = ""; + if(allergens.isEmpty()) { + Allergens.setText("Allergens : None"); + }else{ + for(int i = 0; i < allergens.size();i++) { + allergens_print = allergens_print + allergens.get(i); + if(i != allergens.size() -1){ + allergens_print = allergens_print + " , "; + } + } + Allergens.setText("Allergens : " + allergens_print); + } + Nutrients = (TextView) findViewById(R.id.nutrients); + nutrients_print = ""; + if(nutrients.isEmpty()) { + Nutrients.setText("Nutrients : None"); + }else{ + for(int i = 0; i < nutrients.size();i++) { + nutrients_print = nutrients_print + nutrients.get(i); + if(i != nutrients.size() -1){ + nutrients_print = nutrients_print + " , "; + } + } + Nutrients.setText("Nutrients : " + nutrients_print); + } + Cooked = (TextView) findViewById(R.id.cooked); + Cooked.setText("Cooked : " + cooked); + BBD = (TextView) findViewById(R.id.BBD); + BBD.setText("BBD : " +bbd); + Processed = (TextView) findViewById(R.id.Process); + Processed.setText("Process : " + processed); + Problematic = (TextView) findViewById(R.id.Problems); + Problematic.setText("Problemed : " + problematic); + + } + + @Override + public void onCancelled(DatabaseError error) { + // Failed to read value + Log.w(TAG, "Failed to read value.", error.toException()); + } + + }); + + + + + + + + } + +} diff --git a/FoodCloud/app/src/main/res/drawable-v24/ic_launcher_foreground.xml b/FoodCloud/app/src/main/res/drawable-v24/ic_launcher_foreground.xml new file mode 100644 index 0000000..c7bd21d --- /dev/null +++ b/FoodCloud/app/src/main/res/drawable-v24/ic_launcher_foreground.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + diff --git a/FoodCloud/app/src/main/res/drawable/ic_launcher_background.xml b/FoodCloud/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..01f0af0 --- /dev/null +++ b/FoodCloud/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,74 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/FoodCloud/app/src/main/res/layout/activity_get_info.xml b/FoodCloud/app/src/main/res/layout/activity_get_info.xml new file mode 100644 index 0000000..23068eb --- /dev/null +++ b/FoodCloud/app/src/main/res/layout/activity_get_info.xml @@ -0,0 +1,33 @@ + + + + + +