diff --git a/.idea/assetWizardSettings.xml b/.idea/assetWizardSettings.xml
new file mode 100644
index 0000000..6b96cf0
--- /dev/null
+++ b/.idea/assetWizardSettings.xml
@@ -0,0 +1,14 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/codeStyles/Project.xml b/.idea/codeStyles/Project.xml
new file mode 100644
index 0000000..30aa626
--- /dev/null
+++ b/.idea/codeStyles/Project.xml
@@ -0,0 +1,29 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/PHP_API_FILES/DbOperation.php b/app/PHP_API_FILES/DbOperation.php
deleted file mode 100644
index e354601..0000000
--- a/app/PHP_API_FILES/DbOperation.php
+++ /dev/null
@@ -1,389 +0,0 @@
-con = $db->connect();
- }
-
- //Method to create a new user
- function registerUser($email, $uid, $name)
- {
- if (!$this->isUserExist($uid)) {
- $password = md5($pass);
- $stmt = $this->con->prepare("INSERT INTO Users (mail, uid, displayname) VALUES (?, ?, ?)");
- $stmt->bind_param("sss", $email, $uid, $name);
- if ($stmt->execute())
- return USER_CREATED;
- return USER_CREATION_FAILED;
- }
- return USER_CREATED;
- }
- function getUserByUid($uid)
- {
- $stmt = $this->con->prepare("SELECT id, mail, uid, displayname FROM Users WHERE uid = ?");
- $stmt->bind_param("s", $uid);
- $stmt->execute();
- $stmt->bind_result($id, $mail, $uid, $displayname);
- $stmt->fetch();
- $user = array();
- $user['id'] = $id;
- $user['mail'] = $mail;
- $user['uid'] = $uid;
- $user['displayname'] = $displayname;
- return $user;
- }
-
-
- //Method for user login
- function userLogin($email, $pass)
- {
- $password = md5($pass);
- $stmt = $this->con->prepare("SELECT id FROM users WHERE email = ? AND password = ?");
- $stmt->bind_param("ss", $email, $password);
- $stmt->execute();
- $stmt->store_result();
- return $stmt->num_rows > 0;
- }
- function registerUserwithmail($email, $uid, $passwrod)
- {
- if (!$this->isUserExist($uid)) {
- $password = md5($password);
- $stmt = $this->con->prepare("INSERT INTO Users (email, uid, password) VALUES (?, ?, ?)");
- $stmt->bind_param("sss", $email, $uid, $password);
- if ($stmt->execute())
- return USER_CREATED;
- return USER_CREATION_FAILED;
- }
- return USER_EXIST;
-
- }
-
- //Method to send a message to another user
- function sendMessage($from, $to, $title, $message)
- {
- $stmt = $this->con->prepare("INSERT INTO messages (from_users_id, to_users_id, title, message) VALUES (?, ?, ?, ?);");
- $stmt->bind_param("iiss", $from, $to, $title, $message);
- if ($stmt->execute())
- return true;
- return false;
- }
- function isShared($UserId, $whichtime, $date)
- {
- $year = substr($date, 0,4);
- $month = substr($date, 5,7);
- $day = substr($date, 8,10);
-
- if($whichtime=="Breakfast"){
- $stmt = $this->con->prepare("SELECT ParentSharedFoodsId FROM SharedBreakfasts WHERE UserID = ? AND year(SendDate) = ?
- AND month(SendDate) =? AND day(SendDate) =?");
- $stmt->bind_param("ssss", $UserId, $year, $month, $day);
- $stmt->execute();
- $stmt->store_result();
- return $stmt->num_rows > 0;
- }
- else if($whichtime=="Lunch")
- {
- $year = substr($date, 0,4);
- $month = substr($date, 5,7);
- $day = substr($date, 8,10);
- $stmt = $this->con->prepare("SELECT ParentSharedFoodsId FROM SharedLunches WHERE UserID = ? AND year(SendDate) = ?
- AND month(SendDate) =? AND day(SendDate) =?");
- $stmt->bind_param("ssss", $UserId, $year, $month, $day);
- $stmt->execute();
- $stmt->store_result();
- return $stmt->num_rows > 0;
- }
- else if($whichtime=="Dinner")
- {
- $year = substr($date, 0,4);
- $month = substr($date, 5,7);
- $day = substr($date, 8,10);
- $stmt = $this->con->prepare("SELECT ParentSharedFoodsId FROM SharedDinners WHERE UserID = ? AND year(SendDate) = ?
- AND month(SendDate) =? AND day(SendDate) =?");
- $stmt->bind_param("isss", $UserId, $year, $month, $day);
- $stmt->execute();
- $stmt->store_result();
- return $stmt->num_rows > 0;
- }
- else if($whichtime=="Drinks")
- {
- $year = substr($date, 0,4);
- $month = substr($date, 5,7);
- $day = substr($date, 8,10);
- $stmt = $this->con->prepare("SELECT ParentSharedFoodsId FROM SharedDrinks WHERE UserID = ? AND year(SendDate) = ?
- AND month(SendDate) =? AND day(SendDate) =?");
- $stmt->bind_param("ssss", $UserId, $year, $month, $day);
- $stmt->execute();
- $stmt->store_result();
- return $stmt->num_rows > 0;
- }
- else if($whichtime=="Snacks")
- {
- $year = substr($date, 0,4);
- $month = substr($date, 5,7);
- $day = substr($date, 8,10);
- $stmt = $this->con->prepare("SELECT ParentSharedFoodsId FROM SharedSnacks WHERE UserID = ? AND year(SendDate) = ?
- AND month(SendDate) =? AND day(SendDate) =?");
- $stmt->bind_param("ssss", $UserId, $year, $month, $day);
- $stmt->execute();
- $stmt->store_result();
- return $stmt->num_rows > 0;
- }
- }
-
- //Method to update profile of user
- function updateProfile($id, $name, $email, $pass, $gender)
- {
- $password = md5($pass);
- $stmt = $this->con->prepare("UPDATE users SET name = ?, email = ?, password = ?, gender = ? WHERE id = ?");
- $stmt->bind_param("ssssi", $name, $email, $password, $gender, $id);
- if ($stmt->execute())
- return true;
- return false;
- }
-
- //Method to get messages of a particular user
- function getMessages($userid)
- {
- $stmt = $this->con->prepare("SELECT messages.id, (SELECT users.name FROM users WHERE users.id = messages.from_users_id) as `from`, (SELECT users.name FROM users WHERE users.id = messages.to_users_id) as `to`, messages.title, messages.message, messages.sentat FROM messages WHERE messages.to_users_id = ? ORDER BY messages.sentat DESC;");
- $stmt->bind_param("i", $userid);
- $stmt->execute();
- $stmt->bind_result($id, $from, $to, $title, $message, $sent);
-
- $messages = array();
-
- while ($stmt->fetch()) {
- $temp = array();
-
- $temp['id'] = $id;
- $temp['from'] = $from;
- $temp['to'] = $to;
- $temp['title'] = $title;
- $temp['message'] = $message;
- $temp['sent'] = $sent;
-
- array_push($messages, $temp);
- }
-
- return $messages;
- }
-
- //Method to get user by email
-
-
- //Method to get all users
- function getAllUsers(){
- $stmt = $this->con->prepare("SELECT id, name, email, gender FROM users");
- $stmt->execute();
- $stmt->bind_result($id, $name, $email, $gender);
- $users = array();
- while($stmt->fetch()){
- $temp = array();
- $temp['id'] = $id;
- $temp['name'] = $name;
- $temp['email'] = $email;
- $temp['gender'] = $gender;
- array_push($users, $temp);
- }
- return $users;
- }
- function addSelectedFood($foodId, $Userid, $Date, $Calories, $Protein, $Fat, $Carbohydrates, $whichtime, $sharedfoodsId)
- {
- $stmt = $this->con->prepare("INSERT INTO ".$whichtime." (foodId, UserId, SendDate, Calories, Protein, Fat, Carbohydrates, SharedFoodsId) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
- $stmt->bind_param("sisddddi", $foodId, $Userid, $Date, $Calories, $Protein, $Fat, $Carbohydrates, $sharedfoodsId);
- if ($stmt->execute())
- return USER_CREATED;
- return USER_CREATION_FAILED;
- }
- function addSharedFoodList($UserId, $Date, $SharedFoodListDatabase, $Calories, $Protein, $Fat, $Carbohydrates)
- {
- $stmt = $this->con->prepare("INSERT INTO ".$SharedFoodListDatabase." (UserId, SendDate, Calories, Protein, Fat, Carbohydrates) VALUES (?, ?, ?, ?, ?, ?)");
- $stmt->bind_param("isdddd", $UserId, $Date, $Calories, $Protein, $Fat, $Carbohydrates);
-
- if ($stmt->execute())
- return USER_CREATED;
- return USER_CREATION_FAILED;
-
- }
- function updateFoods($UserId, $Date, $whichtime, $Calories, $Protein, $Fat, $Carbohydrates )
- {
- $year = substr($Date, 0,4);
- $month = substr($Date, 5,7);
- $day = substr($Date, 8,10);
- if($whichtime=="Breakfast"){
- $stmt = $this->con->prepare("UPDATE Breakfast SET Breakfast.SharedFoodsId=(SELECT SharedBreakfasts.ParentSharedFoodsId
- FROM SharedBreakfasts WHERE year(SharedBreakfasts.SendDate)=? AND month(SharedBreakfasts.SendDate)=? AND day(SharedBreakfasts.SendDate)=?
- AND SharedBreakfasts.UserId=Breakfast.UserId) WHERE year(Breakfast.SendDate)=? AND month(Breakfast.SendDate)=? AND day(Breakfast.SendDate)=?
- AND Breakfast.UserId =?");
- $stmt->bind_param("sssssss", $year, $month, $day, $year, $month, $day, $UserId );
- if ($stmt->execute())
- return true;
- return false;
- }
- else if($whichtime=="Lunch")
- {
- $stmt = $this->con->prepare("UPDATE Lunch SET Lunch.SharedFoodsId=(SELECT SharedLunches.ParentSharedFoodsId
- FROM SharedLunches WHERE year(SharedLunches.SendDate)=? AND month(SharedLunches.SendDate)=? AND day(SharedLunches.SendDate)=?
- AND SharedLunches.UserId=Lunch.UserId) WHERE year(Lunch.SendDate)=? AND month(Lunch.SendDate)=? AND day(Lunch.SendDate)=?
- AND Lunch.UserId =?");
-
- $stmt->bind_param("sssssss", $year, $month, $day, $year, $month, $day, $UserId );
- if ($stmt->execute())
- return true;
- return false;
- }
- else if($whichtime=="Dinner")
- {
- $stmt = $this->con->prepare("UPDATE SharedDinners SET SharedDinners.Calories =?, SharedDinners.Protein =? WHERE year(SharedDinners.SendDate)=? AND
- month(SharedDinners.SendDate)=? AND day(SharedDinners.SendDate)=? AND UserId= ?");
- $stmt->bind_param("ddsssi", $Calories, $Protein, $year, $month, $day, $UserId );
- $stmt->execute();
- $stmt->close();
- $stmt = $this->con->prepare("UPDATE Dinner SET Dinner.SharedFoodsId=(SELECT SharedDinners.ParentSharedFoodsId
- FROM SharedDinners WHERE year(SharedDinners.SendDate)=? AND month(SharedDinners.SendDate)=? AND day(SharedDinners.SendDate)=?
- AND SharedDinners.UserId=Dinner.UserId) WHERE year(Dinner.SendDate)=? AND month(Dinner.SendDate)=? AND day(Dinner.SendDate)=? AND Dinner.UserId =?");
- $stmt->bind_param("ssssssi", $year, $month, $day, $year, $month, $day, $UserId );
- if ($stmt->execute())
- return true;
- return false;
- }
- else if($whichtime=="Drinks")
- {
- $stmt = $this->con->prepare("UPDATE Drinks SET Drinks.SharedFoodsId=(SELECT SharedDrinks.ParentSharedFoodsId
- FROM SharedDrinks WHERE year(SharedDrinks.SendDate)=? AND month(SharedDrinks.SendDate)=? AND day(SharedDrinks.SendDate)=?
- AND SharedDrinks.UserId=Drinks.UserId) WHERE year(Drinks.SendDate)=? AND month(Drinks.SendDate)=? AND day(Drinks.SendDate)=? AND Drinks.UserId =?");
- $stmt->bind_param("sssssss", $year, $month, $day, $year, $month, $day, $UserId );
- if ($stmt->execute())
- return true;
- return false;
- }
- else if($whichtime=="Snacks")
- {
- $stmt = $this->con->prepare("UPDATE Snacks SET Snacks.SharedFoodsId=(SELECT SharedSnacks.ParentSharedFoodsId
- FROM SharedSnacks WHERE year(SharedSnacks.SendDate)=? AND month(SharedSnacks.SendDate)=? AND day(SharedSnacks.SendDate)=? AND SharedSnacks.UserId=Snacks.UserId)
- WHERE year(Snacks.SendDate)=? AND month(Snacks.SendDate)=? AND day(Snacks.SendDate)=? AND Snacks.UserId =?");
- $stmt->bind_param("sssssss", $year, $month, $day, $year, $month, $day, $UserId );
- if ($stmt->execute())
- return true;
- return false;
- }
- return false;
-
- }
- function getAllSelectedFoods($UserId, $whichtime, $year, $month, $day){
- echo "hello";
- $stmt = $this->con->prepare("SELECT foodId, UserId, SendDate, Calories, Protein, Fat, Carbohydrates FROM ".$whichtime." WHERE UserId =?
- AND day(SendDate) =? AND year(SendDate)=? AND month(SendDate)=?");
- $stmt->bind_param("isss", $UserId, $day, $year, $month);
- $stmt->execute();
- $stmt->bind_result($foodId, $Userid, $Date, $Calories, $Protein, $Fat, $Carbohydrates);
- $users = array();
- while($stmt->fetch()){
- $temp = array();
- $temp['foodId'] = $foodId;
- $temp['UserId'] = $Userid;
- $temp['SendDate'] = $Date;
- $temp['Calories'] = $Calories;
- $temp['Protein'] = $Protein;
- $temp['Fat'] = $Fat;
- $temp['Carbohydrates'] = $Carbohydrates;
- array_push($users, $temp);
- }
- return $users;
- }
- function getAllSelectedFoodsPrieview($UserId, $whichtime){
- echo "hello";
- $stmt = $this->con->prepare("SELECT foodId, UserId, SendDate, Calories, Protein, Fat, Carbohydrates FROM ".$whichtime." WHERE SharedFoodsId =?");
- $stmt->bind_param("i", $UserId);
- $stmt->execute();
- $stmt->bind_result($foodId, $Userid, $Date, $Calories, $Protein, $Fat, $Carbohydrates);
- $users = array();
- while($stmt->fetch()){
- $temp = array();
- $temp['foodId'] = $foodId;
- $temp['UserId'] = $Userid;
- $temp['SendDate'] = $Date;
- $temp['Calories'] = $Calories;
- $temp['Protein'] = $Protein;
- $temp['Fat'] = $Fat;
- $temp['Carbohydrates'] = $Carbohydrates;
- array_push($users, $temp);
- }
- return $users;
- }
- function getAllSharedDiets($UserId, $SharedFoodListDatabase){
- $stmt = $this->con->prepare("SELECT ParentSharedFoodsId, UserId, SendDate, Calories, Protein, Fat, Carbohydrates FROM ".$SharedFoodListDatabase." WHERE UserId <>?");
- $stmt->bind_param("i", $UserId);
- $stmt->execute();
- $stmt->bind_result($ParentSharedFoodsId, $Userid, $Date, $Calories, $Protein, $Fat, $Carbohydrates);
- $users = array();
- while($stmt->fetch()){
- $temp = array();
- $temp['ParentSharedFoodsId'] = $ParentSharedFoodsId;
- $temp['UserId'] = $Userid;
- $temp['Date'] = $Date;
- $temp['Calories'] = $Calories;
- $temp['Protein'] = $Protein;
- $temp['Fat'] = $Fat;
- $temp['Carbohydrates'] = $Carbohydrates;
- array_push($users, $temp);
- }
- return $users;
- }
- function getAllFilteredSharedDiets($UserId, $SharedFoodListDatabase, $proteinbegin, $proteinend, $caloriesbegin, $caloriesend, $carbohydratesbegin,
- $carbohydratesend, $fatsbegin, $fatsend){
- $stmt = $this->con->prepare("SELECT ParentSharedFoodsId, UserId, SendDate, Calories, Protein, Fat, Carbohydrates FROM ".$SharedFoodListDatabase."
- WHERE SharedDinners.UserId <> ? AND SharedDinners.Calories BETWEEN ? AND ? AND SharedDinners.Carbohydrates BETWEEN ? AND ? AND SharedDinners.Protein BETWEEN ? AND ? AND SharedDinners.Fat BETWEEN ? AND ?");
- $stmt->bind_param("iiiiiiiii", $UserId, $caloriesbegin, $caloriesend, $carbohydratesbegin, $carbohydratesend, $proteinbegin, $proteinend, $fatsbegin, $fatsend );
- $stmt->execute();
- $stmt->bind_result($ParentSharedFoodsId, $Userid, $Date, $Calories, $Protein, $Fat, $Carbohydrates);
- $users = array();
- while($stmt->fetch()){
- $temp = array();
- $temp['ParentSharedFoodsId'] = $ParentSharedFoodsId;
- $temp['UserId'] = $Userid;
- $temp['Date'] = $Date;
- $temp['Calories'] = $Calories;
- $temp['Protein'] = $Protein;
- $temp['Fat'] = $Fat;
- $temp['Carbohydrates'] = $Carbohydrates;
- array_push($users, $temp);
- }
- return $users;
- }
- function qur( $value, $name)
- {
-
- $stmt = $this->con->prepare("SELECT id, name, email, gender FROM users WHERE " .$name. " = ?");
- $stmt->bind_param("s", $value);
- $stmt->execute();
- $stmt->bind_result($id, $name, $email, $gender);
- $users = array();
- while($stmt->fetch()){
- $temp = array();
- $temp['id'] = $id;
- $temp['name'] = $name;
- $temp['email'] = $email;
- $temp['gender'] = $gender;
- array_push($users, $temp);
- }
- //error_reporting();
- return $users;
- }
-
- //Method to check if email already exist
- function isUserExist($uid)
- {
- $stmt = $this->con->prepare("SELECT id FROM Users WHERE uid = ?");
- $stmt->bind_param("s", $uid);
- $stmt->execute();
- $stmt->store_result();
- return $stmt->num_rows > 0;
- }
-}
\ No newline at end of file
diff --git a/app/PHP_API_FILES/index.php b/app/PHP_API_FILES/index.php
deleted file mode 100644
index d6bb38d..0000000
--- a/app/PHP_API_FILES/index.php
+++ /dev/null
@@ -1,329 +0,0 @@
- [
- 'displayErrorDetails' => true
- ]
-]);
-
-
-//registering a new user
-$app->post('/register', function (Request $request, Response $response) {
- $requestData = $request->getParsedBody();
- $name = $requestData['name'];
- $email = $requestData['email'];
- $uid = $requestData['uid'];
-
- $db = new DbOperation();
- $responseData = array();
-
- $result = $db->registerUser($email, $uid, $name);
-
- if ($result == USER_CREATED) {
- $responseData['error'] = false;
- $responseData['message'] = 'Registered successfully';
- $responseData['user'] = $db->getUserByUid($uid);
- } elseif ($result == USER_CREATION_FAILED) {
- $responseData['error'] = true;
- $responseData['message'] = 'Some error occurred';
- } elseif ($result == USER_EXIST) {
- $responseData['error'] = true;
- $responseData['message'] = 'This email already exist, please login';
- }
-
- $response->getBody()->write(json_encode($responseData));
-});
-$app->post('/loginwithmail', function (Request $request, Response $response) {
- // $requestData = $request->getParsedBody();
- $passwrod = $requestData['password'];
- $email = $requestData['email'];
- $uid = $requestData['uid'];
-
- $db = new DbOperation();
- $responseData = array();
-
- $result = $db->registerUserwithmail($email, $uid, $passwrod);
-
- if ($result == USER_CREATED) {
- $responseData['error'] = false;
- $responseData['message'] = 'Registered successfully';
- // $responseData['user'] = $db->getUserByEmail($email);
- } elseif ($result == USER_CREATION_FAILED) {
- $responseData['error'] = true;
- $responseData['message'] = 'Some error occurred';
- } elseif ($result == USER_EXIST) {
- $responseData['error'] = true;
- $responseData['message'] = 'This email already exist, please login';
- }
-
- $response->getBody()->write(json_encode($responseData));
-});
-
-
-
-//user login route
-$app->post('/login', function (Request $request, Response $response) {
- if (isTheseParametersAvailable(array('email', 'password'))) {
- $requestData = $request->getParsedBody();
- $email = $requestData['email'];
- $password = $requestData['password'];
-
- $db = new DbOperation();
-
- $responseData = array();
-
- if ($db->userLogin($email, $password)) {
- $responseData['error'] = false;
- $responseData['user'] = $db->getUserByEmail($email);
- } else {
- $responseData['error'] = true;
- $responseData['message'] = 'Invalid email or password';
- }
-
- $response->getBody()->write(json_encode($responseData));
- }
-});
-$app->get('/getUserByUid', function (Request $request, Response $response) {
-
- $db = new DbOperation();
- $UserId = $request->getQueryParam('UserId');
- $responseData = array();
- $responseData['error'] = false;
- $responseData['message'] = 'Got succesffuly';
- $responseData['user'] = $db->getUserByUid($UserId);
- $response->getBody()->write(json_encode($responseData));
- });
-
-//getting all users
-$app->get('/users', function (Request $request, Response $response) {
- $db = new DbOperation();
- $users = $db->getAllUsers();
- $response->getBody()->write(json_encode(array("users" => $users)));
-});
-
-$app->get('/getAllSharedDiets', function (Request $request, Response $response) {
- $db = new DbOperation();
- $UserId = $request->getQueryParam('UserId');
- $SharedFoodListDatabase = $request->getQueryParam('SharedFoodListDatabase');
-
- $whichtime = $request->getQueryParam('whichtime');
- $users = $db->getAllSharedDiets($UserId, $SharedFoodListDatabase);
- $response->getBody()->write(json_encode(array("selectedFoodretrofits" => $users)));
-});
-$app->get('/getAllFilteredSharedDiets', function (Request $request, Response $response) {
- $db = new DbOperation();
- $UserId = $request->getQueryParam('UserId');
- $SharedFoodListDatabase = $request->getQueryParam('SharedFoodListDatabase');
- $proteinbegin = $request->getQueryParam('ProteinBegin');
- $proteinend = $request->getQueryParam('ProteinEnd');
- $caloriesbegin = $request->getQueryParam('CaloriesBegin');
- $caloriesend = $request->getQueryParam('CaloriesEnd');
- $carbohydratesbegin = $request->getQueryParam('CarbohydratesBegin');
- $carbohydratesend = $request->getQueryParam('CarbohydratesEnd');
- $fatsbegin = $request->getQueryParam('FatsBegin');
- $fatsend = $request->getQueryParam('FatsEnd');
- $users = $db->getAllFilteredSharedDiets($UserId, $SharedFoodListDatabase, $proteinbegin, $proteinend, $caloriesbegin, $caloriesend, $carbohydratesbegin,
- $carbohydratesend, $fatsbegin, $fatsend);
- $response->getBody()->write(json_encode(array("selectedFoodretrofits" => $users)));
-});
-//getting messages for a user
-$app->get('/messages/{id}', function (Request $request, Response $response) {
- $userid = $request->getAttribute('id');
- $db = new DbOperation();
- $messages = $db->getMessages($userid);
- $response->getBody()->write(json_encode(array("messages" => $messages)));
-});
-
-//updating a user
-$app->post('/update/{id}', function (Request $request, Response $response) {
- if (isTheseParametersAvailable(array('name', 'email', 'password', 'gender'))) {
- $id = $request->getAttribute('id');
-
- $requestData = $request->getParsedBody();
-
- $name = $requestData['name'];
- $email = $requestData['email'];
- $password = $requestData['password'];
- $gender = $requestData['gender'];
-
-
- $db = new DbOperation();
-
- $responseData = array();
-
- if ($db->updateProfile($id, $name, $email, $password, $gender)) {
- $responseData['error'] = false;
- $responseData['message'] = 'Updated successfully';
- $responseData['user'] = $db->getUserByEmail($email);
- } else {
- $responseData['error'] = true;
- $responseData['message'] = 'Not updated';
- }
-
- $response->getBody()->write(json_encode($responseData));
- }
-});
-
-
-//sending message to user
-$app->post('/sendmessage', function (Request $request, Response $response) {
- if (isTheseParametersAvailable(array('from', 'to', 'title', 'message'))) {
- $requestData = $request->getParsedBody();
- $from = $requestData['from'];
- $to = $requestData['to'];
- $title = $requestData['title'];
- $message = $requestData['message'];
-
- $db = new DbOperation();
-
- $responseData = array();
-
- if ($db->sendMessage($from, $to, $title, $message)) {
- $responseData['error'] = false;
- $responseData['message'] = 'Message sent successfully';
- } else {
- $responseData['error'] = true;
- $responseData['message'] = 'Could not send message';
- }
-
- $response->getBody()->write(json_encode($responseData));
- }
-});
-$app->get('/getSelectedFoods', function (Request $request, Response $response) {
- $UserId = $request->getQueryParam('UserId');
- $whichtime = $request->getQueryParam('whichtime');
- $year = $request->getQueryParam('year');
- $month = $request->getQueryParam('month');
- $day = $request->getQueryParam('day');
- $db = new DbOperation();
- $users = $db->getAllSelectedFoods($UserId, $whichtime, $year, $month, $day);
- $response->getBody()->write(json_encode(array("users" => $users)));
-});
-$app->get('/getSelectedFoodsPrieview', function (Request $request, Response $response) {
- $getParentSharedFoodsId = $request->getQueryParam('getParentSharedFoodsId');
- $foodselection = $request->getQueryParam('foodselection');
- $db = new DbOperation();
- $users = $db->getAllSelectedFoodsPrieview($getParentSharedFoodsId, $foodselection);
- $response->getBody()->write(json_encode(array("users" => $users)));
-});
-$app->get('/IsShared', function (Request $request, Response $response) {
- $UserId = $request->getQueryParam('UserId');
- $date = $request->getQueryParam('date');
- $whichtime = $request->getQueryParam('whichtime');
- $db = new DbOperation();
- $responseData = array();
- $result = $db->isShared($UserId, $whichtime, $date);
- if (!$result) {
- $responseData['error'] = false;
- echo "maziau";
- // echo $result;
- $responseData['message'] = 'notfound';
- // $responseData['user'] = $db->getUserByEmail($email);
- }
- else {
- echo "daugiau";
- $responseData['error'] = true;
- $responseData['message'] = 'Some error occurred';
- }
- $response->getBody()->write(json_encode($responseData));
-});
-
-$app->post('/addSelectedFood', function (Request $request, Response $response) {
- $requestData = $request->getParsedBody();
- $foodId = $requestData['foodId'];
- $UserId = $requestData['UserId'];
- $Date = $requestData['Date'];
- $Calories = $requestData['Calories'];
- $Protein = $requestData['Protein'];
- $Fat = $requestData['Fat'];
- $Carbohydrates = $requestData['Carbohydrates'];
- $whichtimee = $requestData['whichtime'];
- $sharedfoodsId = $requestData['sharedfoodId'];
-
- $db = new DbOperation();
- $responseData = array();
-
- $result = $db->addSelectedFood($foodId, $UserId, $Date, $Calories, $Protein, $Fat, $Carbohydrates, $whichtimee, $sharedfoodsId);
-
- if ($result == USER_CREATED) {
- $responseData['error'] = false;
- $responseData['message'] = 'Registered successfully';
- // $responseData['user'] = $db->getUserByEmail($email);
- } elseif ($result == USER_CREATION_FAILED) {
- $responseData['error'] = true;
- $responseData['message'] = 'Some error occurred';
- }
-
- $response->getBody()->write(json_encode($responseData));
-});
-$app->post('/addSharedList', function (Request $request, Response $response) {
- $requestData = $request->getParsedBody();
- $UserId = $requestData['UserId'];
- $Date = $requestData['Date'];
- $whichtime = $requestData['whichtime'];
- $SharedFoodListDatabase = $requestData['SharedFoodListDatabase'];
- $Calories = $requestData['Calories'];
- $Protein = $requestData['Protein'];
- $Fat = $requestData['Fat'];
- $Carbohydrates = $requestData['Carbohydrates'];
-
- $db = new DbOperation();
- $responseData = array();
-
- $canyoushare = $db->isShared($UserId, $whichtime, $Date);
- if(!$canyoushare){
- $result = $db->addSharedFoodList($UserId, $Date, $SharedFoodListDatabase, $Calories, $Protein, $Fat, $Carbohydrates );
- if ($result == USER_CREATED) {
- $updateresult = $db->updateFoods($UserId, $Date, $whichtime, $Calories, $Protein, $Fat, $Carbohydrates );
- echo $updateresult;
- $responseData['error'] = false;
- $responseData['message'] = 'Registered successfully';
- // $responseData['user'] = $db->getUserByEmail($email);
- } elseif ($result == USER_CREATION_FAILED) {
- $responseData['error'] = true;
- $responseData['message'] = 'Some error occurred';
- }
-}
-else
-{
- $db->updateFoods($UserId, $Date, $whichtime, $Calories, $Protein, $Fat, $Carbohydrates);
- $responseData['error'] = false;
- $responseData['message'] = 'cantinsertmore';
-}
-
- $response->getBody()->write(json_encode($responseData));
-});
-
-//function to check parameters
-function isTheseParametersAvailable($required_fields)
-{
- $error = false;
- $error_fields = "";
- $request_params = $_REQUEST;
-
- foreach ($required_fields as $field) {
- if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) <= 0) {
- $error = true;
- $error_fields .= $field . ', ';
- }
- }
-
- if ($error) {
- $response = array();
- $response["error"] = true;
- $response["message"] = 'Required field(s) ' . substr($error_fields, 0, -2) . ' is missing or empty';
- echo json_encode($response);
- return false;
- }
- return true;
-}
-
-
-$app->run();
\ No newline at end of file
diff --git a/app/build.gradle b/app/build.gradle
index 6b05cf1..c8af6ca 100644
--- a/app/build.gradle
+++ b/app/build.gradle
@@ -1,12 +1,13 @@
apply plugin: 'com.android.application'
android {
- compileSdkVersion 26
+ compileSdkVersion 27
defaultConfig {
applicationId "udacityteam.healthapp"
minSdkVersion 16
- targetSdkVersion 26
+ targetSdkVersion 27
versionCode 1
+ multiDexEnabled true
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
@@ -28,48 +29,73 @@ android {
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
- implementation 'com.android.support:appcompat-v7:26.1.0'
- implementation "android.arch.lifecycle:extensions:1.1.0"
- // alternatively, just ViewModel
- implementation "android.arch.lifecycle:viewmodel:1.1.0"
- // alternatively, just LiveData
- implementation "android.arch.lifecycle:livedata:1.1.0"
- implementation 'com.android.support:design:26.1.0'
- compile 'com.rengwuxian.materialedittext:library:2.1.4'
+ // UI/ UX
+ implementation 'com.android.support:appcompat-v7:27.1.1'
+ implementation 'com.android.support:design:27.1.1'
+ implementation 'com.android.support:cardview-v7:27.1.1'
+ implementation 'com.prolificinteractive:material-calendarview:1.4.3'
+ implementation 'com.rengwuxian.materialedittext:library:2.1.4'
+ implementation 'com.android.support.constraint:constraint-layout:1.1.2'
+ implementation 'com.github.rey5137:material:1.2.4'
+
+ //Android Architecture Components
+
+ implementation "android.arch.lifecycle:extensions:1.1.1"
+ implementation "android.arch.lifecycle:viewmodel:1.1.1"
+ implementation "android.arch.lifecycle:livedata:1.1.1"
+ annotationProcessor "android.arch.persistence.room:compiler:1.1.1"
+
+ // Retrofit/RxJava (Networking)
+ compile 'io.reactivex.rxjava2:rxandroid:2.0.2'
+ compile 'io.reactivex:rxandroid:1.2.1'
+
+ compile 'io.reactivex.rxjava2:rxjava:2.1.10'
+ compile 'com.squareup.retrofit2:adapter-rxjava:2.2.0'
+ implementation 'com.squareup.okhttp3:logging-interceptor:3.10.0'
+ compile 'com.squareup.retrofit2:retrofit:2.4.0'
+ compile 'com.squareup.retrofit2:converter-gson:2.4.0'
+
+ //Dagger2
+ implementation 'com.google.dagger:dagger-android-support:2.15'
+ annotationProcessor 'com.google.dagger:dagger-android-processor:2.15'
+ annotationProcessor 'com.google.dagger:dagger-compiler:2.16'
+ implementation 'com.google.dagger:dagger:2.16'
+ implementation 'com.google.dagger:dagger-android:2.15'
+
+ implementation "android.arch.persistence.room:runtime:1.1.1"
+ annotationProcessor "android.arch.persistence.room:compiler:1.1.1"
+
+ implementation "android.arch.persistence.room:rxjava2:1.1.1"
+ // Test helpers
+ testImplementation "android.arch.persistence.room:testing:1.1.1"
+
+
+
+
compile 'com.jakewharton:butterknife:8.8.1'
- compile 'com.google.android.gms:play-services-auth:11.8.0'
+ compile 'com.google.android.gms:play-services-auth:15.0.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
- compile 'com.prolificinteractive:material-calendarview:1.4.3'
- implementation 'com.google.firebase:firebase-auth:11.8.0'
+ implementation 'com.google.firebase:firebase-auth:16.0.2'
+
+
- implementation 'com.android.support.constraint:constraint-layout:1.0.2'
- compile 'com.github.rey5137:material:1.2.4'
//noinspection GradleCompatible
- implementation 'com.google.firebase:firebase-database:11.8.0'
- implementation 'com.google.firebase:firebase-core:11.8.0'
- compile 'com.squareup.retrofit2:retrofit:2.2.0'
- compile 'com.squareup.retrofit2:converter-gson:2.2.0'
- compile 'com.google.firebase:firebase-firestore:11.8.0'
- implementation 'com.google.firebase:firebase-storage:11.8.0'
+ implementation 'com.google.firebase:firebase-database:16.0.1'
+ implementation 'com.google.firebase:firebase-core:16.0.1'
+
+ compile 'com.google.firebase:firebase-firestore:17.0.3'
+ implementation 'com.google.firebase:firebase-storage:16.0.1'
testImplementation 'junit:junit:4.12'
- implementation 'com.android.support:cardview-v7:26.1.0'
- compile 'com.google.firebase:firebase-auth:11.8.0'
- compile 'com.google.android.gms:play-services-auth:11.8.0'
- compile 'com.firebaseui:firebase-ui-database:1.2.0'
- implementation 'com.firebaseui:firebase-ui-auth:3.0.0'
+ compile 'com.google.firebase:firebase-auth:16.0.2'
+ compile 'com.google.android.gms:play-services-auth:15.0.1'
+ compile 'com.firebaseui:firebase-ui-database:4.0.0'
+ implementation 'com.firebaseui:firebase-ui-auth:4.0.0'
implementation 'io.apptik.widget:multislider:1.3'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
- compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
- compile 'io.reactivex:rxandroid:1.2.1'
-
-// Because RxAndroid releases are few and far between, it is recommended you also
-// explicitly depend on RxJava's latest version for bug fixes and new features.
- compile 'io.reactivex.rxjava2:rxjava:2.1.8'
- compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
}
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 9e7bb70..2bd8794 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -13,7 +13,7 @@
android:supportsRtl="true"
android:theme="@style/AppTheme">
diff --git a/app/src/main/java/udacityteam/healthapp/Model/OneSharedFoodProductsListRetrofit.java b/app/src/main/java/udacityteam/healthapp/Model/OneSharedFoodProductsListRetrofit.java
index 420e19c..64fbac9 100644
--- a/app/src/main/java/udacityteam/healthapp/Model/OneSharedFoodProductsListRetrofit.java
+++ b/app/src/main/java/udacityteam/healthapp/Model/OneSharedFoodProductsListRetrofit.java
@@ -1,16 +1,26 @@
package udacityteam.healthapp.Model;
+import android.arch.persistence.room.Entity;
+import android.arch.persistence.room.PrimaryKey;
+import android.arch.persistence.room.TypeConverters;
import android.os.Parcel;
import android.os.Parcelable;
+import com.google.gson.annotations.SerializedName;
+
import java.sql.Timestamp;
import java.util.ArrayList;
+import udacityteam.healthapp.completeRedesign.DataConverterStep;
+import udacityteam.healthapp.models.User;
+
/**
* Created by vvost on 12/29/2017.
*/
-
+@Entity
public class OneSharedFoodProductsListRetrofit implements Parcelable {
+ @PrimaryKey(autoGenerate = true)
+ private int roomId;
private String UserId;
private String Date;
private Integer ParentSharedFoodsId;
@@ -18,7 +28,45 @@ public class OneSharedFoodProductsListRetrofit implements Parcelable {
private float Protein;
private float Fat;
private float Carbohydrates;
+ private String displayname;
+ private String mail;
+ @TypeConverters(DataConverterStep.class)
+ private UserProfile userProfile;
+ public OneSharedFoodProductsListRetrofit() {
+ }
+
+ public int getRoomId() {
+ return roomId;
+ }
+
+ public void setRoomId(int roomId) {
+ this.roomId = roomId;
+ }
+
+ public UserProfile getUserProfile() {
+ return userProfile;
+ }
+
+ public void setUserProfile(UserProfile userProfile) {
+ this.userProfile = userProfile;
+ }
+
+ public String getDisplayname() {
+ return displayname;
+ }
+
+ public void setDisplayname(String displayname) {
+ this.displayname = displayname;
+ }
+
+ public String getMail() {
+ return mail;
+ }
+
+ public void setMail(String mail) {
+ this.mail = mail;
+ }
protected OneSharedFoodProductsListRetrofit(Parcel in) {
UserId = in.readString();
@@ -103,6 +151,7 @@ public void setUserId(String userId) {
}
+
@Override
public int describeContents() {
return 0;
diff --git a/app/src/main/java/udacityteam/healthapp/Model/SelectedFoodretrofit.java b/app/src/main/java/udacityteam/healthapp/Model/SelectedFoodretrofit.java
index 76e1eb0..f9bcbda 100644
--- a/app/src/main/java/udacityteam/healthapp/Model/SelectedFoodretrofit.java
+++ b/app/src/main/java/udacityteam/healthapp/Model/SelectedFoodretrofit.java
@@ -22,6 +22,11 @@ public class SelectedFoodretrofit implements Parcelable {
private float Protein;
private float Fat;
private float Carbohydrates;
+ // private String mail;
+ // private String
+
+
+
diff --git a/app/src/main/java/udacityteam/healthapp/Model/UserProfile.java b/app/src/main/java/udacityteam/healthapp/Model/UserProfile.java
new file mode 100644
index 0000000..b25e100
--- /dev/null
+++ b/app/src/main/java/udacityteam/healthapp/Model/UserProfile.java
@@ -0,0 +1,31 @@
+package udacityteam.healthapp.Model;
+
+public class UserProfile {
+
+ private String mail;
+ private String displayname;
+
+ public UserProfile(String mail, String displayname) {
+ this.mail = mail;
+ this.displayname = displayname;
+ }
+
+ public UserProfile() {
+ }
+
+ public String getMail() {
+ return mail;
+ }
+
+ public void setMail(String mail) {
+ this.mail = mail;
+ }
+
+ public String getDisplayname() {
+ return displayname;
+ }
+
+ public void setDisplayname(String displayname) {
+ this.displayname = displayname;
+ }
+}
diff --git a/app/src/main/java/udacityteam/healthapp/Model/UserRetrofitGood.java b/app/src/main/java/udacityteam/healthapp/Model/UserRetrofitGood.java
index c5d805e..dfb1de7 100644
--- a/app/src/main/java/udacityteam/healthapp/Model/UserRetrofitGood.java
+++ b/app/src/main/java/udacityteam/healthapp/Model/UserRetrofitGood.java
@@ -1,19 +1,30 @@
package udacityteam.healthapp.Model;
+import android.arch.persistence.room.Entity;
+import android.arch.persistence.room.PrimaryKey;
+
/**
* Created by vvost on 1/27/2018.
*/
-
+@Entity
public class UserRetrofitGood {
-
+ @PrimaryKey(autoGenerate = true)
+ private int roomId;
private Integer id;
private String mail;
private String uid;
private String displayname;
+ public int getRoomId() {
+ return roomId;
+ }
+
+ public void setRoomId(int roomId) {
+ this.roomId = roomId;
+ }
- public UserRetrofitGood(int id, String mail, String uid, String displayname) {
+ public UserRetrofitGood(int id, String mail, String uid, String displayname) {
this.id = id;
this.mail = mail;
this.uid = uid;
diff --git a/app/src/main/java/udacityteam/healthapp/Model/Userretrofit.java b/app/src/main/java/udacityteam/healthapp/Model/Userretrofit.java
index ae0e222..d1bcc81 100644
--- a/app/src/main/java/udacityteam/healthapp/Model/Userretrofit.java
+++ b/app/src/main/java/udacityteam/healthapp/Model/Userretrofit.java
@@ -9,9 +9,7 @@ public class Userretrofit {
private int id;
private String name;
private String email;
- private String password;
private String uid;
- private String gender;
public String getUid() {
return uid;
@@ -23,27 +21,7 @@ public Userretrofit(String name, String email, String uid) {
this.uid = uid;
}
- public Userretrofit(String name, String email, String password, String gender) {
- this.name = name;
- this.email = email;
- this.password = password;
- this.gender = gender;
- }
- public Userretrofit(int id, String name, String email, String gender){
- this.id = id;
- this.name = name;
- this.email = email;
- this.gender = gender;
- }
-
- public Userretrofit(int id, String name, String email, String password, String gender) {
- this.id = id;
- this.name = name;
- this.email = email;
- this.password = password;
- this.gender = gender;
- }
public int getId() {
return id;
@@ -57,11 +35,4 @@ public String getEmail() {
return email;
}
- public String getPassword(){
- return password;
- }
-
- public String getGender() {
- return gender;
- }
}
diff --git a/app/src/main/java/udacityteam/healthapp/Model/_0.java b/app/src/main/java/udacityteam/healthapp/Model/_0.java
new file mode 100644
index 0000000..a17fbfa
--- /dev/null
+++ b/app/src/main/java/udacityteam/healthapp/Model/_0.java
@@ -0,0 +1,30 @@
+package udacityteam.healthapp.Model;
+
+import com.google.gson.annotations.Expose;
+import com.google.gson.annotations.SerializedName;
+
+public class _0 {
+
+ @SerializedName("displayname")
+ @Expose
+ private String displayname;
+ @SerializedName("mail")
+ @Expose
+ private String mail;
+
+ public String getDisplayname() {
+ return displayname;
+ }
+
+ public void setDisplayname(String displayname) {
+ this.displayname = displayname;
+ }
+
+ public String getMail() {
+ return mail;
+ }
+
+ public void setMail(String mail) {
+ this.mail = mail;
+ }
+}
diff --git a/app/src/main/java/udacityteam/healthapp/Network/PHPService.java b/app/src/main/java/udacityteam/healthapp/Network/PHPService.java
index b7e613e..71115b6 100644
--- a/app/src/main/java/udacityteam/healthapp/Network/PHPService.java
+++ b/app/src/main/java/udacityteam/healthapp/Network/PHPService.java
@@ -1,7 +1,13 @@
package udacityteam.healthapp.Network;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+
import java.sql.Timestamp;
+import java.util.concurrent.TimeUnit;
+import okhttp3.OkHttpClient;
+import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
@@ -17,46 +23,29 @@
import udacityteam.healthapp.Model.SelectedFoodretrofitarray;
import udacityteam.healthapp.Model.SharedFoodProductsRetrofit;
import udacityteam.healthapp.Model.Usersretrofit;
+import udacityteam.healthapp.completeRedesign.Data.Networking.API.LiveDataCallAdapterFactory;
import static udacityteam.healthapp.PHP_Retrofit_API.APIUrl.BASE_URL;
public interface PHPService {
- @FormUrlEncoded
- @POST("register")
- Observable createUser(
- @Field("name") String name,
- @Field("email") String email,
- @Field("uid") String uid);
-
-
- @FormUrlEncoded
- @POST("login")
- Observable userLogin(
- @Field("email") String email,
- @Field("password") String password
- );
- @FormUrlEncoded
- @POST("loginwithmail")
- Observable userLoginwithmail(
- @Field("email") String email,
- @Field("password") String password,
- @Field("uid") String uid
- );
-
- @FormUrlEncoded
- @POST("addSelectedFood")
- Observable addSelectedFood(
- @Field("foodId") String foodId,
- @Field("UserId") Integer UserId,
- @Field("Date") Timestamp Date,
- @Field("Calories") Float Calories,
- @Field("Protein") Float Protein,
- @Field("Fat") Float Fat,
- @Field("Carbohydrates") Float Carbohyrates,
- @Field("whichtime") String whichtime,
- @Field("sharedfoodId") Integer sharedFoodId
- );
+ public static final String BASE_URL = "http://app.wellbranding.com/";
+
+
+@FormUrlEncoded
+@POST("addSelectedFood")
+Call addSelectedFood(
+ @Field("foodId") String foodId,
+ @Field("foodName") String foodName,
+ @Field("UserId") Integer UserId,
+ @Field("Date") Timestamp Date,
+ @Field("Calories") Float Calories,
+ @Field("Protein") Float Protein,
+ @Field("Fat") Float Fat,
+ @Field("Carbohydrates") Float Carbohyrates,
+ @Field("whichtime") String whichtime,
+ @Field("sharedfoodId") Integer sharedFoodId
+);
@FormUrlEncoded
@POST("addSharedList")
Observable addSharedList(
@@ -75,14 +64,6 @@ Observable getCurrentUser(
@Query("UserId") String UserId
);
-// @GET("getSelectedFoods")
-// Observable getselectedfoods(
-// @Query("UserId") Integer UserId,
-// @Query("whichtime") String whichtime,
-// @Query("year") String year,
-// @Query("month") String month,
-// @Query("day") String day
-// );
@GET("getSelectedFoods")
Observable getselectedfoods(
@Query("UserId") Integer UserId,
@@ -142,12 +123,26 @@ Call getqur(
class Factory {
public static PHPService create() {
+ Gson gson = new GsonBuilder()
+ .setLenient()
+ .create();
+ HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
+ interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
+ OkHttpClient client = new OkHttpClient.Builder()
+ .addInterceptor(interceptor)
+ .connectTimeout(30, TimeUnit.SECONDS)
+ .writeTimeout(30, TimeUnit.SECONDS)
+ .readTimeout(10, TimeUnit.SECONDS)
+ .build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
- .addConverterFactory(GsonConverterFactory.create())
+ .addConverterFactory(GsonConverterFactory.create(gson))
+ .addCallAdapterFactory(new LiveDataCallAdapterFactory())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
+ .client(client)
.build();
return retrofit.create(PHPService.class);
+
}
}
}
diff --git a/app/src/main/java/udacityteam/healthapp/PHP_Retrofit_API/APIService.java b/app/src/main/java/udacityteam/healthapp/PHP_Retrofit_API/APIService.java
index 583c0e5..5ec0120 100644
--- a/app/src/main/java/udacityteam/healthapp/PHP_Retrofit_API/APIService.java
+++ b/app/src/main/java/udacityteam/healthapp/PHP_Retrofit_API/APIService.java
@@ -47,13 +47,14 @@ Call userLoginwithmail(
@POST("addSelectedFood")
Call addSelectedFood(
@Field("foodId") String foodId,
+ @Field("foodName") String foodName,
@Field("UserId") Integer UserId,
@Field("Date") Timestamp Date,
@Field("Calories") Float Calories,
@Field("Protein") Float Protein,
@Field("Fat") Float Fat,
@Field("Carbohydrates") Float Carbohyrates,
- @Field("whichtime") String whichtime,
+ @Field("whichtime") String whichtime,
@Field("sharedfoodId") Integer sharedFoodId
);
@FormUrlEncoded
diff --git a/app/src/main/java/udacityteam/healthapp/activities/BaseActivity.java b/app/src/main/java/udacityteam/healthapp/activities/BaseActivity.java
new file mode 100644
index 0000000..68f6f6f
--- /dev/null
+++ b/app/src/main/java/udacityteam/healthapp/activities/BaseActivity.java
@@ -0,0 +1,202 @@
+package udacityteam.healthapp.activities;
+
+/**
+ * Created by vvost on 12/29/2017.
+ */
+import android.app.Fragment;
+import android.app.FragmentManager;
+import android.arch.lifecycle.ViewModelProvider;
+import android.arch.lifecycle.ViewModelProviders;
+import android.support.v7.app.AppCompatActivity;
+import android.os.Bundle;
+import android.content.Intent;
+import android.support.design.widget.Snackbar;
+import android.util.Log;
+import android.view.View;
+import android.widget.Button;
+import android.widget.Toast;
+
+import com.google.android.gms.auth.api.signin.GoogleSignIn;
+import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
+import com.google.android.gms.auth.api.signin.GoogleSignInClient;
+import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
+import com.google.android.gms.common.api.ApiException;
+import com.google.android.gms.tasks.Task;
+import com.google.firebase.auth.AuthCredential;
+import com.google.firebase.auth.FirebaseAuth;
+import com.google.firebase.auth.FirebaseUser;
+import com.google.firebase.auth.GoogleAuthProvider;
+
+import javax.inject.Inject;
+
+import dagger.android.AndroidInjection;
+import udacityteam.healthapp.Model.Userretrofit;
+import udacityteam.healthapp.R;
+
+
+/**
+ * Demonstrate Firebase Authentication using a Google ID Token.
+ */
+public class BaseActivity extends AppCompatActivity implements
+ View.OnClickListener {
+
+ private static final String TAG = "GoogleActivity";
+ private static final int RC_SIGN_IN = 9001;
+ private static final String BACK_STACK_ROOT_TAG_LOGIN = "login";
+
+ // [START declare_auth]
+ private FirebaseAuth mAuth;
+
+ // [END declare_auth]
+
+ private GoogleSignInClient mGoogleSignInClient;
+
+ @Inject
+ ViewModelProvider.Factory ViewModelFactory;
+
+ LoginRegisterViewModel viewModel;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ AndroidInjection.inject(this);
+ mAuth = FirebaseAuth.getInstance();
+ GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
+ .requestIdToken("1025887070439-pa8ivq2h24eigj8vv8h66e43ng7fgefh.apps.googleusercontent.com")
+ .requestEmail()
+ .build();
+ mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.register_activity_home);
+ findViewById(R.id.sign_in_button).setOnClickListener(this);
+
+ viewModel = ViewModelProviders.of(this, ViewModelFactory).
+ get(LoginRegisterViewModel.class);
+
+ Button registermail = findViewById(R.id.mailregister);
+ Button loginmail = findViewById(R.id.mailogin);
+
+
+ registermail.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+
+ RegisterWithMailFragment fragment = new RegisterWithMailFragment();
+ android.support.v4.app.FragmentManager fragmentManager = BaseActivity.this.getSupportFragmentManager();
+ fragmentManager.popBackStack(BACK_STACK_ROOT_TAG_LOGIN, FragmentManager.POP_BACK_STACK_INCLUSIVE);
+ fragmentManager.beginTransaction().
+ replace(R.id.fragmentContainer, fragment)
+ .addToBackStack(BACK_STACK_ROOT_TAG_LOGIN)
+ .commit();
+ fragmentManager.executePendingTransactions();
+// Intent intent = new Intent(BaseActivity.this, RegisterWithMailPasword.class);
+// startActivity(intent);
+ }
+ });
+ loginmail.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ Intent intent = new Intent(BaseActivity.this, LoginWithMailPasword.class);
+ startActivity(intent);
+ }
+ });
+
+ }
+
+ // [START on_start_check_user]
+ @Override
+ public void onStart() {
+ super.onStart();
+ FirebaseUser currentUser = mAuth.getCurrentUser();
+ updateUI(currentUser);
+ }
+ // [END on_start_check_user]
+
+ // [START onactivityresult]
+ @Override
+ public void onActivityResult(int requestCode, int resultCode, Intent data) {
+ super.onActivityResult(requestCode, resultCode, data);
+
+ // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
+ if (requestCode == RC_SIGN_IN) {
+ Task task = GoogleSignIn.getSignedInAccountFromIntent(data);
+ try {
+ // Google Sign In was successful, authenticate with Firebase
+ GoogleSignInAccount account = task.getResult(ApiException.class);
+ firebaseAuthWithGoogle(account);
+ } catch (ApiException e) {
+ // Google Sign In failed, update UI appropriately
+ Log.w(TAG, "Google sign in failed", e);
+ // [START_EXCLUDE]
+ updateUI(null);
+ // [END_EXCLUDE]
+ }
+ }
+ }
+ // [END onactivityresult]
+
+ // [START auth_with_google]
+ private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
+ Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
+ AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
+ mAuth.signInWithCredential(credential)
+ .addOnCompleteListener(this, task -> {
+ if (task.isSuccessful()) {
+ final FirebaseUser user = mAuth.getCurrentUser();
+ // Sign in success, update UI with the signed-in user's information
+ if(user!=null) {
+
+ Userretrofit retrofituser = new Userretrofit(user.getDisplayName(), user.getEmail(), mAuth.getCurrentUser().getUid());
+ viewModel.getRegisterWithGoogleSignInResponse(retrofituser).observe(this, result->
+ {
+ if(result!=null)
+ if(!result.getError())
+ {
+ Intent intent = new Intent(BaseActivity.this, MainActivity.class);
+ startActivity(intent);
+ finish();
+ }
+ else
+ {
+ Toast.makeText(this, result.getMessage(), Toast.LENGTH_SHORT).show();
+ }
+ });
+
+ } else {
+ Log.w(TAG, "signInWithCredential:failure", task.getException());
+ Snackbar.make(findViewById(R.id.main_layout), "Authentication Failed.", Snackbar.LENGTH_SHORT).show();
+ updateUI(null);
+ }
+ }
+ });}
+
+ private void signIn() {
+ Intent signInIntent = mGoogleSignInClient.getSignInIntent();
+ startActivityForResult(signInIntent, RC_SIGN_IN);
+ }
+
+
+
+ private void updateUI(FirebaseUser user) {
+ if (user != null && user.isEmailVerified()) {
+ Intent intent = new Intent(BaseActivity.this, MainActivity.class);
+ startActivity(intent);
+ }
+ else
+ if(user!=null && !user.isEmailVerified())
+ {
+ //TODO
+ //Possibly add Verification button in MainActivity
+ }
+ }
+
+ @Override
+ public void onClick(View v) {
+ int i = v.getId();
+ if (i == R.id.sign_in_button) {
+ signIn();
+ }
+
+ }
+}
+
+
diff --git a/app/src/main/java/udacityteam/healthapp/activities/CommunityActivities/CommunityFoodListDisplayFragment0MVVMViewModel.java b/app/src/main/java/udacityteam/healthapp/activities/CommunityActivities/CommunityFoodListDisplayFragment0MVVMViewModel.java
index f23e4e4..3350d43 100644
--- a/app/src/main/java/udacityteam/healthapp/activities/CommunityActivities/CommunityFoodListDisplayFragment0MVVMViewModel.java
+++ b/app/src/main/java/udacityteam/healthapp/activities/CommunityActivities/CommunityFoodListDisplayFragment0MVVMViewModel.java
@@ -31,6 +31,7 @@
import udacityteam.healthapp.Model.SelectedFoodretrofit;
import udacityteam.healthapp.Model.SelectedFoodretrofitarray;
import udacityteam.healthapp.Model.SharedFoodProductsRetrofit;
+import udacityteam.healthapp.Model.UserProfile;
import udacityteam.healthapp.Network.PHPService;
import udacityteam.healthapp.PHP_Retrofit_API.APIService;
import udacityteam.healthapp.PHP_Retrofit_API.APIUrl;
@@ -64,11 +65,6 @@ public class CommunityFoodListDisplayFragment0MVVMViewModel extends AndroidViewM
public MutableLiveData> mutableLiveData = new MutableLiveData<>();
ApplicationController application = null;
-// public CommunityFoodListDisplayFragment0MVVMViewModel(Context context, DataListener dataListener) {
-// // this.selectedFoodretrofit = repository;
-// this.dataListener = dataListener;
-// this.context = context;
-// }
public CommunityFoodListDisplayFragment0MVVMViewModel(Application application)
{
super(application);
@@ -93,6 +89,12 @@ public void LoadFoodList( String SharedFoodListDatabase)
.subscribe(new Subscriber() {
@Override
public void onCompleted() {
+ for(int i=0;i< selectedFoodretrofits.size(); i++)
+ {
+ selectedFoodretrofits.get(i).setUserProfile(new UserProfile(
+ selectedFoodretrofits.get(i).getMail(), selectedFoodretrofits.get(i).getDisplayname()
+ ));
+ }
Log.d("aryra", String.valueOf(selectedFoodretrofits.size()));
InitSelectedfoods(selectedFoodretrofits);
// dataListener.onRepositoriesChanged(selectedFoodretrofits);
diff --git a/app/src/main/java/udacityteam/healthapp/activities/CommunityActivities/CommunityFoodListsDisplayFragment0.java b/app/src/main/java/udacityteam/healthapp/activities/CommunityActivities/CommunityFoodListsDisplayFragment0.java
index 8ab41e3..6cbbc86 100644
--- a/app/src/main/java/udacityteam/healthapp/activities/CommunityActivities/CommunityFoodListsDisplayFragment0.java
+++ b/app/src/main/java/udacityteam/healthapp/activities/CommunityActivities/CommunityFoodListsDisplayFragment0.java
@@ -157,6 +157,7 @@ private void RetrofitList()
public void onResponse(Call call, Response response) {
mAdapter = new SharedFoodListsAdapter(response.body().
getSelectedFoodretrofits(), side);
+ Log.d("important", response.body().getSelectedFoodretrofits().get(0).getUserProfile().getDisplayname());
mRecyclerView.setAdapter(mAdapter);
}
diff --git a/app/src/main/java/udacityteam/healthapp/activities/CommunityActivities/CommunityFoodListsDisplayFragment0MVVM.java b/app/src/main/java/udacityteam/healthapp/activities/CommunityActivities/CommunityFoodListsDisplayFragment0MVVM.java
index 2dcd175..8b8004a 100644
--- a/app/src/main/java/udacityteam/healthapp/activities/CommunityActivities/CommunityFoodListsDisplayFragment0MVVM.java
+++ b/app/src/main/java/udacityteam/healthapp/activities/CommunityActivities/CommunityFoodListsDisplayFragment0MVVM.java
@@ -128,36 +128,6 @@ public void onClick(View view) {
}
-// @Override
-// public View onCreateView(LayoutInflater inflater, ViewGroup container,
-// Bundle savedInstanceState) {
-// View rootView = inflater.inflate(R.layout.community_list_fragment, container, false);
-// rootView.setTag(TAG);
-// // foodList = database.getReference("MainFeed").child(value).child("SharedDiets");
-//
-// mRecyclerView = rootView.findViewById(R.id.recyclerView);
-// listodydis = (TextView) rootView.findViewById(R.id.listodydis);
-// progressBar = rootView.findViewById(R.id.progressbar);
-// filterData = rootView.findViewById(R.id.filterdata);
-// test = rootView.findViewById(R.id.test);
-// if(side!=null)
-// {
-// Log.d("pabvyko", "paby");
-// }
-// filterData.setOnClickListener(new View.OnClickListener() {
-// @Override
-// public void onClick(View view) {
-// Intent intent = new Intent(getActivity(), FilterActivity.class);
-// intent.putExtra("SharedFoodListDatabase", SharedFoodListDatabase);
-// startActivity(intent);
-// }
-// });
-//
-// RetrofitList();
-//
-//
-// return rootView;
-// }
public void LoadFoodListMutable()
{
communityListFragmentBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
diff --git a/app/src/main/java/udacityteam/healthapp/activities/CommunityActivities/CommunityList.java b/app/src/main/java/udacityteam/healthapp/activities/CommunityActivities/CommunityList.java
index bd1969e..f1259c0 100644
--- a/app/src/main/java/udacityteam/healthapp/activities/CommunityActivities/CommunityList.java
+++ b/app/src/main/java/udacityteam/healthapp/activities/CommunityActivities/CommunityList.java
@@ -17,13 +17,26 @@
import android.view.MenuItem;
import android.view.View;
+import javax.inject.Inject;
+
+import dagger.android.AndroidInjection;
+import dagger.android.AndroidInjector;
+import dagger.android.DispatchingAndroidInjector;
+import dagger.android.support.HasSupportFragmentInjector;
import udacityteam.healthapp.R;
-public class CommunityList extends AppCompatActivity {
+public class CommunityList extends AppCompatActivity implements HasSupportFragmentInjector {
// Resources
Resources res;
+ @Inject
+ DispatchingAndroidInjector dispatchingAndroidInjector;
+ @Override
+ public AndroidInjector supportFragmentInjector() {
+ return dispatchingAndroidInjector;
+ }
+
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
@@ -43,6 +56,7 @@ public class CommunityList extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
+ AndroidInjection.inject(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
res = getResources();
@@ -136,7 +150,7 @@ public CharSequence getPageTitle(int position) {
public Fragment getItem(int position) {
switch (position) {
case 0:
- return CommunityFoodListsDisplayFragment0MVVM.newInstance(queryParam);
+ return SharedFoodListFragmentNetwork.newInstance(queryParam);
case 1:
return new CommunityFoodListsDisplayFragment1();
case 2:
diff --git a/app/src/main/java/udacityteam/healthapp/activities/CommunityActivities/SectionsPagerAdapter.java b/app/src/main/java/udacityteam/healthapp/activities/CommunityActivities/SectionsPagerAdapter.java
deleted file mode 100644
index b754f43..0000000
--- a/app/src/main/java/udacityteam/healthapp/activities/CommunityActivities/SectionsPagerAdapter.java
+++ /dev/null
@@ -1,51 +0,0 @@
-package udacityteam.healthapp.activities.CommunityActivities;
-
-import android.os.Bundle;
-import android.support.v4.app.Fragment;
-import android.support.v4.app.FragmentManager;
-import android.support.v4.app.FragmentPagerAdapter;
-
-/**
- * Created by vvost on 2/11/2018.
- */
-
-public class SectionsPagerAdapter extends FragmentPagerAdapter {
- private String[] tabTitles;
- private Bundle queryParam;
-
- public SectionsPagerAdapter(FragmentManager fm, String[] tabTitles, Bundle qureryparam) {
- super(fm);
- this.tabTitles = tabTitles;
- this.queryParam = qureryparam;
- }
-
- @Override
- public CharSequence getPageTitle(int position) {
- return tabTitles[position];
- }
-
- @Override
- public Fragment getItem(int position) {
- switch (position) {
- case 0:
- CommunityFoodListsDisplayFragment0MVVM communityFoodListsDisplayFragment0 = new CommunityFoodListsDisplayFragment0MVVM();
-// communityFoodListsDisplayFragment0.setArguments(queryParam);
- return communityFoodListsDisplayFragment0;
- case 1:
- return new CommunityFoodListsDisplayFragment1();
- case 2:
- return new CommunityFoodListsDisplayFragment2();
- default:
- return null;
-
- }
- }
-
- @Override
- public int getCount() {
- // Show 3 total pages.
- return 3;
- }
-
-
-}
\ No newline at end of file
diff --git a/app/src/main/java/udacityteam/healthapp/activities/CommunityActivities/SharedFoodListFragmentNetwork.java b/app/src/main/java/udacityteam/healthapp/activities/CommunityActivities/SharedFoodListFragmentNetwork.java
new file mode 100644
index 0000000..38ee8ab
--- /dev/null
+++ b/app/src/main/java/udacityteam/healthapp/activities/CommunityActivities/SharedFoodListFragmentNetwork.java
@@ -0,0 +1,180 @@
+package udacityteam.healthapp.activities.CommunityActivities;
+
+import android.app.FragmentManager;
+import android.arch.lifecycle.ViewModelProvider;
+import android.arch.lifecycle.ViewModelProviders;
+import android.content.Context;
+import android.databinding.DataBindingUtil;
+import android.os.Bundle;
+import android.support.v4.app.Fragment;
+import android.support.v7.widget.LinearLayoutManager;
+import android.support.v7.widget.RecyclerView;
+import android.util.Log;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.Button;
+import android.widget.ProgressBar;
+import android.widget.RadioButton;
+import android.widget.TextView;
+
+import com.firebase.ui.database.FirebaseRecyclerAdapter;
+import com.google.firebase.auth.FirebaseAuth;
+import com.google.firebase.database.DatabaseReference;
+import com.google.firebase.database.FirebaseDatabase;
+import com.google.firebase.firestore.FirebaseFirestore;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+
+import java.util.List;
+
+import javax.inject.Inject;
+
+import dagger.android.support.AndroidSupportInjection;
+import retrofit2.Call;
+import retrofit2.Callback;
+import retrofit2.Response;
+import retrofit2.Retrofit;
+import retrofit2.converter.gson.GsonConverterFactory;
+import udacityteam.healthapp.Model.OneSharedFoodProductsListRetrofit;
+import udacityteam.healthapp.Model.SharedFoodProductsRetrofit;
+import udacityteam.healthapp.PHP_Retrofit_API.APIService;
+import udacityteam.healthapp.PHP_Retrofit_API.APIUrl;
+import udacityteam.healthapp.R;
+import udacityteam.healthapp.activities.ApplicationClass;
+import udacityteam.healthapp.adapters.FoodViewHolder;
+import udacityteam.healthapp.adapters.SharedFoodListsAdapter;
+import udacityteam.healthapp.adapters.SharedFoodListsAdapterNew;
+import udacityteam.healthapp.completeRedesign.Repository.Status;
+import udacityteam.healthapp.databinding.CommunityListFragmentBinding;
+import udacityteam.healthapp.models.SelectedFood;
+
+/**
+ * Created by vvost on 11/16/2017.
+ */
+
+public class SharedFoodListFragmentNetwork extends Fragment{
+ private static final String TAG = "RecyclerViewFragment";
+ private static final String KEY_LAYOUT_MANAGER = "layoutManager";
+ private static final int SPAN_COUNT = 2;
+ private static final int DATASET_COUNT = 60;
+ private RecyclerView.LayoutManager layoutManager;
+ FirebaseRecyclerAdapter adapter;
+ FirebaseFirestore storage;
+
+
+ private enum LayoutManagerType {
+ GRID_LAYOUT_MANAGER,
+ LINEAR_LAYOUT_MANAGER
+ }
+
+ protected SharedFoodListFragmentNetwork.LayoutManagerType mCurrentLayoutManagerType;
+
+ protected RadioButton mLinearLayoutRadioButton;
+ protected RadioButton mGridLayoutRadioButton;
+
+ protected RecyclerView mRecyclerView;
+ protected SharedFoodListsAdapter mAdapter;
+ protected RecyclerView.LayoutManager mLayoutManager;
+ TextView listodydis;
+ protected String[] mDataset;
+ public static String value = "Breakfast";
+ ProgressBar progressBar;
+
+ private FirebaseAuth mAuth;
+ DatabaseReference foodList;
+ FirebaseDatabase database;
+ Button filterData, test;
+ String side, SharedFoodListDatabase;
+ private CommunityListFragmentBinding communityListFragmentBinding;
+ private SharedFoodListsViewModelNew viewModel;
+
+ @Inject
+ ViewModelProvider.Factory ViewModelFactory;
+
+ public static SharedFoodListFragmentNetwork newInstance(Bundle values) {
+ SharedFoodListFragmentNetwork storiesFragment = new SharedFoodListFragmentNetwork();
+ storiesFragment.setArguments(values);
+ return storiesFragment;
+ }
+
+ @Override
+ public void onAttach(Context context) {
+ AndroidSupportInjection.inject(this);
+ super.onAttach(context);
+ }
+
+ @Override
+ public void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ viewModel = ViewModelProviders.of(getActivity(), ViewModelFactory).
+ get(SharedFoodListsViewModelNew.class);
+ Bundle bundle = getArguments();
+ if (bundle != null) {
+ side = bundle.getString("foodselection", null);
+ SharedFoodListDatabase = bundle.getString("SharedFoodListDatabase");
+ }
+
+ mAuth = FirebaseAuth.getInstance();
+
+ }
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+ communityListFragmentBinding = DataBindingUtil.inflate(inflater, R.layout.community_list_fragment, container, false);
+ InitializeRecyclerView();
+ observeResult();
+ filterData = communityListFragmentBinding.getRoot().findViewById(R.id.filterdata);
+
+ filterData.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ FragmentManager ft = getActivity().getFragmentManager();
+ FilterActivity dialog = new FilterActivity();
+ dialog.show(ft, "MyCustomDialog");
+ }
+ });
+ return communityListFragmentBinding.getRoot();
+ }
+
+
+ public void LoadFoodListMutable()
+ {
+ communityListFragmentBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
+ communityListFragmentBinding.recyclerView.setHasFixedSize(true);
+ }
+private void observeResult()
+{
+
+ viewModel.getRecipes().observe(this,repositories->
+ {
+ if(repositories.status== Status.SUCCESS) {
+ SharedFoodListsAdapterNew customAdapterFoodListPrievew = new
+ SharedFoodListsAdapterNew(side);
+ customAdapterFoodListPrievew.setSelectedFoods(repositories.data);
+ customAdapterFoodListPrievew.notifyDataSetChanged();
+ communityListFragmentBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
+ communityListFragmentBinding.recyclerView.setHasFixedSize(true);
+ communityListFragmentBinding.recyclerView.setAdapter(customAdapterFoodListPrievew);
+ }
+ });
+
+}
+
+
+ private void InitializeRecyclerView()
+ {
+ SharedFoodListsAdapterNew customAdapterFoodListPrievew= new
+ SharedFoodListsAdapterNew(side);
+ viewModel.mutableLiveData.observe(getActivity(), (selectedfoods)->{
+ customAdapterFoodListPrievew.setSelectedFoods(selectedfoods);
+ customAdapterFoodListPrievew.notifyDataSetChanged();
+
+ } );
+ mLayoutManager = new LinearLayoutManager(getActivity());
+ communityListFragmentBinding.recyclerView.setLayoutManager(mLayoutManager);
+ communityListFragmentBinding.recyclerView.setAdapter(customAdapterFoodListPrievew);
+
+ }
+
+
+}
diff --git a/app/src/main/java/udacityteam/healthapp/activities/CommunityActivities/SharedFoodListsViewModelNew.java b/app/src/main/java/udacityteam/healthapp/activities/CommunityActivities/SharedFoodListsViewModelNew.java
new file mode 100644
index 0000000..e463edc
--- /dev/null
+++ b/app/src/main/java/udacityteam/healthapp/activities/CommunityActivities/SharedFoodListsViewModelNew.java
@@ -0,0 +1,197 @@
+package udacityteam.healthapp.activities.CommunityActivities;
+
+import android.app.Application;
+import android.arch.lifecycle.AndroidViewModel;
+import android.arch.lifecycle.LiveData;
+import android.arch.lifecycle.MutableLiveData;
+import android.arch.lifecycle.ViewModel;
+import android.content.Context;
+import android.util.Log;
+import android.view.View;
+import android.widget.Toast;
+
+import com.google.firebase.auth.FirebaseAuth;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+
+import java.sql.Timestamp;
+import java.util.List;
+
+import javax.inject.Inject;
+
+import io.apptik.widget.MultiSlider;
+import retrofit2.Call;
+import retrofit2.Callback;
+import retrofit2.Response;
+import retrofit2.Retrofit;
+import retrofit2.converter.gson.GsonConverterFactory;
+import rx.Subscriber;
+import rx.Subscription;
+import rx.android.schedulers.AndroidSchedulers;
+import udacityteam.healthapp.Model.OneSharedFoodProductsListRetrofit;
+import udacityteam.healthapp.Model.SelectedFoodretrofit;
+import udacityteam.healthapp.Model.SharedFoodProductsRetrofit;
+import udacityteam.healthapp.Model.UserProfile;
+import udacityteam.healthapp.Network.PHPService;
+import udacityteam.healthapp.PHP_Retrofit_API.APIService;
+import udacityteam.healthapp.PHP_Retrofit_API.APIUrl;
+import udacityteam.healthapp.activities.FoodNutritiensDisplayPrieview;
+import udacityteam.healthapp.app.ApplicationController;
+import udacityteam.healthapp.completeRedesign.Repository.RecipiesRepository;
+import udacityteam.healthapp.completeRedesign.Repository.Resource;
+
+/**
+ * View model for each item in the repositories RecyclerView
+ */
+public class SharedFoodListsViewModelNew extends ViewModel {
+
+ private static final String TAG ="trxt" ;
+ private SelectedFoodretrofit selectedFoodretrofit;
+ private Context context;
+ private String foodId;
+ private String foodName;
+ private String UserId= FirebaseAuth.getInstance().getCurrentUser().getUid();
+ private String SendDate;
+ private float Calories;
+ private float Protein;
+ private float Fat;
+ private float Carbohydrates;
+ private Subscription subscription;
+ private DataListener dataListener;
+ private LiveData>> recipes;
+
+ List selectedFoodretrofits;
+ RecipiesRepository repository;
+
+ public MutableLiveData> mutableLiveData = new MutableLiveData<>();
+ ApplicationController application = null;
+
+ @Inject
+ public SharedFoodListsViewModelNew(RecipiesRepository recipiesRepository) {
+ this.repository = recipiesRepository;
+ }
+
+ public LiveData>> getRecipes() {
+ if (recipes == null) {
+ recipes = repository.loadRecipes();
+ }
+ return recipes;
+ }
+
+ public String getName() {
+ return selectedFoodretrofit.getFoodid();
+ }
+
+ public void LoadFoodList( String SharedFoodListDatabase)
+ {
+
+ if (subscription != null && !subscription.isUnsubscribed()) subscription.unsubscribe();
+
+ PHPService phpService = application.getPHPService();
+ subscription = phpService.getAllSharedDiets(application.getId(),
+ SharedFoodListDatabase)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribeOn(application.defaultSubscribeScheduler())
+ .subscribe(new Subscriber() {
+ @Override
+ public void onCompleted() {
+ for(int i=0;i< selectedFoodretrofits.size(); i++)
+ {
+ selectedFoodretrofits.get(i).setUserProfile(new UserProfile(
+ selectedFoodretrofits.get(i).getMail(), selectedFoodretrofits.get(i).getDisplayname()
+ ));
+ }
+ Log.d("aryra", String.valueOf(selectedFoodretrofits.size()));
+ InitSelectedfoods(selectedFoodretrofits);
+ }
+
+ @Override
+ public void onError(Throwable error) {
+ Log.e(TAG, "Error loading GitHub repos ", error);
+// if (isHttp404(error)) {
+// infoMessage.set("notfound");
+// } else {
+// infoMessage.set("good");
+// }
+// infoMessageVisibility.set(View.VISIBLE);
+ }
+
+ @Override
+ public void onNext(SharedFoodProductsRetrofit repositories) {
+
+ Log.i(TAG, "Repos loaded " + repositories);
+ Log.d("aryra1", String.valueOf(repositories));
+ // CommunityFoodListsDisplayFragment0.this.selectedFoodretrofits = repositories.getUsers().getClass();
+ SharedFoodListsViewModelNew.this.selectedFoodretrofits = repositories.getSelectedFoodretrofits();
+ }
+ });
+ }
+ public void InitSelectedfoods(List ones)
+ {
+ mutableLiveData.setValue(ones);
+ }
+ public MutableLiveData> getMutableLiveData()
+ {
+ return mutableLiveData;
+ }
+ public void setSelectectedFoood(SelectedFoodretrofit selectedFoodretrofit) {
+ this.selectedFoodretrofit = selectedFoodretrofit;
+ notify();
+ }
+ public void onItemClick(View view) {
+ application.getApplicationContext().startActivity(FoodNutritiensDisplayPrieview.newIntent(context, selectedFoodretrofit));
+ }
+ public void Hello()
+ {
+ Toast.makeText(application.getApplicationContext(), "heeeeeeeeee", Toast.LENGTH_LONG).show();
+ }
+ public void GetFilteredSharedDiets(MultiSlider protein, MultiSlider calories,
+ MultiSlider carbohydrates, MultiSlider fats
+ , String SharedFoodListDatabase) //only if today
+ {
+
+ Timestamp timestamp = new Timestamp(System.currentTimeMillis());
+ Gson gson = new GsonBuilder()
+ .setLenient()
+ .create();
+ Retrofit retrofit = new Retrofit.Builder()
+ .baseUrl(APIUrl.BASE_URL)
+ .addConverterFactory(GsonConverterFactory.create(gson))
+ .build();
+
+ //Defining retrofit api service
+ APIService service = retrofit.create(APIService.class);
+
+ Call call = service.getAllFilteredSharedDiets(application.getId()
+ , SharedFoodListDatabase, protein.getThumb(0).getValue(), protein.getThumb(1).getValue(),
+ calories.getThumb(0).getValue(), calories.getThumb(1).getValue(),
+ carbohydrates.getThumb(0).getValue(), carbohydrates.getThumb(1).getValue(),
+ fats.getThumb(0).getValue(), fats.getThumb(1).getValue()
+ );
+ call.enqueue(new Callback() {
+ @Override
+ public void onResponse(Call call, Response response) {
+ List selectedFoodretrofits = response.body().
+ getSelectedFoodretrofits();
+ mutableLiveData.setValue(selectedFoodretrofits);
+ //notify();
+
+ if (selectedFoodretrofits.size() != 0) {
+ Toast.makeText(application.getApplicationContext(), String.valueOf(selectedFoodretrofits.get(0).getCalories()), Toast.LENGTH_SHORT).show();
+ }
+ }
+
+ @Override
+ public void onFailure(Call call, Throwable t) {
+
+ }
+
+ });
+
+ }
+
+ public interface DataListener {
+ void onRepositoriesChanged(List repositories);
+ }
+
+}
diff --git a/app/src/main/java/udacityteam/healthapp/activities/FoodListViewModel.java b/app/src/main/java/udacityteam/healthapp/activities/FoodListViewModel.java
index 340c0f6..077fc4d 100644
--- a/app/src/main/java/udacityteam/healthapp/activities/FoodListViewModel.java
+++ b/app/src/main/java/udacityteam/healthapp/activities/FoodListViewModel.java
@@ -142,7 +142,8 @@ private void handleResponse(SelectedFoodretrofitarray androidList) {
private void handleError(Throwable error) {
// Toast.makeText(this, "Error "+error.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
- Log.d("erroraa", "error");
+
+ Log.d("erroraa", error.getMessage());
}
public void IsShared(String foodselection)
diff --git a/app/src/main/java/udacityteam/healthapp/activities/FoodNutritiensDisplay.java b/app/src/main/java/udacityteam/healthapp/activities/FoodNutritiensDisplay.java
index 4926fe4..303cdd7 100644
--- a/app/src/main/java/udacityteam/healthapp/activities/FoodNutritiensDisplay.java
+++ b/app/src/main/java/udacityteam/healthapp/activities/FoodNutritiensDisplay.java
@@ -46,6 +46,7 @@
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
+import udacityteam.healthapp.Network.PHPService;
import udacityteam.healthapp.PHP_Retrofit_API.APIService;
import udacityteam.healthapp.PHP_Retrofit_API.APIUrl;
import udacityteam.healthapp.Model.Result;
@@ -172,8 +173,8 @@ private void AddFoodtoDatabase(List nutritiens) {
//Defining retrofit api service
APIService service = retrofit.create(APIService.class);
- Call call = service.addSelectedFood(
- id,
+ Call call = PHPService.Factory.create().addSelectedFood(
+ id,"shshshshs",
((ApplicationController)context.getApplicationContext()).getId(), timestamp, nutritiens.get(0)
,nutritiens.get(1),nutritiens.get(2),nutritiens.get(3),
foodselection,0
diff --git a/app/src/main/java/udacityteam/healthapp/activities/LoginRegisterViewModel.java b/app/src/main/java/udacityteam/healthapp/activities/LoginRegisterViewModel.java
new file mode 100644
index 0000000..ded01a7
--- /dev/null
+++ b/app/src/main/java/udacityteam/healthapp/activities/LoginRegisterViewModel.java
@@ -0,0 +1,129 @@
+package udacityteam.healthapp.activities;
+
+import android.arch.lifecycle.LiveData;
+import android.arch.lifecycle.MutableLiveData;
+import android.arch.lifecycle.ViewModel;
+import android.content.Intent;
+import android.support.annotation.NonNull;
+import android.util.Log;
+import android.widget.Toast;
+
+import com.google.firebase.auth.FirebaseAuth;
+import com.google.firebase.auth.FirebaseUser;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+
+import javax.inject.Inject;
+
+import io.reactivex.Completable;
+import io.reactivex.CompletableObserver;
+import io.reactivex.Observable;
+import io.reactivex.Scheduler;
+import io.reactivex.android.schedulers.AndroidSchedulers;
+import io.reactivex.disposables.Disposable;
+import io.reactivex.functions.Action;
+import io.reactivex.schedulers.Schedulers;
+import retrofit2.Call;
+import retrofit2.Callback;
+import retrofit2.Response;
+import retrofit2.Retrofit;
+import retrofit2.converter.gson.GsonConverterFactory;
+import udacityteam.healthapp.Model.Result;
+import udacityteam.healthapp.Model.UserRetrofitGood;
+import udacityteam.healthapp.Model.Userretrofit;
+import udacityteam.healthapp.PHP_Retrofit_API.APIService;
+import udacityteam.healthapp.PHP_Retrofit_API.APIUrl;
+import udacityteam.healthapp.completeRedesign.Data.Networking.API.RetrofitFactoryNew;
+import udacityteam.healthapp.completeRedesign.Repository.RecipiesRepository;
+import udacityteam.healthapp.completeRedesign.db.MainDatabase;
+import udacityteam.healthapp.completeRedesign.db.RecipesMainDao;
+
+public class LoginRegisterViewModel extends ViewModel {
+
+ RecipiesRepository repository;
+ private FirebaseAuth mAuth;
+ private RecipesMainDao recipesMainDao;
+ private MainDatabase mainDatabase;
+ @Inject
+ public LoginRegisterViewModel(RecipiesRepository recipiesRepository) {
+ this.repository = recipiesRepository;
+ this.recipesMainDao = recipiesRepository.getUserDao();
+ this.mainDatabase = recipiesRepository.getMainDatabase();
+ }
+ MutableLiveData googleSigInRegister;
+ public LiveData getRegisterWithGoogleSignInResponse(Userretrofit userretrofit)
+ {
+ if(googleSigInRegister==null)
+ {
+ if(userretrofit!=null)
+ registerWithGoogleSignIn(userretrofit);
+
+ }
+ return googleSigInRegister;
+
+ }
+
+ public void registerWithGoogleSignIn(Userretrofit retrofituser)
+ {
+ googleSigInRegister = new MutableLiveData<>();
+
+ //Defiin retrofit api service
+ udacityteam.healthapp.completeRedesign.Data.Networking.API.APIService apiService
+ = RetrofitFactoryNew.create();
+
+ //defining the call
+ Call call = apiService.createUser(
+ retrofituser.getName(),
+ retrofituser.getEmail(),
+ retrofituser.getUid()
+
+ );
+ call.enqueue(new Callback() {
+ @Override
+ public void onResponse(@NonNull Call call, @NonNull Response response) {
+ Result result = response.body();
+ if(result!=null) {
+ if (!result.getError()) {
+ googleSigInRegister.setValue(result);
+ UserRetrofitGood userRetrofitGood= result.getUser();
+ Completable.fromAction(() ->
+ recipesMainDao.insertCurrentUser(userRetrofitGood)).
+ observeOn(AndroidSchedulers.mainThread())
+ .subscribeOn(Schedulers.io()).subscribe(new CompletableObserver() {
+ @Override
+ public void onSubscribe(Disposable d) {
+ }
+
+ @Override
+ public void onComplete() {
+ }
+
+ @Override
+ public void onError(Throwable e) {
+ }
+ });
+
+ } else {
+ googleSigInRegister.setValue(result);
+ }
+ }
+ else
+ {
+ googleSigInRegister.setValue(new Result(false, "Server Issue"
+ , null));
+ }
+
+
+ }
+
+ @Override
+ public void onFailure(@NonNull Call call, @NonNull Throwable t) {
+
+
+ }
+ });
+ }
+
+ //public void
+
+}
diff --git a/app/src/main/java/udacityteam/healthapp/activities/LoginWithMailFragment.java b/app/src/main/java/udacityteam/healthapp/activities/LoginWithMailFragment.java
new file mode 100644
index 0000000..879ada3
--- /dev/null
+++ b/app/src/main/java/udacityteam/healthapp/activities/LoginWithMailFragment.java
@@ -0,0 +1,253 @@
+package udacityteam.healthapp.activities;
+
+import android.content.Intent;
+import android.os.Bundle;
+import android.support.annotation.NonNull;
+import android.support.v7.app.AppCompatActivity;
+import android.text.TextUtils;
+import android.util.Log;
+import android.view.View;
+import android.widget.EditText;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.google.android.gms.tasks.OnCompleteListener;
+import com.google.android.gms.tasks.Task;
+import com.google.firebase.auth.AuthResult;
+import com.google.firebase.auth.FirebaseAuth;
+import com.google.firebase.auth.FirebaseUser;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+
+import retrofit2.Call;
+import retrofit2.Callback;
+import retrofit2.Response;
+import retrofit2.Retrofit;
+import retrofit2.converter.gson.GsonConverterFactory;
+import udacityteam.healthapp.Model.Result;
+import udacityteam.healthapp.Model.UserRetrofitGood;
+import udacityteam.healthapp.Model.Userretrofit;
+import udacityteam.healthapp.PHP_Retrofit_API.APIService;
+import udacityteam.healthapp.PHP_Retrofit_API.APIUrl;
+import udacityteam.healthapp.R;
+
+
+public class LoginWithMailFragment extends AppCompatActivity implements
+ View.OnClickListener {
+
+ private static final String TAG = "EmailPassword";
+
+ private TextView mStatusTextView;
+ private TextView mDetailTextView;
+ private EditText mEmailField;
+ private EditText mPasswordField;
+ public static UserRetrofitGood currentuser;
+
+ // [START declare_auth]
+ private FirebaseAuth mAuth;
+ // [END declare_auth]
+
+ @Override
+ public void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_login_with_mail_pasword);
+
+ // Views
+ mStatusTextView = findViewById(R.id.status);
+ mDetailTextView = findViewById(R.id.detail);
+ mEmailField = findViewById(R.id.field_email);
+ mPasswordField = findViewById(R.id.field_password);
+
+ // Buttons
+ findViewById(R.id.email_sign_in_button).setOnClickListener(this);
+
+ // [START initialize_auth]
+ mAuth = FirebaseAuth.getInstance();
+ // Log.d("mAuthgood", mAuth.getCurrentUser().getUid().toString());
+ // [END initialize_auth]
+ }
+
+ // [START on_start_check_user]
+ @Override
+ public void onStart() {
+ super.onStart();
+ // Check if user is signed in (non-null) and update UI accordingly.
+ FirebaseUser currentUser = mAuth.getCurrentUser();
+ updateUI(currentUser);
+ }
+
+
+ private void signIn(final String email, final String password) {
+ Log.d(TAG, "signIn:" + email);
+ if (!validateForm()) {
+ return;
+ }
+
+ // showProgressDialog();
+
+ // [START sign_in_with_email]
+ mAuth.signInWithEmailAndPassword(email, password)
+ .addOnCompleteListener(this, new OnCompleteListener() {
+ @Override
+ public void onComplete(@NonNull Task task) {
+ if (task.isSuccessful()) {
+
+
+ Log.d(TAG, "signInWithEmail:success");
+ FirebaseUser user = mAuth.getCurrentUser();
+ if(user!=null && user.isEmailVerified()) {
+ Gson gson = new GsonBuilder()
+ .setLenient()
+ .create();
+ Retrofit retrofit = new Retrofit.Builder()
+ .baseUrl(APIUrl.BASE_URL)
+ .addConverterFactory(GsonConverterFactory.create(gson))
+ .build();
+
+ //Defining retrofit api service
+ APIService service = retrofit.create(APIService.class);
+
+ //Defining the user object as we need to pass it with the call
+ Userretrofit retrofituser = new Userretrofit(user.getDisplayName(), user.getEmail(), mAuth.getCurrentUser().getUid());
+
+ //defining the call
+ Call call = service.createUser(
+ password,
+ email,
+ retrofituser.getUid()
+
+ );
+
+ Log.d(TAG, mAuth.getCurrentUser().getUid());
+ call.enqueue(new Callback() {
+ @Override
+ public void onResponse(Call call, Response response) {
+
+ Log.d("veikeas", String.valueOf(response.body().getUser().getId()));
+
+ Intent intent = new Intent(LoginWithMailFragment.this, MainActivity.class);
+ startActivity(intent);
+ finish();
+ }
+
+ @Override
+ public void onFailure(Call call, Throwable t) {
+ // progressDialog.dismiss();
+ Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
+ }
+ });
+
+ }
+ else
+ {
+ Toast.makeText(LoginWithMailFragment.this, "User Email is not verified", Toast.LENGTH_SHORT).show();
+ }
+
+
+
+ updateUI(user);
+ } else {
+ // If sign in fails, display a message to the user.
+ Log.w(TAG, "signInWithEmail:failure", task.getException());
+ // Toast.makeText(EmailPasswordActivity.this, "Authentication failed.",
+ // Toast.LENGTH_SHORT).show();
+ updateUI(null);
+ }
+
+ // [START_EXCLUDE]
+ if (!task.isSuccessful()) {
+ mStatusTextView.setText("failed");
+ }
+ // hideProgressDialog();
+ // [END_EXCLUDE]
+ }
+ });
+ // [END sign_in_with_email]
+ }
+
+ private void signOut() {
+ mAuth.signOut();
+ updateUI(null);
+ }
+
+ private void sendEmailVerification() {
+ // Disable button
+ findViewById(R.id.verify_email_button).setEnabled(false);
+
+ // Send verification email
+ // [START send_email_verification]
+ final FirebaseUser user = mAuth.getCurrentUser();
+ user.sendEmailVerification()
+ .addOnCompleteListener(this, new OnCompleteListener() {
+ @Override
+ public void onComplete(@NonNull Task task) {
+ // [START_EXCLUDE]
+ // Re-enable button
+ findViewById(R.id.verify_email_button).setEnabled(true);
+
+ if (task.isSuccessful()) {
+ Toast.makeText(LoginWithMailFragment.this,
+ "Verification email sent to " + user.getEmail(),
+ Toast.LENGTH_SHORT).show();
+ } else {
+ Log.e(TAG, "sendEmailVerification", task.getException());
+ Toast.makeText(LoginWithMailFragment.this,
+ "Failed to send verification email.",
+ Toast.LENGTH_SHORT).show();
+ }
+ // [END_EXCLUDE]
+ }
+ });
+ // [END send_email_verification]
+ }
+
+ private boolean validateForm() {
+ boolean valid = true;
+
+ String email = mEmailField.getText().toString();
+ if (TextUtils.isEmpty(email)) {
+ mEmailField.setError("Required.");
+ valid = false;
+ } else {
+ mEmailField.setError(null);
+ }
+
+ String password = mPasswordField.getText().toString();
+ if (TextUtils.isEmpty(password)) {
+ mPasswordField.setError("Required.");
+ valid = false;
+ } else {
+ mPasswordField.setError(null);
+ }
+
+ return valid;
+ }
+
+ private void updateUI(FirebaseUser user) {
+ // hideProgressDialog();
+ if (user != null) {
+ if(user.isEmailVerified())
+ {
+ Intent intent = new Intent(LoginWithMailFragment.this, MainActivity.class);
+ startActivity(intent);
+ }
+
+ }
+ else {
+ mStatusTextView.setText("sitnout");
+ mDetailTextView.setText(null);
+
+ findViewById(R.id.email_password_buttons).setVisibility(View.VISIBLE);
+ findViewById(R.id.email_password_fields).setVisibility(View.VISIBLE);
+ findViewById(R.id.signed_in_buttons).setVisibility(View.GONE);
+ }
+ }
+
+ @Override
+ public void onClick(View v) {
+ int i = v.getId();
+ if (i == R.id.email_sign_in_button) {
+ signIn(mEmailField.getText().toString(), mPasswordField.getText().toString());
+ }
+ }
+}
diff --git a/app/src/main/java/udacityteam/healthapp/activities/MainActivity.java b/app/src/main/java/udacityteam/healthapp/activities/MainActivity.java
index 7179012..26dc356 100644
--- a/app/src/main/java/udacityteam/healthapp/activities/MainActivity.java
+++ b/app/src/main/java/udacityteam/healthapp/activities/MainActivity.java
@@ -439,7 +439,7 @@ private void ReturntoRegister()
.addOnCompleteListener(new OnCompleteListener() {
public void onComplete(@NonNull Task task) {
// user is now signed out
- Intent intent = new Intent(MainActivity.this, RegisterActivityHome.class);
+ Intent intent = new Intent(MainActivity.this, BaseActivity.class);
intent.putExtra("offline", true);
startActivity(intent);
finish();
diff --git a/app/src/main/java/udacityteam/healthapp/activities/RegisterActivityHome.java b/app/src/main/java/udacityteam/healthapp/activities/RegisterActivityHome.java
deleted file mode 100644
index 3c8befd..0000000
--- a/app/src/main/java/udacityteam/healthapp/activities/RegisterActivityHome.java
+++ /dev/null
@@ -1,278 +0,0 @@
-package udacityteam.healthapp.activities;
-
-/**
- * Created by vvost on 12/29/2017.
- */
-import android.support.v7.app.AppCompatActivity;
-import android.os.Bundle;
-import android.content.Intent;
-import android.support.annotation.NonNull;
-import android.support.design.widget.Snackbar;
-import android.util.Log;
-import android.view.View;
-import android.widget.Button;
-import android.widget.TextView;
-import android.widget.Toast;
-
-import com.google.android.gms.auth.api.signin.GoogleSignIn;
-import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
-import com.google.android.gms.auth.api.signin.GoogleSignInClient;
-import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
-import com.google.android.gms.common.api.ApiException;
-import com.google.android.gms.tasks.OnCompleteListener;
-import com.google.android.gms.tasks.Task;
-import com.google.firebase.auth.AuthCredential;
-import com.google.firebase.auth.AuthResult;
-import com.google.firebase.auth.FirebaseAuth;
-import com.google.firebase.auth.FirebaseUser;
-import com.google.firebase.auth.GoogleAuthProvider;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-
-import retrofit2.Call;
-import retrofit2.Callback;
-import retrofit2.Response;
-import retrofit2.Retrofit;
-import retrofit2.converter.gson.GsonConverterFactory;
-import udacityteam.healthapp.PHP_Retrofit_API.APIService;
-import udacityteam.healthapp.PHP_Retrofit_API.APIUrl;
-import udacityteam.healthapp.Model.Result;
-import udacityteam.healthapp.Model.Userretrofit;
-import udacityteam.healthapp.R;
-
-
-/**
- * Demonstrate Firebase Authentication using a Google ID Token.
- */
-public class RegisterActivityHome extends AppCompatActivity implements
- View.OnClickListener {
-
- private static final String TAG = "GoogleActivity";
- private static final int RC_SIGN_IN = 9001;
-
- // [START declare_auth]
- private FirebaseAuth mAuth;
-
- // [END declare_auth]
-
- private GoogleSignInClient mGoogleSignInClient;
- private TextView mStatusTextView;
- private TextView mDetailTextView;
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.register_activity_home);
-
- // Views
- mStatusTextView = findViewById(R.id.status);
- mDetailTextView = findViewById(R.id.detail);
-
- // Button listeners
- findViewById(R.id.sign_in_button).setOnClickListener(this);
-
- Button registermail = findViewById(R.id.mailregister);
- Button loginmail = findViewById(R.id.mailogin);
-
- mAuth = FirebaseAuth.getInstance();
- FirebaseUser currentUser = mAuth.getCurrentUser();
-
- registermail.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- Intent intent = new Intent(RegisterActivityHome.this, RegisterWithMailPasword.class);
- startActivity(intent);
- }
- });
- loginmail.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- Intent intent = new Intent(RegisterActivityHome.this, LoginWithMailPasword.class);
- startActivity(intent);
- }
- });
- // [START config_signin]
- // Configure Google Sign In
- GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
- .requestIdToken("1025887070439-pa8ivq2h24eigj8vv8h66e43ng7fgefh.apps.googleusercontent.com")
- .requestEmail()
- .build();
- // [END config_signin]
-
- mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
-
- // [START initialize_auth]
-
- // [END initialize_auth]
- }
-
- // [START on_start_check_user]
- @Override
- public void onStart() {
- super.onStart();
- // Check if user is signed in (non-null) and update UI accordingly.
- FirebaseUser currentUser = mAuth.getCurrentUser();
- updateUI(currentUser);
- }
- // [END on_start_check_user]
-
- // [START onactivityresult]
- @Override
- public void onActivityResult(int requestCode, int resultCode, Intent data) {
- super.onActivityResult(requestCode, resultCode, data);
-
- // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
- if (requestCode == RC_SIGN_IN) {
- Task task = GoogleSignIn.getSignedInAccountFromIntent(data);
- try {
- // Google Sign In was successful, authenticate with Firebase
- GoogleSignInAccount account = task.getResult(ApiException.class);
- firebaseAuthWithGoogle(account);
- } catch (ApiException e) {
- // Google Sign In failed, update UI appropriately
- Log.w(TAG, "Google sign in failed", e);
- // [START_EXCLUDE]
- updateUI(null);
- // [END_EXCLUDE]
- }
- }
- }
- // [END onactivityresult]
-
- // [START auth_with_google]
- private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
- Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
- // [START_EXCLUDE silent]
- // showProgressDialog();
- // [END_EXCLUDE]
-
- AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
- mAuth.signInWithCredential(credential)
- .addOnCompleteListener(this, new OnCompleteListener() {
- @Override
- public void onComplete(@NonNull Task task) {
- if (task.isSuccessful()) {
- final FirebaseUser user = mAuth.getCurrentUser();
- Log.d("curent", mAuth.getCurrentUser().getUid());
- // Sign in success, update UI with the signed-in user's information
- if(user!=null) {
-
- Gson gson = new GsonBuilder()
- .setLenient()
- .create();
- Retrofit retrofit = new Retrofit.Builder()
- .baseUrl(APIUrl.BASE_URL)
- .addConverterFactory(GsonConverterFactory.create(gson))
- .build();
-
- //Defining retrofit api service
- APIService service = retrofit.create(APIService.class);
-
- //Defining the user object as we need to pass it with the call
- Userretrofit retrofituser = new Userretrofit(user.getDisplayName(), user.getEmail(), mAuth.getCurrentUser().getUid());
-
- //defining the call
- Call call = service.createUser(
- retrofituser.getName(),
- retrofituser.getEmail(),
- retrofituser.getUid()
-
- );
- Intent intent = new Intent(RegisterActivityHome.this, MainActivity.class);
- startActivity(intent);
- finish();
- Log.d(TAG, mAuth.getCurrentUser().getUid());
- call.enqueue(new Callback() {
- @Override
- public void onResponse(Call call, Response response) {
-
-
- }
-
- @Override
- public void onFailure(Call call, Throwable t) {
- // progressDialog.dismiss();
- Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
- }
- });
- // Sign in success, update UI with the signed-in user's information
-
- } else {
- // If sign in fails, display a message to the user.
- Log.w(TAG, "signInWithCredential:failure", task.getException());
- Snackbar.make(findViewById(R.id.main_layout), "Authentication Failed.", Snackbar.LENGTH_SHORT).show();
- updateUI(null);
- }
-
- // [START_EXCLUDE]
- // hideProgressDialog();
- // [END_EXCLUDE]
- }
- }
- });}
-
- // [END auth_with_google]
-
- // [START signin]
- private void signIn() {
- Intent signInIntent = mGoogleSignInClient.getSignInIntent();
- startActivityForResult(signInIntent, RC_SIGN_IN);
- }
- // [END signin]
-
- private void signOut() {
- // Firebase sign out
- mAuth.signOut();
-
- // Google sign out
- mGoogleSignInClient.signOut().addOnCompleteListener(this,
- new OnCompleteListener() {
- @Override
- public void onComplete(@NonNull Task task) {
- updateUI(null);
- }
- });
- }
-
- private void revokeAccess() {
- // Firebase sign out
- mAuth.signOut();
-
- // Google revoke access
- mGoogleSignInClient.revokeAccess().addOnCompleteListener(this,
- new OnCompleteListener() {
- @Override
- public void onComplete(@NonNull Task task) {
- updateUI(null);
- }
- });
- }
-
- private void updateUI(FirebaseUser user) {
- // hideProgressDialog();
- if (user != null && user.isEmailVerified()) {
- Intent intent = new Intent(RegisterActivityHome.this, MainActivity.class);
- startActivity(intent);
- mStatusTextView.setText( user.getEmail());
- mDetailTextView.setText(user.getUid());
-
- } else {
- mStatusTextView.setText("noo");
- mDetailTextView.setText(null);
-
- findViewById(R.id.sign_in_button).setVisibility(View.VISIBLE);
-
- }
- }
-
- @Override
- public void onClick(View v) {
- int i = v.getId();
- if (i == R.id.sign_in_button) {
- signIn();
- }
-
- }
-}
-
-
diff --git a/app/src/main/java/udacityteam/healthapp/activities/RegisterWithMailFragment.java b/app/src/main/java/udacityteam/healthapp/activities/RegisterWithMailFragment.java
new file mode 100644
index 0000000..9ad7dd4
--- /dev/null
+++ b/app/src/main/java/udacityteam/healthapp/activities/RegisterWithMailFragment.java
@@ -0,0 +1,211 @@
+package udacityteam.healthapp.activities;
+
+
+import android.content.Intent;
+import android.os.Bundle;
+import android.support.annotation.NonNull;
+import android.support.annotation.Nullable;
+import android.support.v4.app.Fragment;
+import android.support.v7.app.AppCompatActivity;
+import android.text.TextUtils;
+import android.util.Log;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.EditText;
+import android.widget.TextView;
+import android.widget.Toast;
+
+import com.google.android.gms.tasks.OnCompleteListener;
+import com.google.android.gms.tasks.Task;
+import com.google.firebase.auth.AuthResult;
+import com.google.firebase.auth.FirebaseAuth;
+import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException;
+import com.google.firebase.auth.FirebaseAuthUserCollisionException;
+import com.google.firebase.auth.FirebaseAuthWeakPasswordException;
+import com.google.firebase.auth.FirebaseUser;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+
+import java.util.Objects;
+import java.util.zip.Inflater;
+
+import retrofit2.Call;
+import retrofit2.Callback;
+import retrofit2.Response;
+import retrofit2.Retrofit;
+import retrofit2.converter.gson.GsonConverterFactory;
+import udacityteam.healthapp.PHP_Retrofit_API.APIService;
+import udacityteam.healthapp.PHP_Retrofit_API.APIUrl;
+import udacityteam.healthapp.Model.Result;
+import udacityteam.healthapp.Model.Userretrofit;
+import udacityteam.healthapp.R;
+
+
+public class RegisterWithMailFragment extends Fragment implements
+ View.OnClickListener {
+
+ private static final String TAG = "EmailPassword";
+
+ private TextView mStatusTextView;
+ private TextView mDetailTextView;
+ private EditText mEmailField;
+ private EditText mPasswordField;
+
+ // [START declare_auth]
+ private FirebaseAuth mAuth;
+ // [END declare_auth]
+
+ @Override
+ public void onCreate(Bundle savedInstanceState) {
+ mAuth = FirebaseAuth.getInstance();
+ super.onCreate(savedInstanceState);
+ }
+
+ @Nullable
+ @Override
+ public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
+ View view = inflater.inflate(R.layout.activity_register_with_mail_pasword,
+ container, false);
+ mStatusTextView = view.findViewById(R.id.status);
+ mDetailTextView = view.findViewById(R.id.detail);
+ mEmailField = view.findViewById(R.id.field_email);
+ mPasswordField = view.findViewById(R.id.field_password);
+
+ view.findViewById(R.id.email_create_account_button).setOnClickListener(this);
+ view.findViewById(R.id.verify_email_button).setOnClickListener(this);
+ view.findViewById(R.id.signed_in_buttons).setVisibility(View.GONE);
+ return view;
+ }
+
+ // [START on_start_check_user]
+ @Override
+ public void onStart() {
+ super.onStart();
+ FirebaseUser currentUser = mAuth.getCurrentUser();
+ updateUI(currentUser);
+ }
+ // [END on_start_check_user]
+
+ private void createAccount(final String email, final String password) {
+ Log.d(TAG, "createAccount:" + email);
+ if (!validateForm()) {
+ return;
+ }
+
+ mAuth.createUserWithEmailAndPassword(email, password)
+ .addOnCompleteListener(requireActivity(), task -> {
+ if (task.isSuccessful()) {
+ // Sign in success, update UI with the signed-in user's information
+ Log.d(TAG, "createUserWithEmail:success");
+ FirebaseUser user = mAuth.getCurrentUser();
+
+ updateUI(user);
+ } else {
+ // If sign in fails, display a message to the user.
+ Log.w(TAG, "createUserWithEmail:failure", task.getException());
+ try {
+ throw Objects.requireNonNull(task.getException());
+ } catch(FirebaseAuthWeakPasswordException e) {
+ Toast.makeText(requireActivity(), "The Password is too short",
+ Toast.LENGTH_SHORT).show();
+
+ } catch(FirebaseAuthInvalidCredentialsException e) {
+ Toast.makeText(requireActivity(), "The Email is badly formatted",
+ Toast.LENGTH_SHORT).show();
+
+ } catch(FirebaseAuthUserCollisionException e) {
+ Toast.makeText(requireActivity(), "The Email is already in Use",
+ Toast.LENGTH_SHORT).show();
+
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ updateUI(null);
+ }
+
+ });
+ }
+
+
+
+ private void sendEmailVerification() {
+ requireActivity().findViewById(R.id.verify_email_button).setEnabled(false);
+ final FirebaseUser user = mAuth.getCurrentUser();
+ if(user!=null) {
+ user.sendEmailVerification()
+ .addOnCompleteListener(requireActivity(), new OnCompleteListener() {
+ @Override
+ public void onComplete(@NonNull Task task) {
+ requireActivity().findViewById(R.id.verify_email_button).setEnabled(true);
+
+ if (task.isSuccessful()) {
+ Toast.makeText(requireActivity(),
+ "Verification email sent to " + user.getEmail(),
+ Toast.LENGTH_SHORT).show();
+ Intent intent = new Intent(requireActivity(), LoginWithMailPasword.class);
+ startActivity(intent);
+ }
+ }
+ });
+ }
+ else
+ {
+ Toast.makeText(requireActivity(),
+ "Could not find a registration request",
+ Toast.LENGTH_SHORT).show();
+ }
+ }
+
+ private boolean validateForm() {
+ boolean valid = true;
+
+ String email = mEmailField.getText().toString();
+ if (TextUtils.isEmpty(email)) {
+ mEmailField.setError("Required.");
+ valid = false;
+ } else {
+ mEmailField.setError(null);
+ }
+
+ String password = mPasswordField.getText().toString();
+ if (TextUtils.isEmpty(password)) {
+ mPasswordField.setError("Required.");
+ valid = false;
+ } else {
+ mPasswordField.setError(null);
+ }
+
+ return valid;
+ }
+
+ private void updateUI(FirebaseUser user) {
+ if (user != null) {
+ requireActivity().findViewById(R.id.email_password_buttons).setVisibility(View.GONE);
+ requireActivity().findViewById(R.id.email_password_fields).setVisibility(View.GONE);
+ requireActivity().findViewById(R.id.signed_in_buttons).setVisibility(View.VISIBLE);
+ requireActivity().findViewById(R.id.verify_email_button).setEnabled(!user.isEmailVerified());
+
+
+ } else {
+ mStatusTextView.setText("sitnout");
+ mDetailTextView.setText(null);
+ requireActivity().findViewById(R.id.email_password_buttons).setVisibility(View.VISIBLE);
+ requireActivity().findViewById(R.id.email_password_fields).setVisibility(View.VISIBLE);
+ requireActivity().findViewById(R.id.signed_in_buttons).setVisibility(View.GONE);
+ }
+ }
+
+ @Override
+ public void onClick(View v) {
+ int i = v.getId();
+ if (i == R.id.email_create_account_button) {
+ createAccount(mEmailField.getText().toString(), mPasswordField.getText().toString());
+
+ } else if (i == R.id.verify_email_button) {
+ sendEmailVerification();
+ }
+ }
+}
diff --git a/app/src/main/java/udacityteam/healthapp/activities/RegisterWithMailPasword.java b/app/src/main/java/udacityteam/healthapp/activities/RegisterWithMailPasword.java
index fb8df5a..881f01a 100644
--- a/app/src/main/java/udacityteam/healthapp/activities/RegisterWithMailPasword.java
+++ b/app/src/main/java/udacityteam/healthapp/activities/RegisterWithMailPasword.java
@@ -73,7 +73,6 @@ public void onCreate(Bundle savedInstanceState) {
@Override
public void onStart() {
super.onStart();
- // Check if user is signed in (non-null) and update UI accordingly.
FirebaseUser currentUser = mAuth.getCurrentUser();
updateUI(currentUser);
}
@@ -84,10 +83,6 @@ private void createAccount(final String email, final String password) {
if (!validateForm()) {
return;
}
-
- // showProgressDialog();
-
- // [START create_user_with_email]
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener() {
@Override
@@ -96,7 +91,6 @@ public void onComplete(@NonNull Task task) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "createUserWithEmail:success");
FirebaseUser user = mAuth.getCurrentUser();
- Log.d("ahahag", user.getUid().toString());
//check if email exist
@@ -136,96 +130,6 @@ public void onComplete(@NonNull Task task) {
// [END create_user_with_email]
}
- private void signIn(final String email, final String password) {
- Log.d(TAG, "signIn:" + email);
- if (!validateForm()) {
- return;
- }
-
- // showProgressDialog();
-
- // [START sign_in_with_email]
- mAuth.signInWithEmailAndPassword(email, password)
- .addOnCompleteListener(this, new OnCompleteListener() {
- @Override
- public void onComplete(@NonNull Task task) {
- if (task.isSuccessful()) {
-
- // Sign in success, update UI with the signed-in user's information
- Log.d(TAG, "signInWithEmail:success");
- FirebaseUser user = mAuth.getCurrentUser();
- mStatusTextView.setText(user.getUid());
- if (user!=null && user.isEmailVerified()) {
- Gson gson = new GsonBuilder()
- .setLenient()
- .create();
- Retrofit retrofit = new Retrofit.Builder()
- .baseUrl(APIUrl.BASE_URL)
- .addConverterFactory(GsonConverterFactory.create(gson))
- .build();
-
- //Defining retrofit api service
- APIService service = retrofit.create(APIService.class);
-
- //Defining the user object as we need to pass it with the call
- Userretrofit retrofituser = new Userretrofit(user.getDisplayName(), user.getEmail(), mAuth.getCurrentUser().getUid());
-
- //defining the call
- Call call = service.createUser(
- password,
- email,
- retrofituser.getUid()
-
- );
- Intent intent = new Intent(RegisterWithMailPasword.this, MainActivity.class);
- startActivity(intent);
- finish();
- Log.d(TAG, mAuth.getCurrentUser().getUid());
- call.enqueue(new Callback() {
- @Override
- public void onResponse(Call call, Response response) {
-
-
- }
-
- @Override
- public void onFailure(Call call, Throwable t) {
- // progressDialog.dismiss();
- Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
- }
- });
-
- } else
- {
- Toast.makeText(RegisterWithMailPasword.this, "not verified", Toast.LENGTH_LONG).show();
- }
-
-
-
- updateUI(user);
- } else {
- // If sign in fails, display a message to the user.
- Log.w(TAG, "signInWithEmail:failure", task.getException());
- // Toast.makeText(EmailPasswordActivity.this, "Authentication failed.",
- // Toast.LENGTH_SHORT).show();
- updateUI(null);
- }
-
- // [START_EXCLUDE]
- if (!task.isSuccessful()) {
- mStatusTextView.setText("failed");
- }
- // hideProgressDialog();
- // [END_EXCLUDE]
- }
- });
- // [END sign_in_with_email]
- }
-
- private void signOut() {
- mAuth.signOut();
- updateUI(null);
- }
private void sendEmailVerification() {
// Disable button
@@ -288,9 +192,6 @@ private boolean validateForm() {
private void updateUI(FirebaseUser user) {
// hideProgressDialog();
if (user != null) {
-// mStatusTextView.setText(
-// user.getEmail(), user.isEmailVerified()));
-// mDetailTextView.setText(getString(R.string.firebase_status_fmt, user.getUid()));
findViewById(R.id.email_password_buttons).setVisibility(View.GONE);
findViewById(R.id.email_password_fields).setVisibility(View.GONE);
diff --git a/app/src/main/java/udacityteam/healthapp/adapters/SharedFoodListsAdapterNew.java b/app/src/main/java/udacityteam/healthapp/adapters/SharedFoodListsAdapterNew.java
index 7327b1b..4eab1a2 100644
--- a/app/src/main/java/udacityteam/healthapp/adapters/SharedFoodListsAdapterNew.java
+++ b/app/src/main/java/udacityteam/healthapp/adapters/SharedFoodListsAdapterNew.java
@@ -60,7 +60,9 @@ public void onBindViewHolder(RepositoryViewHolder holder, int position) {
@Override
public int getItemCount() {
+ if(oneSharedFoodProductsListRetrofits!=null)
return oneSharedFoodProductsListRetrofits.size();
+ else return 0;
}
public static class RepositoryViewHolder extends RecyclerView.ViewHolder {
diff --git a/app/src/main/java/udacityteam/healthapp/app/ApplicationController.java b/app/src/main/java/udacityteam/healthapp/app/ApplicationController.java
index 9d1086a..5cb1641 100644
--- a/app/src/main/java/udacityteam/healthapp/app/ApplicationController.java
+++ b/app/src/main/java/udacityteam/healthapp/app/ApplicationController.java
@@ -1,17 +1,65 @@
package udacityteam.healthapp.app;
+import android.app.Activity;
import android.app.Application;
+import android.app.Service;
+import android.content.BroadcastReceiver;
import android.content.Context;
+import javax.inject.Inject;
+
+import dagger.android.AndroidInjector;
+import dagger.android.DispatchingAndroidInjector;
+import dagger.android.HasActivityInjector;
+import dagger.android.HasBroadcastReceiverInjector;
+import dagger.android.HasServiceInjector;
import rx.Scheduler;
import rx.schedulers.Schedulers;
import udacityteam.healthapp.Network.PHPService;
+import udacityteam.healthapp.completeRedesign.Dagger2.DaggerAppComponent;
/**
* Created by vvost on 2/8/2018.
*/
-public class ApplicationController extends Application {
+public class ApplicationController extends Application
+ implements HasActivityInjector, HasServiceInjector, HasBroadcastReceiverInjector
+ {
+
+ @Override
+ public void onCreate() {
+ super.onCreate();
+ DaggerAppComponent.builder()
+ .application(this)
+ .build()
+ .inject(this);
+ }
+
+ @Inject
+ DispatchingAndroidInjector dispatchingAndroidInjector;
+
+ @Inject
+ DispatchingAndroidInjector dispatchingBroadcastReceiverInjector;
+
+ @Inject
+ DispatchingAndroidInjector dispatchingServiceInjector;
+
+ @Override
+ public DispatchingAndroidInjector activityInjector() {
+ return dispatchingAndroidInjector;
+ }
+
+ @Override
+ public DispatchingAndroidInjector serviceInjector() {
+ return dispatchingServiceInjector;
+ }
+
+ @Override
+ public AndroidInjector broadcastReceiverInjector() {
+ return dispatchingBroadcastReceiverInjector;
+ }
+
+
private PHPService phpService;
private Scheduler defaultSubscribeScheduler;
diff --git a/app/src/main/java/udacityteam/healthapp/completeRedesign/App.java b/app/src/main/java/udacityteam/healthapp/completeRedesign/App.java
new file mode 100644
index 0000000..f24240a
--- /dev/null
+++ b/app/src/main/java/udacityteam/healthapp/completeRedesign/App.java
@@ -0,0 +1,53 @@
+package udacityteam.healthapp.completeRedesign;
+
+import android.app.Activity;
+import android.app.Application;
+import android.app.Service;
+import android.content.BroadcastReceiver;
+
+import javax.inject.Inject;
+
+import dagger.android.AndroidInjector;
+import dagger.android.DispatchingAndroidInjector;
+import dagger.android.HasActivityInjector;
+import dagger.android.HasBroadcastReceiverInjector;
+import dagger.android.HasServiceInjector;
+
+public class App extends Application
+ // implements HasActivityInjector, HasServiceInjector, HasBroadcastReceiverInjector
+{
+
+//
+// @Override
+// public void onCreate() {
+// super.onCreate();
+// DaggerAppComponent.builder()
+// .application(this)
+// .build()
+// .inject(this);
+// }
+//
+// @Inject
+// DispatchingAndroidInjector dispatchingAndroidInjector;
+//
+// @Inject
+// DispatchingAndroidInjector dispatchingBroadcastReceiverInjector;
+//
+// @Inject
+// DispatchingAndroidInjector dispatchingServiceInjector;
+//
+// @Override
+// public DispatchingAndroidInjector activityInjector() {
+// return dispatchingAndroidInjector;
+// }
+//
+// @Override
+// public DispatchingAndroidInjector serviceInjector() {
+// return dispatchingServiceInjector;
+// }
+//
+// @Override
+// public AndroidInjector broadcastReceiverInjector() {
+// return dispatchingBroadcastReceiverInjector;
+// }
+}
diff --git a/app/src/main/java/udacityteam/healthapp/completeRedesign/Dagger2/ActivityModule.java b/app/src/main/java/udacityteam/healthapp/completeRedesign/Dagger2/ActivityModule.java
new file mode 100644
index 0000000..5680e79
--- /dev/null
+++ b/app/src/main/java/udacityteam/healthapp/completeRedesign/Dagger2/ActivityModule.java
@@ -0,0 +1,16 @@
+package udacityteam.healthapp.completeRedesign.Dagger2;
+
+
+import dagger.Module;
+import dagger.android.ContributesAndroidInjector;
+import udacityteam.healthapp.activities.CommunityActivities.CommunityList;
+
+@Module
+public abstract class ActivityModule {
+ @ContributesAndroidInjector(modules = CommunityListFragmentsModule.class)
+ abstract CommunityList contributeMainActivity();
+
+// @ContributesAndroidInjector()
+// abstract BaseActivity contributeBaseActivity();
+}
+
diff --git a/app/src/main/java/udacityteam/healthapp/completeRedesign/Dagger2/AppComponent.java b/app/src/main/java/udacityteam/healthapp/completeRedesign/Dagger2/AppComponent.java
new file mode 100644
index 0000000..c6957fd
--- /dev/null
+++ b/app/src/main/java/udacityteam/healthapp/completeRedesign/Dagger2/AppComponent.java
@@ -0,0 +1,38 @@
+package udacityteam.healthapp.completeRedesign.Dagger2;
+
+
+import android.app.Application;
+
+import javax.inject.Singleton;
+
+import dagger.BindsInstance;
+import dagger.Component;
+import dagger.android.AndroidInjectionModule;
+import udacityteam.healthapp.app.ApplicationController;
+
+@Singleton
+@Component(modules = {ActivityModule.class,
+ AndroidInjectionModule.class,
+ // DetailsOfRecipeActivityModule.class,
+ RemoteViewsService.class,
+ BaseActivityModule.class,
+ // BakingAppWidgetModule.class,
+ AppModule.class})
+
+
+public interface AppComponent {
+ void inject(ApplicationController app);
+
+ @Component.Builder
+ interface Builder {
+ @BindsInstance
+ Builder application(Application application);
+
+ AppComponent build();
+
+ }
+
+ // void inject(BakingAppWidget bakingAppWidget);
+
+}
+
diff --git a/app/src/main/java/udacityteam/healthapp/completeRedesign/Dagger2/AppExecutors.java b/app/src/main/java/udacityteam/healthapp/completeRedesign/Dagger2/AppExecutors.java
new file mode 100644
index 0000000..60b3298
--- /dev/null
+++ b/app/src/main/java/udacityteam/healthapp/completeRedesign/Dagger2/AppExecutors.java
@@ -0,0 +1,46 @@
+package udacityteam.healthapp.completeRedesign.Dagger2;
+
+import android.os.Handler;
+import android.os.Looper;
+import android.support.annotation.NonNull;
+
+import java.util.concurrent.Executor;
+import java.util.concurrent.Executors;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+@Singleton
+public class AppExecutors {
+
+ private final Executor diskIO;
+ private final Executor mainThread;
+
+ public AppExecutors(Executor diskIO, Executor mainThread) {
+ this.diskIO = diskIO;
+ this.mainThread = mainThread;
+ }
+
+ @Inject
+ public AppExecutors() {
+ this(Executors.newSingleThreadExecutor(),
+ new MainThreadExecutor());
+ }
+
+ public Executor diskIO() {
+ return diskIO;
+ }
+
+ public Executor mainThread() {
+ return mainThread;
+ }
+
+ private static class MainThreadExecutor implements Executor {
+ private final Handler mainThreadHandler = new Handler(Looper.getMainLooper());
+
+ @Override
+ public void execute(@NonNull Runnable command) {
+ mainThreadHandler.post(command);
+ }
+ }
+}
diff --git a/app/src/main/java/udacityteam/healthapp/completeRedesign/Dagger2/AppModule.java b/app/src/main/java/udacityteam/healthapp/completeRedesign/Dagger2/AppModule.java
new file mode 100644
index 0000000..35545f2
--- /dev/null
+++ b/app/src/main/java/udacityteam/healthapp/completeRedesign/Dagger2/AppModule.java
@@ -0,0 +1,62 @@
+package udacityteam.healthapp.completeRedesign.Dagger2;
+
+import android.app.Application;
+import android.arch.persistence.room.Room;
+import android.content.SharedPreferences;
+import android.preference.PreferenceManager;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+
+import java.util.concurrent.TimeUnit;
+
+import javax.inject.Singleton;
+
+import dagger.Module;
+import dagger.Provides;
+import okhttp3.OkHttpClient;
+import okhttp3.logging.HttpLoggingInterceptor;
+import retrofit2.Retrofit;
+import retrofit2.converter.gson.GsonConverterFactory;
+import udacityteam.healthapp.Network.PHPService;
+import udacityteam.healthapp.completeRedesign.Data.Networking.API.APIService;
+import udacityteam.healthapp.completeRedesign.Data.Networking.API.LiveDataCallAdapterFactory;
+import udacityteam.healthapp.completeRedesign.db.MainDatabase;
+
+@Module(includes = ViewModelsModule.class)
+public class AppModule {
+ @Provides
+ @Singleton
+ APIService apiService_create() {
+ Gson gson = new GsonBuilder()
+ .setLenient()
+ .create();
+ HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
+ interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
+ OkHttpClient client = new OkHttpClient.Builder()
+ .addInterceptor(interceptor)
+ .connectTimeout(30, TimeUnit.SECONDS)
+ .writeTimeout(30, TimeUnit.SECONDS)
+ .readTimeout(10, TimeUnit.SECONDS)
+ .build();
+ Retrofit retrofit = new Retrofit.Builder()
+ .baseUrl(APIService.BASE_URL)
+ .addConverterFactory(GsonConverterFactory.create(gson))
+ .addCallAdapterFactory(new LiveDataCallAdapterFactory())
+ .client(client)
+ .build();
+ return retrofit.create(APIService.class);
+ }
+
+ @Singleton
+ @Provides
+ MainDatabase mainDatabase_create(Application application) {
+ return Room.databaseBuilder(application, MainDatabase.class, "baking_app5").build();
+ }
+
+ @Provides
+ @Singleton
+ SharedPreferences providesSharedPreferences(Application app) {
+ return PreferenceManager.getDefaultSharedPreferences(app);
+ }
+}
diff --git a/app/src/main/java/udacityteam/healthapp/completeRedesign/Dagger2/BakingAppWidgetModule.java b/app/src/main/java/udacityteam/healthapp/completeRedesign/Dagger2/BakingAppWidgetModule.java
new file mode 100644
index 0000000..bbc0259
--- /dev/null
+++ b/app/src/main/java/udacityteam/healthapp/completeRedesign/Dagger2/BakingAppWidgetModule.java
@@ -0,0 +1,11 @@
+package udacityteam.healthapp.completeRedesign.Dagger2;
+
+
+import dagger.Module;
+import dagger.android.ContributesAndroidInjector;
+
+@Module
+public abstract class BakingAppWidgetModule {
+// @ContributesAndroidInjector()
+// abstract BakingAppWidget contributeBakingAppWidget();
+}
diff --git a/app/src/main/java/udacityteam/healthapp/completeRedesign/Dagger2/BaseActivityModule.java b/app/src/main/java/udacityteam/healthapp/completeRedesign/Dagger2/BaseActivityModule.java
new file mode 100644
index 0000000..4afd252
--- /dev/null
+++ b/app/src/main/java/udacityteam/healthapp/completeRedesign/Dagger2/BaseActivityModule.java
@@ -0,0 +1,14 @@
+package udacityteam.healthapp.completeRedesign.Dagger2;
+
+
+import dagger.Module;
+import dagger.android.ContributesAndroidInjector;
+import udacityteam.healthapp.activities.BaseActivity;
+
+@Module
+public abstract class BaseActivityModule {
+
+ @ContributesAndroidInjector()
+ abstract BaseActivity contributeBaseActivity();
+}
+
diff --git a/app/src/main/java/udacityteam/healthapp/completeRedesign/Dagger2/CommunityListFragmentsModule.java b/app/src/main/java/udacityteam/healthapp/completeRedesign/Dagger2/CommunityListFragmentsModule.java
new file mode 100644
index 0000000..6496dc2
--- /dev/null
+++ b/app/src/main/java/udacityteam/healthapp/completeRedesign/Dagger2/CommunityListFragmentsModule.java
@@ -0,0 +1,16 @@
+package udacityteam.healthapp.completeRedesign.Dagger2;
+
+
+import dagger.Module;
+import dagger.android.ContributesAndroidInjector;
+import udacityteam.healthapp.activities.CommunityActivities.SharedFoodListFragmentNetwork;
+
+@Module
+public abstract class CommunityListFragmentsModule {
+// @ContributesAndroidInjector()
+// abstract DetailStepFragment contributeDetailStepFragmenty();
+//
+ @ContributesAndroidInjector()
+ abstract SharedFoodListFragmentNetwork contributeSharedFoodListFragmentNetwork();
+
+}
diff --git a/app/src/main/java/udacityteam/healthapp/completeRedesign/Dagger2/DetailsOfRecipeActivityModule.java b/app/src/main/java/udacityteam/healthapp/completeRedesign/Dagger2/DetailsOfRecipeActivityModule.java
new file mode 100644
index 0000000..cfc1df3
--- /dev/null
+++ b/app/src/main/java/udacityteam/healthapp/completeRedesign/Dagger2/DetailsOfRecipeActivityModule.java
@@ -0,0 +1,12 @@
+package udacityteam.healthapp.completeRedesign.Dagger2;
+
+
+import dagger.Module;
+import dagger.android.ContributesAndroidInjector;
+
+@Module
+public abstract class DetailsOfRecipeActivityModule {
+// @ContributesAndroidInjector(modules = CommunityListFragmentsModule.class)
+// abstract DetailsOfRecipeActivity contributeDetailsOfRecipeActivity();
+
+}
diff --git a/app/src/main/java/udacityteam/healthapp/completeRedesign/Dagger2/LoginRegisterFragmentModule.java b/app/src/main/java/udacityteam/healthapp/completeRedesign/Dagger2/LoginRegisterFragmentModule.java
new file mode 100644
index 0000000..90cbcab
--- /dev/null
+++ b/app/src/main/java/udacityteam/healthapp/completeRedesign/Dagger2/LoginRegisterFragmentModule.java
@@ -0,0 +1,16 @@
+package udacityteam.healthapp.completeRedesign.Dagger2;
+
+
+import dagger.Module;
+import dagger.android.ContributesAndroidInjector;
+import udacityteam.healthapp.activities.CommunityActivities.SharedFoodListFragmentNetwork;
+
+@Module
+public abstract class LoginRegisterFragmentModule {
+// @ContributesAndroidInjector()
+// abstract DetailStepFragment contributeDetailStepFragmenty();
+//
+// @ContributesAndroidInjector()
+// abstract SharedFoodListFragmentNetwork contributeSharedFoodListFragmentNetwork();
+
+}
diff --git a/app/src/main/java/udacityteam/healthapp/completeRedesign/Dagger2/RemoteViewsService.java b/app/src/main/java/udacityteam/healthapp/completeRedesign/Dagger2/RemoteViewsService.java
new file mode 100644
index 0000000..c0eb0a8
--- /dev/null
+++ b/app/src/main/java/udacityteam/healthapp/completeRedesign/Dagger2/RemoteViewsService.java
@@ -0,0 +1,11 @@
+package udacityteam.healthapp.completeRedesign.Dagger2;
+
+
+import dagger.Module;
+import dagger.android.ContributesAndroidInjector;
+
+@Module
+public abstract class RemoteViewsService {
+// @ContributesAndroidInjector()
+// abstract BakingAppWidgetService contributeRemoteViewsService();
+}
diff --git a/app/src/main/java/udacityteam/healthapp/completeRedesign/Dagger2/ViewModelFactory.java b/app/src/main/java/udacityteam/healthapp/completeRedesign/Dagger2/ViewModelFactory.java
new file mode 100644
index 0000000..482843d
--- /dev/null
+++ b/app/src/main/java/udacityteam/healthapp/completeRedesign/Dagger2/ViewModelFactory.java
@@ -0,0 +1,44 @@
+package udacityteam.healthapp.completeRedesign.Dagger2;
+
+import android.arch.lifecycle.ViewModel;
+import android.arch.lifecycle.ViewModelProvider;
+import android.support.annotation.NonNull;
+
+import java.util.Map;
+
+import javax.inject.Inject;
+import javax.inject.Provider;
+import javax.inject.Singleton;
+
+@Singleton
+public class ViewModelFactory implements ViewModelProvider.Factory {
+ private final Map, Provider> creators;
+
+ @Inject
+ public ViewModelFactory(Map, Provider> creators) {
+ this.creators = creators;
+ }
+
+ @NonNull
+ @SuppressWarnings("unchecked")
+ @Override
+ public T create(@NonNull Class modelClass) {
+ Provider extends ViewModel> creator = creators.get(modelClass);
+ if (creator == null) {
+ for (Map.Entry, Provider> entry : creators.entrySet()) {
+ if (modelClass.isAssignableFrom(entry.getKey())) {
+ creator = entry.getValue();
+ break;
+ }
+ }
+ }
+ if (creator == null) {
+ throw new IllegalArgumentException("unknown model class " + modelClass);
+ }
+ try {
+ return (T) creator.get();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+}
\ No newline at end of file
diff --git a/app/src/main/java/udacityteam/healthapp/completeRedesign/Dagger2/ViewModelsKey.java b/app/src/main/java/udacityteam/healthapp/completeRedesign/Dagger2/ViewModelsKey.java
new file mode 100644
index 0000000..01a76d1
--- /dev/null
+++ b/app/src/main/java/udacityteam/healthapp/completeRedesign/Dagger2/ViewModelsKey.java
@@ -0,0 +1,19 @@
+package udacityteam.healthapp.completeRedesign.Dagger2;
+
+import android.arch.lifecycle.ViewModel;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+import dagger.MapKey;
+
+@Documented
+@Target({ElementType.METHOD})
+@Retention(RetentionPolicy.RUNTIME)
+@MapKey
+@interface ViewModelsKey {
+ Class extends ViewModel> value();
+}
diff --git a/app/src/main/java/udacityteam/healthapp/completeRedesign/Dagger2/ViewModelsModule.java b/app/src/main/java/udacityteam/healthapp/completeRedesign/Dagger2/ViewModelsModule.java
new file mode 100644
index 0000000..0e7722b
--- /dev/null
+++ b/app/src/main/java/udacityteam/healthapp/completeRedesign/Dagger2/ViewModelsModule.java
@@ -0,0 +1,29 @@
+package udacityteam.healthapp.completeRedesign.Dagger2;
+
+import android.arch.lifecycle.ViewModel;
+import android.arch.lifecycle.ViewModelProvider;
+
+import dagger.Binds;
+import dagger.Module;
+import dagger.multibindings.IntoMap;
+import udacityteam.healthapp.activities.CommunityActivities.SharedFoodListFragmentNetwork;
+import udacityteam.healthapp.activities.CommunityActivities.SharedFoodListsViewModelNew;
+import udacityteam.healthapp.activities.LoginRegisterViewModel;
+
+@Module
+public abstract class ViewModelsModule {
+
+ @Binds
+ abstract ViewModelProvider.Factory bindViewModelsFactory(ViewModelFactory viewModelFactory);
+
+
+ @Binds
+ @IntoMap
+ @ViewModelsKey(SharedFoodListsViewModelNew.class)
+ abstract ViewModel bindSharedFoodListsViewModelNew(SharedFoodListsViewModelNew mainViewModel);
+
+ @Binds
+ @IntoMap
+ @ViewModelsKey(LoginRegisterViewModel.class)
+ abstract ViewModel bindLoginRegisterViewModel(LoginRegisterViewModel mainViewModel);
+}
diff --git a/app/src/main/java/udacityteam/healthapp/completeRedesign/Data/Networking/API/APIService.java b/app/src/main/java/udacityteam/healthapp/completeRedesign/Data/Networking/API/APIService.java
new file mode 100644
index 0000000..2c393a9
--- /dev/null
+++ b/app/src/main/java/udacityteam/healthapp/completeRedesign/Data/Networking/API/APIService.java
@@ -0,0 +1,141 @@
+package udacityteam.healthapp.completeRedesign.Data.Networking.API;
+
+
+import android.arch.lifecycle.LiveData;
+
+import java.sql.Timestamp;
+import java.util.List;
+
+import retrofit2.Call;
+import retrofit2.http.Field;
+import retrofit2.http.FormUrlEncoded;
+import retrofit2.http.GET;
+import retrofit2.http.POST;
+import retrofit2.http.Path;
+import retrofit2.http.Query;
+import rx.Observable;
+import udacityteam.healthapp.Model.OneSharedFoodProductsListRetrofit;
+import udacityteam.healthapp.Model.Result;
+import udacityteam.healthapp.Model.SelectedFoodretrofitarray;
+import udacityteam.healthapp.Model.SharedFoodProductsRetrofit;
+import udacityteam.healthapp.Model.Usersretrofit;
+
+/**
+ * Created by Belal on 14/04/17.
+ */
+
+public interface APIService {
+
+ public static final String BASE_URL = "http://app.wellbranding.com/";
+
+ @FormUrlEncoded
+ @POST("register")
+ Call createUser(
+ @Field("name") String name,
+ @Field("email") String email,
+ @Field("uid") String uid);
+
+
+ @FormUrlEncoded
+ @POST("login")
+ Observable userLogin(
+ @Field("email") String email,
+ @Field("password") String password
+ );
+ @FormUrlEncoded
+ @POST("loginwithmail")
+ Observable userLoginwithmail(
+ @Field("email") String email,
+ @Field("password") String password,
+ @Field("uid") String uid
+ );
+ @FormUrlEncoded
+ @POST("addSelectedFood")
+ Call addSelectedFood(
+ @Field("foodId") String foodId,
+ @Field("foodName") String foodName,
+ @Field("UserId") Integer UserId,
+ @Field("Date") Timestamp Date,
+ @Field("Calories") Float Calories,
+ @Field("Protein") Float Protein,
+ @Field("Fat") Float Fat,
+ @Field("Carbohydrates") Float Carbohyrates,
+ @Field("whichtime") String whichtime,
+ @Field("sharedfoodId") Integer sharedFoodId
+ );
+ @FormUrlEncoded
+ @POST("addSharedList")
+ Observable addSharedList(
+ @Field("UserId") Integer UserId,
+ @Field("Date") Timestamp Date,
+ @Field("SharedFoodListDatabase") String SharedFoodListDatabase,
+ @Field("whichtime") String whichtime,
+ @Field("Calories") Float Calories,
+ @Field("Protein") Float Protein,
+ @Field("Fat") Float Fat,
+ @Field("Carbohydrates") Float Carbohyrates
+ );
+
+ @GET("getUserByUid")
+ Observable getCurrentUser(
+ @Query("UserId") String UserId
+
+ );
+ @GET("getSelectedFoods")
+ Observable getselectedfoods(
+ @Query("UserId") Integer UserId,
+ @Query("whichtime") String whichtime,
+ @Query("year") String year,
+ @Query("month") String month,
+ @Query("day") String day
+ );
+ @GET("getSelectedFoodsPrieview")
+ Observable getselectedfoodsPrieview(
+ @Query("getParentSharedFoodsId") Integer ParentSharedKey,
+ @Query("foodselection") String foodSelection
+ );
+
+ @GET("users")
+ Observable getUsers();
+
+ @GET("getAllSharedDiets")
+ LiveData> getAllSharedDiets(
+ @Query("UserId") Integer UserId,
+ @Query("SharedFoodListDatabase") String SharedFoodListDatabase
+ );
+ @GET("getAllFilteredSharedDiets")
+ Observable getAllFilteredSharedDiets(
+ @Query("UserId") Integer UserId,
+ @Query("SharedFoodListDatabase") String SharedFoodListDatabase,
+ @Query("ProteinBegin") Integer proteinbegin,
+ @Query("ProteinEnd") Integer proteinend,
+ @Query("CaloriesBegin") Integer caloriesbegin,
+ @Query("CaloriesEnd") Integer caloriesend,
+ @Query("CarbohydratesBegin") Integer carbohydratesbegin,
+ @Query("CarbohydratesEnd") Integer carbohydratesend,
+ @Query("FatsBegin") Integer fatsbegin,
+ @Query("FatsEnd") Integer fatssend
+
+ );
+
+ @GET("IsShared")
+ Observable getIsShared
+ (
+ @Query("UserId") Integer UserId,
+ @Query("date") Timestamp Date,
+ @Query("whichtime") String whichtime
+ );
+
+ @GET("usersquery")
+ Observable getUsersquery();
+
+ @GET("tasks/{sort}")
+ Observable getTasks(
+ @Path("sort") String order);
+ @GET("qur")
+ Call getqur(
+ @Query("value") String value,
+ @Query("name") String name);
+
+
+}
diff --git a/app/src/main/java/udacityteam/healthapp/completeRedesign/Data/Networking/API/APIUrl.java b/app/src/main/java/udacityteam/healthapp/completeRedesign/Data/Networking/API/APIUrl.java
new file mode 100644
index 0000000..2352697
--- /dev/null
+++ b/app/src/main/java/udacityteam/healthapp/completeRedesign/Data/Networking/API/APIUrl.java
@@ -0,0 +1,5 @@
+package udacityteam.healthapp.completeRedesign.Data.Networking.API;
+
+public class APIUrl {
+ public static final String BASE_URL = "https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/";
+}
\ No newline at end of file
diff --git a/app/src/main/java/udacityteam/healthapp/completeRedesign/Data/Networking/API/ApiResponse.java b/app/src/main/java/udacityteam/healthapp/completeRedesign/Data/Networking/API/ApiResponse.java
new file mode 100644
index 0000000..fdfeb40
--- /dev/null
+++ b/app/src/main/java/udacityteam/healthapp/completeRedesign/Data/Networking/API/ApiResponse.java
@@ -0,0 +1,47 @@
+package udacityteam.healthapp.completeRedesign.Data.Networking.API;
+
+import android.support.annotation.Nullable;
+
+import java.io.IOException;
+
+import retrofit2.Response;
+
+public class ApiResponse {
+ public final int code;
+ @Nullable
+ public final T body;
+ @Nullable
+ public final String errorMessage;
+
+ public ApiResponse(Throwable error) {
+ code = 500;
+ body = null;
+ errorMessage = error.getMessage();
+ }
+
+ public ApiResponse(Response response) {
+ code = response.code();
+ if (response.isSuccessful()) {
+ body = response.body();
+ errorMessage = null;
+ } else {
+ String message = null;
+ if (response.errorBody() != null) {
+ try {
+ message = response.errorBody().string();
+ } catch (IOException ignored) {
+
+ }
+ }
+ if (message == null || message.trim().length() == 0) {
+ message = response.message();
+ }
+ errorMessage = message;
+ body = null;
+ }
+ }
+
+ public boolean isSuccessful() {
+ return code >= 200 && code < 300;
+ }
+}
diff --git a/app/src/main/java/udacityteam/healthapp/completeRedesign/Data/Networking/API/LiveDataCallAdapter.java b/app/src/main/java/udacityteam/healthapp/completeRedesign/Data/Networking/API/LiveDataCallAdapter.java
new file mode 100644
index 0000000..f973cba
--- /dev/null
+++ b/app/src/main/java/udacityteam/healthapp/completeRedesign/Data/Networking/API/LiveDataCallAdapter.java
@@ -0,0 +1,54 @@
+package udacityteam.healthapp.completeRedesign.Data.Networking.API;
+
+import android.arch.lifecycle.LiveData;
+
+import java.lang.reflect.Type;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import retrofit2.Call;
+import retrofit2.CallAdapter;
+import retrofit2.Callback;
+import retrofit2.Response;
+
+/**
+ * A Retrofit adapter that converts the Call into a LiveData of ApiResponse.
+ *
+ * @param
+ */
+public class LiveDataCallAdapter implements CallAdapter>> {
+ private final Type responseType;
+
+ public LiveDataCallAdapter(Type responseType) {
+ this.responseType = responseType;
+ }
+
+ @Override
+ public Type responseType() {
+ return responseType;
+ }
+
+ @Override
+ public LiveData> adapt(Call call) {
+ return new LiveData>() {
+ final AtomicBoolean started = new AtomicBoolean(false);
+
+ @Override
+ protected void onActive() {
+ super.onActive();
+ if (started.compareAndSet(false, true)) {
+ call.enqueue(new Callback() {
+ @Override
+ public void onResponse(Call call, Response response) {
+ postValue(new ApiResponse<>(response));
+ }
+
+ @Override
+ public void onFailure(Call call, Throwable throwable) {
+ postValue(new ApiResponse<>(throwable));
+ }
+ });
+ }
+ }
+ };
+ }
+}
\ No newline at end of file
diff --git a/app/src/main/java/udacityteam/healthapp/completeRedesign/Data/Networking/API/LiveDataCallAdapterFactory.java b/app/src/main/java/udacityteam/healthapp/completeRedesign/Data/Networking/API/LiveDataCallAdapterFactory.java
new file mode 100644
index 0000000..acd7de9
--- /dev/null
+++ b/app/src/main/java/udacityteam/healthapp/completeRedesign/Data/Networking/API/LiveDataCallAdapterFactory.java
@@ -0,0 +1,30 @@
+package udacityteam.healthapp.completeRedesign.Data.Networking.API;
+
+import android.arch.lifecycle.LiveData;
+
+import java.lang.annotation.Annotation;
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+
+import retrofit2.CallAdapter;
+import retrofit2.Retrofit;
+
+public class LiveDataCallAdapterFactory extends CallAdapter.Factory {
+
+ @Override
+ public CallAdapter, ?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
+ if (getRawType(returnType) != LiveData.class) {
+ return null;
+ }
+ Type observableType = getParameterUpperBound(0, (ParameterizedType) returnType);
+ Class> rawObservableType = getRawType(observableType);
+ if (rawObservableType != ApiResponse.class) {
+ throw new IllegalArgumentException("type must be a resource");
+ }
+ if (!(observableType instanceof ParameterizedType)) {
+ throw new IllegalArgumentException("resource must be parameterized");
+ }
+ Type bodyType = getParameterUpperBound(0, (ParameterizedType) observableType);
+ return new LiveDataCallAdapter<>(bodyType);
+ }
+}
diff --git a/app/src/main/java/udacityteam/healthapp/completeRedesign/Data/Networking/API/NEW_API_GOOD_SERVICE.java b/app/src/main/java/udacityteam/healthapp/completeRedesign/Data/Networking/API/NEW_API_GOOD_SERVICE.java
new file mode 100644
index 0000000..2e65e4c
--- /dev/null
+++ b/app/src/main/java/udacityteam/healthapp/completeRedesign/Data/Networking/API/NEW_API_GOOD_SERVICE.java
@@ -0,0 +1,129 @@
+package udacityteam.healthapp.completeRedesign.Data.Networking.API;
+
+import java.sql.Timestamp;
+
+import retrofit2.Call;
+import retrofit2.http.Field;
+import retrofit2.http.FormUrlEncoded;
+import retrofit2.http.GET;
+import retrofit2.http.POST;
+import retrofit2.http.Path;
+import retrofit2.http.Query;
+import rx.Observable;
+import udacityteam.healthapp.Model.Result;
+import udacityteam.healthapp.Model.SelectedFoodretrofitarray;
+import udacityteam.healthapp.Model.SharedFoodProductsRetrofit;
+import udacityteam.healthapp.Model.Usersretrofit;
+
+public interface NEW_API_GOOD_SERVICE {
+ public static final String BASE_URL = "http://app.wellbranding.com/";
+
+ @FormUrlEncoded
+ @POST("register")
+ Observable createUser(
+ @Field("name") String name,
+ @Field("email") String email,
+ @Field("uid") String uid);
+
+
+ @FormUrlEncoded
+ @POST("login")
+ Observable userLogin(
+ @Field("email") String email,
+ @Field("password") String password
+ );
+ @FormUrlEncoded
+ @POST("loginwithmail")
+ Observable userLoginwithmail(
+ @Field("email") String email,
+ @Field("password") String password,
+ @Field("uid") String uid
+ );
+ @FormUrlEncoded
+ @POST("addSelectedFood")
+ Call addSelectedFood(
+ @Field("foodId") String foodId,
+ @Field("foodName") String foodName,
+ @Field("UserId") Integer UserId,
+ @Field("Date") Timestamp Date,
+ @Field("Calories") Float Calories,
+ @Field("Protein") Float Protein,
+ @Field("Fat") Float Fat,
+ @Field("Carbohydrates") Float Carbohyrates,
+ @Field("whichtime") String whichtime,
+ @Field("sharedfoodId") Integer sharedFoodId
+ );
+ @FormUrlEncoded
+ @POST("addSharedList")
+ Observable addSharedList(
+ @Field("UserId") Integer UserId,
+ @Field("Date") Timestamp Date,
+ @Field("SharedFoodListDatabase") String SharedFoodListDatabase,
+ @Field("whichtime") String whichtime,
+ @Field("Calories") Float Calories,
+ @Field("Protein") Float Protein,
+ @Field("Fat") Float Fat,
+ @Field("Carbohydrates") Float Carbohyrates
+ );
+
+ @GET("getUserByUid")
+ Observable getCurrentUser(
+ @Query("UserId") String UserId
+
+ );
+ @GET("getSelectedFoods")
+ Observable getselectedfoods(
+ @Query("UserId") Integer UserId,
+ @Query("whichtime") String whichtime,
+ @Query("year") String year,
+ @Query("month") String month,
+ @Query("day") String day
+ );
+ @GET("getSelectedFoodsPrieview")
+ Observable getselectedfoodsPrieview(
+ @Query("getParentSharedFoodsId") Integer ParentSharedKey,
+ @Query("foodselection") String foodSelection
+ );
+
+ @GET("users")
+ Observable getUsers();
+
+ @GET("getAllSharedDiets")
+ Observable getAllSharedDiets(
+ @Query("UserId") Integer UserId,
+ @Query("SharedFoodListDatabase") String SharedFoodListDatabase
+ );
+ @GET("getAllFilteredSharedDiets")
+ Observable getAllFilteredSharedDiets(
+ @Query("UserId") Integer UserId,
+ @Query("SharedFoodListDatabase") String SharedFoodListDatabase,
+ @Query("ProteinBegin") Integer proteinbegin,
+ @Query("ProteinEnd") Integer proteinend,
+ @Query("CaloriesBegin") Integer caloriesbegin,
+ @Query("CaloriesEnd") Integer caloriesend,
+ @Query("CarbohydratesBegin") Integer carbohydratesbegin,
+ @Query("CarbohydratesEnd") Integer carbohydratesend,
+ @Query("FatsBegin") Integer fatsbegin,
+ @Query("FatsEnd") Integer fatssend
+
+ );
+
+ @GET("IsShared")
+ Observable getIsShared
+ (
+ @Query("UserId") Integer UserId,
+ @Query("date") Timestamp Date,
+ @Query("whichtime") String whichtime
+ );
+
+ @GET("usersquery")
+ Observable getUsersquery();
+
+ @GET("tasks/{sort}")
+ Observable getTasks(
+ @Path("sort") String order);
+ @GET("qur")
+ Call getqur(
+ @Query("value") String value,
+ @Query("name") String name);
+}
diff --git a/app/src/main/java/udacityteam/healthapp/completeRedesign/Data/Networking/API/RetrofitFactory.java b/app/src/main/java/udacityteam/healthapp/completeRedesign/Data/Networking/API/RetrofitFactory.java
new file mode 100644
index 0000000..857c1c5
--- /dev/null
+++ b/app/src/main/java/udacityteam/healthapp/completeRedesign/Data/Networking/API/RetrofitFactory.java
@@ -0,0 +1,34 @@
+package udacityteam.healthapp.completeRedesign.Data.Networking.API;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+
+import java.util.concurrent.TimeUnit;
+
+import okhttp3.OkHttpClient;
+import okhttp3.logging.HttpLoggingInterceptor;
+import retrofit2.Retrofit;
+import retrofit2.converter.gson.GsonConverterFactory;
+
+public interface RetrofitFactory {
+ static APIService create() {
+ Gson gson = new GsonBuilder()
+ .setLenient()
+ .create();
+ HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
+ interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
+ OkHttpClient client = new OkHttpClient.Builder()
+ .addInterceptor(interceptor)
+ .connectTimeout(30, TimeUnit.SECONDS)
+ .writeTimeout(30, TimeUnit.SECONDS)
+ .readTimeout(10, TimeUnit.SECONDS)
+ .build();
+ Retrofit retrofit = new Retrofit.Builder()
+ .baseUrl(APIService.BASE_URL)
+ .addConverterFactory(GsonConverterFactory.create(gson))
+ .addCallAdapterFactory(new LiveDataCallAdapterFactory())
+ .client(client)
+ .build();
+ return retrofit.create(APIService.class);
+ }
+}
diff --git a/app/src/main/java/udacityteam/healthapp/completeRedesign/Data/Networking/API/RetrofitFactoryNew.java b/app/src/main/java/udacityteam/healthapp/completeRedesign/Data/Networking/API/RetrofitFactoryNew.java
new file mode 100644
index 0000000..1763342
--- /dev/null
+++ b/app/src/main/java/udacityteam/healthapp/completeRedesign/Data/Networking/API/RetrofitFactoryNew.java
@@ -0,0 +1,34 @@
+package udacityteam.healthapp.completeRedesign.Data.Networking.API;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+
+import java.util.concurrent.TimeUnit;
+
+import okhttp3.OkHttpClient;
+import okhttp3.logging.HttpLoggingInterceptor;
+import retrofit2.Retrofit;
+import retrofit2.converter.gson.GsonConverterFactory;
+
+public interface RetrofitFactoryNew {
+ static APIService create() {
+ Gson gson = new GsonBuilder()
+ .setLenient()
+ .create();
+ HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
+ interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
+ OkHttpClient client = new OkHttpClient.Builder()
+ .addInterceptor(interceptor)
+ .connectTimeout(30, TimeUnit.SECONDS)
+ .writeTimeout(30, TimeUnit.SECONDS)
+ .readTimeout(10, TimeUnit.SECONDS)
+ .build();
+ Retrofit retrofit = new Retrofit.Builder()
+ .baseUrl(APIService.BASE_URL)
+ .addConverterFactory(GsonConverterFactory.create(gson))
+ .addCallAdapterFactory(new LiveDataCallAdapterFactory())
+ .client(client)
+ .build();
+ return retrofit.create(APIService.class);
+ }
+}
diff --git a/app/src/main/java/udacityteam/healthapp/completeRedesign/Data/Networking/Models/Ingredient.java b/app/src/main/java/udacityteam/healthapp/completeRedesign/Data/Networking/Models/Ingredient.java
new file mode 100644
index 0000000..7b90789
--- /dev/null
+++ b/app/src/main/java/udacityteam/healthapp/completeRedesign/Data/Networking/Models/Ingredient.java
@@ -0,0 +1,93 @@
+package udacityteam.healthapp.completeRedesign.Data.Networking.Models;
+
+
+import android.arch.persistence.room.Entity;
+import android.arch.persistence.room.PrimaryKey;
+import android.os.Parcel;
+import android.os.Parcelable;
+
+import com.google.gson.annotations.Expose;
+import com.google.gson.annotations.SerializedName;
+
+@Entity
+public class Ingredient implements Parcelable {
+
+ @PrimaryKey(autoGenerate = true)
+ private int roomId;
+ @SerializedName("quantity")
+ @Expose
+ private Float quantity;
+ @SerializedName("measure")
+ @Expose
+ private String measure;
+ @SerializedName("ingredient")
+ @Expose
+ private String ingredient;
+ public final static Creator CREATOR = new Creator() {
+
+
+ @SuppressWarnings({
+ "unchecked"
+ })
+ public Ingredient createFromParcel(Parcel in) {
+ return new Ingredient(in);
+ }
+
+ public Ingredient[] newArray(int size) {
+ return (new Ingredient[size]);
+ }
+
+ };
+
+ protected Ingredient(Parcel in) {
+ this.quantity = ((Float) in.readValue((Float.class.getClassLoader())));
+ this.measure = ((String) in.readValue((String.class.getClassLoader())));
+ this.ingredient = ((String) in.readValue((String.class.getClassLoader())));
+ }
+
+ public int getRoomId() {
+ return roomId;
+ }
+
+ public void setRoomId(int roomId) {
+ this.roomId = roomId;
+ }
+
+ public Ingredient() {
+ }
+
+ public Float getQuantity() {
+ return quantity;
+ }
+
+ public void setQuantity(Float quantity) {
+ this.quantity = quantity;
+ }
+
+ public String getMeasure() {
+ return measure;
+ }
+
+ public void setMeasure(String measure) {
+ this.measure = measure;
+ }
+
+ public String getIngredient() {
+ return ingredient;
+ }
+
+ public void setIngredient(String ingredient) {
+ this.ingredient = ingredient;
+ }
+
+ public void writeToParcel(Parcel dest, int flags) {
+ dest.writeValue(quantity);
+ dest.writeValue(measure);
+ dest.writeValue(ingredient);
+ }
+
+ public int describeContents() {
+ return 0;
+ }
+
+}
\ No newline at end of file
diff --git a/app/src/main/java/udacityteam/healthapp/completeRedesign/DataConverterStep.java b/app/src/main/java/udacityteam/healthapp/completeRedesign/DataConverterStep.java
new file mode 100644
index 0000000..e170430
--- /dev/null
+++ b/app/src/main/java/udacityteam/healthapp/completeRedesign/DataConverterStep.java
@@ -0,0 +1,36 @@
+package udacityteam.healthapp.completeRedesign;
+
+import android.arch.persistence.room.TypeConverter;
+
+import com.google.gson.Gson;
+import com.google.gson.reflect.TypeToken;
+
+import java.lang.reflect.Type;
+import java.util.List;
+
+import udacityteam.healthapp.Model.UserProfile;
+import udacityteam.healthapp.models.User;
+
+public class DataConverterStep {
+ @TypeConverter
+ public String fromRoom(UserProfile roomStep) {
+ if (roomStep == null) {
+ return (null);
+ }
+ Gson gson = new Gson();
+ Type type = new TypeToken() {
+ }.getType();
+ return gson.toJson(roomStep, type);
+ }
+
+ @TypeConverter
+ public UserProfile toSteps(String step) {
+ if (step == null) {
+ return (null);
+ }
+ Gson gson = new Gson();
+ Type type = new TypeToken() {
+ }.getType();
+ return gson.fromJson(step, type);
+ }
+}
diff --git a/app/src/main/java/udacityteam/healthapp/completeRedesign/Repository/NetworkBoundResource.java b/app/src/main/java/udacityteam/healthapp/completeRedesign/Repository/NetworkBoundResource.java
new file mode 100644
index 0000000..d0878e1
--- /dev/null
+++ b/app/src/main/java/udacityteam/healthapp/completeRedesign/Repository/NetworkBoundResource.java
@@ -0,0 +1,104 @@
+package udacityteam.healthapp.completeRedesign.Repository;
+
+import android.arch.lifecycle.LiveData;
+import android.arch.lifecycle.MediatorLiveData;
+import android.os.AsyncTask;
+import android.support.annotation.MainThread;
+import android.support.annotation.NonNull;
+import android.support.annotation.Nullable;
+
+import udacityteam.healthapp.completeRedesign.Dagger2.AppExecutors;
+import udacityteam.healthapp.completeRedesign.Data.Networking.API.ApiResponse;
+
+public abstract class NetworkBoundResource {
+ private final MediatorLiveData> result = new MediatorLiveData<>();
+ AppExecutors appExecutors;
+
+ @MainThread
+ NetworkBoundResource(AppExecutors appExecutors) {
+
+ result.setValue(Resource.loading(null));
+ LiveData dbSource = loadFromDb();
+ this.appExecutors = appExecutors;
+ result.addSource(dbSource, data -> {
+ result.removeSource(dbSource);
+ if (shouldFetch(data)) {
+ fetchFromNetwork(dbSource);
+ } else {
+ result.addSource(dbSource,
+ newData -> result.setValue(Resource.success(newData)));
+ }
+ });
+ }
+
+ private void fetchFromNetwork(final LiveData dbSource) {
+ LiveData> apiResponse = createCall();
+ // we re-attach dbSource as a new source,
+ // it will dispatch its latest value quickly
+ result.addSource(dbSource,
+ newData -> result.setValue(Resource.loading(newData)));
+ result.addSource(apiResponse, response -> {
+ result.removeSource(apiResponse);
+ result.removeSource(dbSource);
+ //noinspection ConstantConditions
+ if (response.isSuccessful()) {
+ appExecutors.diskIO().execute(new Runnable() {
+ @Override
+ public void run() {
+ saveResultAndReInit(response);
+ appExecutors.mainThread().execute(new Runnable() {
+ @Override
+ public void run() {
+ result.addSource(loadFromDb(),
+ newData -> result.setValue(Resource.success(newData)));
+ }
+ });
+ }
+ });
+
+ } else {
+ // onFetchFailed();
+ result.addSource(dbSource,
+ newData -> result.setValue(
+ Resource.error(response.errorMessage, newData)));
+ }
+ });
+ }
+
+
+ @MainThread
+ private void saveResultAndReInit(ApiResponse response) {
+ new AsyncTask() {
+
+ @Override
+ protected Void doInBackground(Void... voids) {
+ saveCallResult(response.body);
+ return null;
+ }
+
+ @Override
+ protected void onPostExecute(Void aVoid) {
+ // we specially request a new live data,
+ // otherwise we will get immediately last cached value,
+ // which may not be updated with latest results received from network.
+ result.addSource(loadFromDb(),
+ newData -> result.setValue(Resource.success(newData)));
+ }
+ }.execute();
+ }
+
+ public final LiveData> getAsLiveData() {
+ return result;
+ }
+
+
+ protected abstract void saveCallResult(@NonNull RequestType item);
+
+ protected abstract boolean shouldFetch(@Nullable ResultType item);
+
+ @NonNull
+ protected abstract LiveData loadFromDb();
+
+ @NonNull
+ protected abstract LiveData> createCall();
+}
\ No newline at end of file
diff --git a/app/src/main/java/udacityteam/healthapp/completeRedesign/Repository/RecipiesRepository.java b/app/src/main/java/udacityteam/healthapp/completeRedesign/Repository/RecipiesRepository.java
new file mode 100644
index 0000000..a908621
--- /dev/null
+++ b/app/src/main/java/udacityteam/healthapp/completeRedesign/Repository/RecipiesRepository.java
@@ -0,0 +1,78 @@
+package udacityteam.healthapp.completeRedesign.Repository;
+
+import android.arch.lifecycle.LiveData;
+import android.support.annotation.NonNull;
+import android.support.annotation.Nullable;
+
+import java.util.List;
+
+import javax.inject.Inject;
+
+
+import udacityteam.healthapp.Model.OneSharedFoodProductsListRetrofit;
+import udacityteam.healthapp.Model.SharedFoodProductsRetrofit;
+import udacityteam.healthapp.completeRedesign.Dagger2.AppExecutors;
+import udacityteam.healthapp.completeRedesign.Data.Networking.API.APIService;
+import udacityteam.healthapp.completeRedesign.Data.Networking.API.ApiResponse;
+import udacityteam.healthapp.completeRedesign.Data.Networking.API.RetrofitFactoryNew;
+import udacityteam.healthapp.completeRedesign.db.MainDatabase;
+import udacityteam.healthapp.completeRedesign.db.RecipesMainDao;
+
+public class RecipiesRepository {
+
+ APIService webservice;
+ RecipesMainDao userDao;
+ APIService apiService;
+ AppExecutors appExecutors;
+ MainDatabase mainDatabase;
+
+ public MainDatabase getMainDatabase() {
+ return mainDatabase;
+ }
+
+
+
+ public RecipesMainDao getUserDao() {
+ return userDao;
+ }
+
+
+
+ @Inject
+ RecipiesRepository(AppExecutors appExecutors, APIService apiService, MainDatabase mainDatabase) {
+ userDao = mainDatabase.recipeDao();
+ this.appExecutors = appExecutors;
+ this.mainDatabase = mainDatabase;
+ this.apiService = apiService;
+
+ }
+
+ public LiveData>> loadRecipes() {
+ return new NetworkBoundResource,SharedFoodProductsRetrofit >(appExecutors) {
+ @Override
+ protected void saveCallResult(@NonNull SharedFoodProductsRetrofit item) {
+ userDao.insertAllOneSharedFoodProductsListRetrofit(item.getSelectedFoodretrofits());
+ }
+
+ @Override
+ protected boolean shouldFetch(@Nullable List data) {
+ return data == null ||
+ data.size()==0;
+ }
+
+ @NonNull @Override
+ protected LiveData> loadFromDb() {
+ return userDao.getRecipes();
+ }
+
+ @NonNull
+ @Override
+ protected LiveData> createCall() {
+ return RetrofitFactoryNew.create().getAllSharedDiets(2,"Dinner" );
+ }
+
+
+ }.getAsLiveData();
+ }
+}
+
diff --git a/app/src/main/java/udacityteam/healthapp/completeRedesign/Repository/Resource.java b/app/src/main/java/udacityteam/healthapp/completeRedesign/Repository/Resource.java
new file mode 100644
index 0000000..2e51a82
--- /dev/null
+++ b/app/src/main/java/udacityteam/healthapp/completeRedesign/Repository/Resource.java
@@ -0,0 +1,37 @@
+package udacityteam.healthapp.completeRedesign.Repository;
+
+import android.support.annotation.NonNull;
+import android.support.annotation.Nullable;
+
+import static udacityteam.healthapp.completeRedesign.Repository.Status.ERROR;
+import static udacityteam.healthapp.completeRedesign.Repository.Status.LOADING;
+import static udacityteam.healthapp.completeRedesign.Repository.Status.SUCCESS;
+
+public class Resource {
+ @NonNull
+ public final Status status;
+
+ @Nullable
+ public final String message;
+
+ @Nullable
+ public final T data;
+
+ public Resource(@NonNull Status status, @Nullable T data, @Nullable String message) {
+ this.status = status;
+ this.data = data;
+ this.message = message;
+ }
+
+ public static Resource success(@Nullable T data) {
+ return new Resource<>(SUCCESS, data, null);
+ }
+
+ public static Resource error(String msg, @Nullable T data) {
+ return new Resource<>(ERROR, data, msg);
+ }
+
+ public static Resource loading(@Nullable T data) {
+ return new Resource<>(LOADING, data, null);
+ }
+}
diff --git a/app/src/main/java/udacityteam/healthapp/completeRedesign/Repository/Status.java b/app/src/main/java/udacityteam/healthapp/completeRedesign/Repository/Status.java
new file mode 100644
index 0000000..6d7d70e
--- /dev/null
+++ b/app/src/main/java/udacityteam/healthapp/completeRedesign/Repository/Status.java
@@ -0,0 +1,7 @@
+package udacityteam.healthapp.completeRedesign.Repository;
+
+public enum Status {
+ SUCCESS,
+ ERROR,
+ LOADING
+}
diff --git a/app/src/main/java/udacityteam/healthapp/completeRedesign/db/MainDatabase.java b/app/src/main/java/udacityteam/healthapp/completeRedesign/db/MainDatabase.java
new file mode 100644
index 0000000..2005d67
--- /dev/null
+++ b/app/src/main/java/udacityteam/healthapp/completeRedesign/db/MainDatabase.java
@@ -0,0 +1,18 @@
+package udacityteam.healthapp.completeRedesign.db;
+
+import android.arch.persistence.room.Database;
+import android.arch.persistence.room.RoomDatabase;
+
+import udacityteam.healthapp.Model.OneSharedFoodProductsListRetrofit;
+import udacityteam.healthapp.Model.UserRetrofitGood;
+
+
+@Database(entities = {OneSharedFoodProductsListRetrofit.class,
+ UserRetrofitGood.class}, version = MainDatabase.VERSION)
+public abstract class MainDatabase extends RoomDatabase {
+
+ public abstract RecipesMainDao recipeDao();
+
+ static final int VERSION = 6;
+
+}
diff --git a/app/src/main/java/udacityteam/healthapp/completeRedesign/db/RecipesMainDao.java b/app/src/main/java/udacityteam/healthapp/completeRedesign/db/RecipesMainDao.java
new file mode 100644
index 0000000..c359fb4
--- /dev/null
+++ b/app/src/main/java/udacityteam/healthapp/completeRedesign/db/RecipesMainDao.java
@@ -0,0 +1,40 @@
+package udacityteam.healthapp.completeRedesign.db;
+
+import android.arch.lifecycle.LiveData;
+import android.arch.persistence.room.Dao;
+import android.arch.persistence.room.Insert;
+import android.arch.persistence.room.Query;
+import android.arch.persistence.room.Transaction;
+
+import java.util.List;
+
+import udacityteam.healthapp.Model.OneSharedFoodProductsListRetrofit;
+import udacityteam.healthapp.Model.UserRetrofitGood;
+import udacityteam.healthapp.Model.Userretrofit;
+
+
+@Dao
+public interface RecipesMainDao {
+ @Query("SELECT * FROM OneSharedFoodProductsListRetrofit")
+ public abstract LiveData> getRecipes();
+
+
+ @Insert
+ public void insertCurrentUser(UserRetrofitGood userretrofit);
+
+ // @Query("SELECT * FROM ")
+//
+// @Transaction
+// @Query("SELECT * FROM Recipe WHERE id = :id")
+// public abstract Recipe getRecipe(int id);
+//
+// @Insert
+// public abstract void insertAllRecipes(List recipeList);
+ @Insert
+ public void insertAllOneSharedFoodProductsListRetrofit(List oneSharedFoodProductsListRetrofits);
+ @Insert
+ public abstract void insertOneSharedFoodProductsListRetrofit(OneSharedFoodProductsListRetrofit oneSharedFoodProductsListRetrofit);
+}
+
+
+
diff --git a/app/src/main/res/layout/activity_register_with_mail_pasword.xml b/app/src/main/res/layout/activity_register_with_mail_pasword.xml
index c5b7a64..03bb278 100644
--- a/app/src/main/res/layout/activity_register_with_mail_pasword.xml
+++ b/app/src/main/res/layout/activity_register_with_mail_pasword.xml
@@ -1,6 +1,7 @@
+
+
\ No newline at end of file
+
+
\ No newline at end of file
diff --git a/build.gradle b/build.gradle
index 5191a1c..7d1763d 100644
--- a/build.gradle
+++ b/build.gradle
@@ -7,12 +7,12 @@ buildscript {
jcenter()
}
dependencies {
- classpath 'com.android.tools.build:gradle:3.0.1'
+ classpath 'com.android.tools.build:gradle:3.1.3'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
- classpath 'com.google.gms:google-services:3.1.0'
+ classpath 'com.google.gms:google-services:4.0.1'
classpath 'com.jakewharton:butterknife-gradle-plugin:8.8.1'
}
}
diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties
index a223c5e..c091c7c 100644
--- a/gradle/wrapper/gradle-wrapper.properties
+++ b/gradle/wrapper/gradle-wrapper.properties
@@ -1,6 +1,6 @@
-#Wed Nov 15 23:13:01 EET 2017
+#Fri Jul 27 19:13:20 EEST 2018
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
-distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip
+distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip