├── .gitignore ├── .idea ├── .name ├── compiler.xml ├── copyright │ └── profiles_settings.xml ├── gradle.xml ├── misc.xml ├── modules.xml ├── runConfigurations.xml └── vcs.xml ├── Foodie Doodie API ├── include │ ├── Config.php │ ├── DB_Connect.php │ └── DB_Functions.php ├── index.php ├── login.php └── register.php ├── README.md ├── Screenshots ├── Screenshot_2016-04-18-17-20-35.png ├── Screenshot_2016-04-18-17-20-43.png └── Screenshot_2016-04-18-17-21-00.png ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── codelycan │ │ └── foodiedoodie │ │ └── ApplicationTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── codelycan │ │ │ └── foodiedoodie │ │ │ ├── LoginActivity.java │ │ │ ├── MainActivity.java │ │ │ ├── RegisterActivity.java │ │ │ └── Util │ │ │ ├── AppController.java │ │ │ ├── Config.java │ │ │ ├── HelperMethods.java │ │ │ ├── SQLiteHandler.java │ │ │ └── SessionManager.java │ └── res │ │ ├── layout │ │ ├── activity_login.xml │ │ ├── activity_main.xml │ │ └── activity_register.xml │ │ ├── mipmap-hdpi │ │ └── ic_launcher.png │ │ ├── mipmap-mdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxxhdpi │ │ └── ic_launcher.png │ │ ├── values-v21 │ │ └── styles.xml │ │ ├── values-w820dp │ │ └── dimens.xml │ │ └── values │ │ ├── colors.xml │ │ ├── dimens.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── com │ └── codelycan │ └── foodiedoodie │ └── ExampleUnitTest.java ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/workspace.xml 5 | /.idea/libraries 6 | .DS_Store 7 | /build 8 | /captures 9 | -------------------------------------------------------------------------------- /.idea/.name: -------------------------------------------------------------------------------- 1 | Foodie Doodie -------------------------------------------------------------------------------- /.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /.idea/copyright/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 18 | 19 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 19 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 46 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /.idea/runConfigurations.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 12 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /Foodie Doodie API/include/Config.php: -------------------------------------------------------------------------------- 1 | 11 | -------------------------------------------------------------------------------- /Foodie Doodie API/include/DB_Connect.php: -------------------------------------------------------------------------------- 1 | conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE); 11 | 12 | // return database handler 13 | return $this->conn; 14 | } 15 | } 16 | 17 | ?> -------------------------------------------------------------------------------- /Foodie Doodie API/include/DB_Functions.php: -------------------------------------------------------------------------------- 1 | conn = $db->connect(); 14 | } 15 | 16 | // destructor 17 | function __destruct() { 18 | 19 | } 20 | 21 | /** 22 | * Storing new user 23 | * returns user details 24 | */ 25 | public function storeUser($name, $email, $password, $image) { 26 | $uuid = uniqid('', true); 27 | $hash = $this->hashSSHA($password); 28 | $encrypted_password = $hash["encrypted"]; // encrypted password 29 | $salt = $hash["salt"]; // salt 30 | 31 | $stmt = $this->conn->prepare("INSERT INTO users(unique_id, name, email, image, encrypted_password, salt, created_at) VALUES(?, ?, ?, ?, ?, ?, NOW())"); 32 | $stmt->bind_param("ssssss", $uuid, $name, $email, $image, $encrypted_password, $salt); 33 | $result = $stmt->execute(); 34 | $stmt->close(); 35 | 36 | // check for successful store 37 | if ($result) { 38 | $stmt = $this->conn->prepare("SELECT * FROM users WHERE email = ?"); 39 | $stmt->bind_param("s", $email); 40 | $stmt->execute(); 41 | 42 | $stmt->bind_result($id, $unique_id, $name, $email, $image, $encrypted_password, $salt, $created_at, $updated_at); 43 | $stmt->fetch(); 44 | $user = array('id'=>$id,'unique_id'=>$unique_id,'name'=>$name,'email'=>$email,'image'=>$image,'encrypted_password'=>$encrypted_password,'salt' => $salt,'created_at' => $created_at,'updated_at' =>$updated_at); 45 | 46 | //$user = $stmt->get_result()->fetch_assoc(); 47 | $stmt->close(); 48 | 49 | return $user; 50 | } else { 51 | return false; 52 | } 53 | } 54 | 55 | /** 56 | * Get user by email and password 57 | */ 58 | public function getUserByEmailAndPassword($email, $password) { 59 | 60 | $stmt = $this->conn->prepare("SELECT * FROM users WHERE email = ?"); 61 | 62 | $stmt->bind_param("s", $email); 63 | // added 64 | if($stmt->execute()){ 65 | $stmt->bind_result($id, $unique_id, $name, $email, $image, $encrypted_password, $salt, $created_at, $updated_at); 66 | $stmt->fetch(); 67 | $hash = $this->checkhashSSHA($salt, $password); 68 | // check for password equality 69 | if ($encrypted_password == $hash) { 70 | // user authentication details are correct 71 | $user = array('id'=>$id,'unique_id'=>$unique_id,'name'=>$name,'email'=>$email,'image'=>$image,'encrypted_password'=>$encrypted_password,'salt' => $salt,'created_at' => $created_at,'updated_at' =>$updated_at); 72 | $stmt->close(); 73 | return $user; 74 | } 75 | $stmt->close(); 76 | return NULL; 77 | 78 | }else { 79 | return NULL; 80 | } 81 | 82 | 83 | 84 | // //Previous 85 | // if ($stmt->execute()) { 86 | // $user = $stmt->get_result()->fetch_assoc(); 87 | // $stmt->close(); 88 | 89 | // // verifying user password 90 | // $salt = $user['salt']; 91 | // $encrypted_password = $user['encrypted_password']; 92 | // $hash = $this->checkhashSSHA($salt, $password); 93 | // // check for password equality 94 | // if ($encrypted_password == $hash) { 95 | // // user authentication details are correct 96 | // return $user; 97 | // } 98 | // } else { 99 | // return NULL; 100 | // } 101 | } 102 | 103 | /** 104 | * Get user by email and password 105 | */ 106 | public function getFbUserByEmail($email) { 107 | 108 | $stmt = $this->conn->prepare("SELECT * FROM users_fb WHERE email = ?"); 109 | 110 | $stmt->bind_param("s", $email); 111 | 112 | if ($stmt->execute()) { 113 | $stmt->bind_result($id, $unique_id, $name, $email, $image, $created_at, $updated_at); 114 | $stmt->fetch(); 115 | $user = array('id'=>$id,'unique_id'=>$unique_id,'name'=>$name,'email'=>$email,'image'=>$image,'created_at' => $created_at,'updated_at' =>$updated_at); 116 | 117 | return $user; 118 | 119 | } else { 120 | return NULL; 121 | } 122 | } 123 | 124 | /** 125 | * Check user is existed or not 126 | */ 127 | public function isUserExisted($email) { 128 | $stmt = $this->conn->prepare("SELECT email from users WHERE email = ?"); 129 | 130 | $stmt->bind_param("s", $email); 131 | 132 | $stmt->execute(); 133 | 134 | $stmt->store_result(); 135 | 136 | if ($stmt->num_rows > 0) { 137 | // user existed 138 | $stmt->close(); 139 | return true; 140 | } else { 141 | // user not existed 142 | $stmt->close(); 143 | return false; 144 | } 145 | } 146 | 147 | /** 148 | * Check fb user is existed or not 149 | */ 150 | public function isFbUserExisted($email) { 151 | $stmt = $this->conn->prepare("SELECT email from users_fb WHERE email = ?"); 152 | 153 | $stmt->bind_param("s", $email); 154 | 155 | $stmt->execute(); 156 | 157 | $stmt->store_result(); 158 | 159 | if ($stmt->num_rows > 0) { 160 | // user existed 161 | $stmt->close(); 162 | return true; 163 | } else { 164 | // user not existed 165 | $stmt->close(); 166 | return false; 167 | } 168 | } 169 | 170 | /** 171 | * Encrypting password 172 | * @param password 173 | * returns salt and encrypted password 174 | */ 175 | public function hashSSHA($password) { 176 | 177 | $salt = sha1(rand()); 178 | $salt = substr($salt, 0, 10); 179 | $encrypted = base64_encode(sha1($password . $salt, true) . $salt); 180 | $hash = array("salt" => $salt, "encrypted" => $encrypted); 181 | return $hash; 182 | } 183 | 184 | /** 185 | * Decrypting password 186 | * @param salt, password 187 | * returns hash string 188 | */ 189 | public function checkhashSSHA($salt, $password) { 190 | 191 | $hash = base64_encode(sha1($password . $salt, true) . $salt); 192 | 193 | return $hash; 194 | } 195 | 196 | /** 197 | * Storing new fb user 198 | * returns user details 199 | */ 200 | public function storeFbUser($uid, $name, $email, $image) { 201 | 202 | $stmt = $this->conn->prepare("INSERT INTO users_fb(unique_id, name, email, image, created_at) VALUES(?, ?, ?, ?, NOW())"); 203 | $stmt->bind_param("ssss", $uid, $name, $email, $image); 204 | $result = $stmt->execute(); 205 | $stmt->close(); 206 | 207 | // check for successful store 208 | if ($result) { 209 | $stmt = $this->conn->prepare("SELECT * FROM users_fb WHERE email = ?"); 210 | $stmt->bind_param("s", $email); 211 | $stmt->execute(); 212 | $stmt->bind_result($id, $unique_id, $name, $email, $image, $created_at, $updated_at); 213 | $stmt->fetch(); 214 | $user = array('id'=>$id,'unique_id'=>$unique_id,'name'=>$name,'email'=>$email,'image'=>$image,'created_at' => $created_at,'updated_at' =>$updated_at); 215 | $stmt->close(); 216 | 217 | return $user; 218 | } else { 219 | return false; 220 | } 221 | } 222 | 223 | } 224 | 225 | ?> -------------------------------------------------------------------------------- /Foodie Doodie API/index.php: -------------------------------------------------------------------------------- 1 |

Life is a mystery!!

-------------------------------------------------------------------------------- /Foodie Doodie API/login.php: -------------------------------------------------------------------------------- 1 | FALSE); 7 | 8 | if (isset($_POST['email']) && isset($_POST['password'])) { 9 | 10 | // receiving the post params 11 | $email = $_POST['email']; 12 | $password = $_POST['password']; 13 | 14 | // get the user by email and password 15 | $user = $db->getUserByEmailAndPassword($email, $password); 16 | 17 | if ($user != NULL) { 18 | // user is found 19 | $response["error"] = FALSE; 20 | $response["uid"] = $user["unique_id"]; 21 | $response["user"]["name"] = $user["name"]; 22 | $response["user"]["email"] = $user["email"]; 23 | $response["user"]["image"] = $user["image"]; 24 | $response["user"]["created_at"] = $user["created_at"]; 25 | $response["user"]["updated_at"] = $user["updated_at"]; 26 | echo json_encode($response); 27 | } else { 28 | // user is not found with the credentials 29 | $response["error"] = TRUE; 30 | $response["error_msg"] = "Login credentials are wrong. Please try again!"; 31 | echo json_encode($response); 32 | } 33 | } 34 | elseif (isset($_POST['email'])) { 35 | // receiving the post params 36 | $email = $_POST['email']; 37 | 38 | // get the user by email and password 39 | $user = $db->getFbUserByEmail($email); 40 | 41 | if ($user != NULL) { 42 | // user is found 43 | $response["error"] = FALSE; 44 | $response["uid"] = $user["unique_id"]; 45 | $response["user"]["name"] = $user["name"]; 46 | $response["user"]["email"] = $user["email"]; 47 | $response["user"]["image"] = $user["image"]; 48 | $response["user"]["created_at"] = $user["created_at"]; 49 | $response["user"]["updated_at"] = $user["updated_at"]; 50 | echo json_encode($response); 51 | } else { 52 | // user is not found with the credentials 53 | $response["error"] = TRUE; 54 | $response["error_msg"] = "Login credentials are wrong from fb. Please try again!"; 55 | echo json_encode($response); 56 | } 57 | } 58 | else { 59 | // required post params is missing 60 | $response["error"] = TRUE; 61 | $response["error_msg"] = "Required parameters email or password is missing!"; 62 | echo json_encode($response); 63 | } 64 | ?> -------------------------------------------------------------------------------- /Foodie Doodie API/register.php: -------------------------------------------------------------------------------- 1 | FALSE); 8 | 9 | if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['password']) && isset($_POST['image'])) { 10 | 11 | // receiving the post params 12 | $name = $_POST['name']; 13 | $email = $_POST['email']; 14 | $password = $_POST['password']; 15 | $image = $_POST['image']; 16 | 17 | // check if user is already existed with the same email 18 | if ($db->isUserExisted($email)) { 19 | // user already existed 20 | $response["error"] = TRUE; 21 | $response["error_msg"] = "User already existed with " . $email; 22 | echo json_encode($response); 23 | } else { 24 | // create a new user 25 | $user = $db->storeUser($name, $email, $password, $image); 26 | if ($user) { 27 | // user stored successfully 28 | $response["error"] = FALSE; 29 | $response["uid"] = $user["unique_id"]; 30 | $response["user"]["name"] = $user["name"]; 31 | $response["user"]["email"] = $user["email"]; 32 | $response["user"]["created_at"] = $user["created_at"]; 33 | $response["user"]["updated_at"] = $user["updated_at"]; 34 | echo json_encode($response); 35 | } else { 36 | // user failed to store 37 | $response["error"] = TRUE; 38 | $response["error_msg"] = "Unknown error occurred in registration!"; 39 | echo json_encode($response); 40 | } 41 | } 42 | } else { 43 | $response["error"] = TRUE; 44 | $response["error_msg"] = "Required parameters (name, email or password) is missing!"; 45 | echo json_encode($response); 46 | } 47 | ?> -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | *** 2 | THIS PROJECT IS DISCONTINUED. 3 | Please goto [Android-Registration-System-v2](https://github.com/taharushain/android-registration-system-v2) for the updated continual of this. 4 | *** 5 | 6 | # Android-Registration-System 7 | 8 | This project is developed to help bootstrap user login/registration system along with the support of Facebook API. 9 | It could sometimes be a real pain in ass just to develop this system again n again for different projects specially when other APIs are to be incorporated. 10 | 11 | ## Getting Started 12 | First things first, we need to implement a server side api for our app. 13 | 14 | ### Server Side 15 | Upload the contents of 'Foodie Doodie API' folder into your web host or local host. 16 | 17 | *Make sure the scripts have a priviledge of '0775'* 18 | 19 | #### Create a database and Tables in Mysql 20 | ```CREATE DATABASE my_db;``` 21 | ``` 22 | CREATE TABLE IF NOT EXISTS `users` ( 23 | `id` int(11) NOT NULL AUTO_INCREMENT, 24 | `unique_id` varchar(23) NOT NULL, 25 | `name` varchar(50) NOT NULL, 26 | `email` varchar(100) NOT NULL, 27 | `image` mediumtext NOT NULL, 28 | `encrypted_password` varchar(80) NOT NULL, 29 | `salt` varchar(10) NOT NULL, 30 | `created_at` datetime DEFAULT NULL, 31 | `updated_at` datetime DEFAULT NULL, 32 | PRIMARY KEY (`id`), 33 | UNIQUE KEY `unique_id` (`unique_id`), 34 | UNIQUE KEY `email` (`email`) 35 | ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ; 36 | ``` 37 | ``` 38 | CREATE TABLE IF NOT EXISTS `users_fb` ( 39 | `id` int(11) NOT NULL AUTO_INCREMENT, 40 | `unique_id` varchar(255) NOT NULL, 41 | `name` varchar(50) NOT NULL, 42 | `email` varchar(100) NOT NULL, 43 | `image` mediumtext NOT NULL, 44 | `created_at` datetime DEFAULT NULL, 45 | `updated_at` datetime DEFAULT NULL, 46 | PRIMARY KEY (`id`), 47 | UNIQUE KEY `unique_id` (`unique_id`), 48 | UNIQUE KEY `email` (`email`) 49 | ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ; 50 | ``` 51 | 52 | #### Modify include/Config.php 53 | ``` 54 | 60 | ``` 61 | Change localhost with your host, user with Database user , password with Databse user's password and db with Database name 62 | 63 | ### Client Side (Android) 64 | Import the project in Android Studio and run gradle to sync libraries. 65 | #### Modify /app/src/main/res/values/strings.xml 66 | ``` 67 | YOUR FACEBOOK APP ID 68 | ``` 69 | *Create a Facebook app and paste your APP ID here* 70 | All the information regarding this process has been provided by [Facebook] (https://developers.facebook.com/docs/facebook-login/android) 71 | 72 | ### Modify /app/src/main/java/com/codelycan/foodiedoodie/Util/Config.java 73 | ``` 74 | package com.codelycan.foodiedoodie.Util; 75 | /** 76 | * Created by trushain on 4/16/16. 77 | */ 78 | public class Config { 79 | 80 | public static String URL_LOGIN = "http://localhost/folder/register.php"; 81 | 82 | // Server user register url 83 | public static String URL_REGISTER = "http://localhost/folder/register.php"; 84 | } 85 | ``` 86 | *Replace the URLS respectively to the uploaded files* 87 | 88 | ##That's it! 89 | No need to say Thanks, just don't forget to have fun! 90 | >"There is no time like present, I guess" 91 | 92 | ## Screenshots 93 | 94 | ![alt text](https://raw.githubusercontent.com/trushain/Android-Registration-System/master/Screenshots/Screenshot_2016-04-18-17-20-35.png "Login Activity") 95 | ![alt text](https://raw.githubusercontent.com/trushain/Android-Registration-System/master/Screenshots/Screenshot_2016-04-18-17-20-43.png "Register Activity") 96 | ![alt text](https://raw.githubusercontent.com/trushain/Android-Registration-System/master/Screenshots/Screenshot_2016-04-18-17-21-00.png "Main Activity") 97 | 98 | -------------------------------------------------------------------------------- /Screenshots/Screenshot_2016-04-18-17-20-35.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taharushain/Android-Registration-System/db19fabcfd823c6c169547ad91df04acb973d548/Screenshots/Screenshot_2016-04-18-17-20-35.png -------------------------------------------------------------------------------- /Screenshots/Screenshot_2016-04-18-17-20-43.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taharushain/Android-Registration-System/db19fabcfd823c6c169547ad91df04acb973d548/Screenshots/Screenshot_2016-04-18-17-20-43.png -------------------------------------------------------------------------------- /Screenshots/Screenshot_2016-04-18-17-21-00.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/taharushain/Android-Registration-System/db19fabcfd823c6c169547ad91df04acb973d548/Screenshots/Screenshot_2016-04-18-17-21-00.png -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 23 5 | buildToolsVersion "23.0.3" 6 | defaultConfig { 7 | applicationId 'com.codelycan.foodiedoodie' 8 | minSdkVersion 15 9 | targetSdkVersion 23 10 | versionCode 1 11 | versionName "1.0" 12 | } 13 | buildTypes { 14 | release { 15 | minifyEnabled false 16 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 17 | } 18 | } 19 | productFlavors { 20 | } 21 | } 22 | repositories { 23 | mavenCentral() 24 | } 25 | dependencies { 26 | compile fileTree(include: ['*.jar'], dir: 'libs') 27 | testCompile 'junit:junit:4.12' 28 | compile 'com.android.support:appcompat-v7:23.2.1' 29 | compile 'com.android.support:design:23.2.1' 30 | compile 'com.facebook.android:facebook-android-sdk:[4,5)' 31 | compile 'com.mcxiaoke.volley:library-aar:1.0.0' 32 | } 33 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /home/trushain/Android/Sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/codelycan/foodiedoodie/ApplicationTest.java: -------------------------------------------------------------------------------- 1 | package com.codelycan.foodiedoodie; 2 | 3 | import android.app.Application; 4 | import android.test.ApplicationTestCase; 5 | 6 | /** 7 | * Testing Fundamentals 8 | */ 9 | public class ApplicationTest extends ApplicationTestCase { 10 | public ApplicationTest() { 11 | super(Application.class); 12 | } 13 | } -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 14 | 17 | 18 | 23 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 39 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /app/src/main/java/com/codelycan/foodiedoodie/LoginActivity.java: -------------------------------------------------------------------------------- 1 | package com.codelycan.foodiedoodie; 2 | 3 | import android.app.ProgressDialog; 4 | import android.content.Intent; 5 | import android.content.pm.PackageInfo; 6 | import android.content.pm.PackageManager; 7 | import android.graphics.Bitmap; 8 | import android.graphics.BitmapFactory; 9 | import android.os.AsyncTask; 10 | import android.support.design.widget.Snackbar; 11 | import android.support.v7.app.AppCompatActivity; 12 | import android.os.Bundle; 13 | import android.util.Base64; 14 | import android.util.Log; 15 | import android.view.View; 16 | import android.widget.Button; 17 | import android.widget.EditText; 18 | import android.widget.TextView; 19 | 20 | import com.android.volley.AuthFailureError; 21 | import com.android.volley.NetworkError; 22 | import com.android.volley.NetworkResponse; 23 | import com.android.volley.NoConnectionError; 24 | import com.android.volley.ParseError; 25 | import com.android.volley.Request; 26 | import com.android.volley.Response; 27 | import com.android.volley.ServerError; 28 | import com.android.volley.TimeoutError; 29 | import com.android.volley.VolleyError; 30 | import com.android.volley.toolbox.StringRequest; 31 | import com.codelycan.foodiedoodie.Util.AppController; 32 | import com.codelycan.foodiedoodie.Util.Config; 33 | import com.codelycan.foodiedoodie.Util.HelperMethods; 34 | import com.codelycan.foodiedoodie.Util.SQLiteHandler; 35 | import com.codelycan.foodiedoodie.Util.SessionManager; 36 | import com.facebook.CallbackManager; 37 | import com.facebook.FacebookCallback; 38 | import com.facebook.FacebookException; 39 | import com.facebook.FacebookSdk; 40 | import com.facebook.GraphRequest; 41 | import com.facebook.GraphResponse; 42 | import com.facebook.login.LoginManager; 43 | import com.facebook.login.LoginResult; 44 | import com.facebook.login.widget.LoginButton; 45 | import com.facebook.Profile; 46 | 47 | import org.json.JSONException; 48 | import org.json.JSONObject; 49 | 50 | import java.io.IOException; 51 | import java.io.InputStream; 52 | import java.net.HttpURLConnection; 53 | import java.net.MalformedURLException; 54 | import java.net.URL; 55 | import java.security.MessageDigest; 56 | import java.security.NoSuchAlgorithmException; 57 | import java.util.Arrays; 58 | import java.util.HashMap; 59 | import java.util.Map; 60 | import java.util.concurrent.ExecutionException; 61 | 62 | 63 | public class LoginActivity extends AppCompatActivity { 64 | 65 | private static final String TAG = LoginActivity.class.getSimpleName(); 66 | private Button btnLogin; 67 | private Button fb_login ; 68 | private TextView btnLinkToRegister; 69 | private EditText inputEmail; 70 | private EditText inputPassword; 71 | private ProgressDialog pDialog; 72 | private SessionManager session; 73 | private SQLiteHandler db; 74 | 75 | private CallbackManager callbackManager; 76 | //private LoginButton fb_loginButton; 77 | 78 | public LoginActivity() { 79 | } 80 | 81 | @Override 82 | protected void onCreate(Bundle savedInstanceState) { 83 | super.onCreate(savedInstanceState); 84 | FacebookSdk.sdkInitialize(getApplicationContext()); 85 | setContentView(R.layout.activity_login); 86 | 87 | fb_login = (Button)findViewById(R.id.fb_login_button); 88 | inputEmail = (EditText) findViewById(R.id.email); 89 | inputPassword = (EditText) findViewById(R.id.password); 90 | btnLogin = (Button) findViewById(R.id.btnLogin); 91 | btnLinkToRegister = (TextView) findViewById(R.id.linkToRegisterScreen); 92 | 93 | // Progress dialog 94 | pDialog = new ProgressDialog(this); 95 | pDialog.setCancelable(false); 96 | 97 | // SQLite database handler 98 | db = new SQLiteHandler(getApplicationContext()); 99 | 100 | // Session manager 101 | session = new SessionManager(getApplicationContext()); 102 | 103 | // Check if user is already logged in or not 104 | if (session.isLoggedIn()) { 105 | // User is already logged in. Take him to main activity 106 | Intent intent = new Intent(LoginActivity.this, MainActivity.class); 107 | startActivity(intent); 108 | finish(); 109 | } 110 | 111 | btnLogin.setOnClickListener(new View.OnClickListener() { 112 | @Override 113 | public void onClick(View v) { 114 | String email = inputEmail.getText().toString().trim(); 115 | String password = inputPassword.getText().toString().trim(); 116 | 117 | // Check for empty data in the form 118 | if (!email.isEmpty() && !password.isEmpty()) { 119 | // login user 120 | checkLogin(email, password); 121 | } else { 122 | // Prompt user to enter credentials 123 | // Toast.makeText(getApplicationContext(), 124 | // "Please enter the credentials!", Toast.LENGTH_LONG) 125 | // .show(); 126 | displaySnackBar(v,"Please enter the credentials!"); 127 | } 128 | } 129 | 130 | }); 131 | 132 | // Link to Register Screen 133 | btnLinkToRegister.setOnClickListener(new View.OnClickListener() { 134 | 135 | public void onClick(View view) { 136 | Intent i = new Intent(getApplicationContext(), 137 | RegisterActivity.class); 138 | startActivity(i); 139 | finish(); 140 | } 141 | }); 142 | 143 | // try { 144 | // PackageInfo info = getPackageManager().getPackageInfo( 145 | // "com.codelycan.registrationsystem", 146 | // PackageManager.GET_SIGNATURES); 147 | // for (android.content.pm.Signature signature : info.signatures) { 148 | // MessageDigest md = MessageDigest.getInstance("SHA"); 149 | // md.update(signature.toByteArray()); 150 | // Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT)); 151 | // } 152 | // } catch (PackageManager.NameNotFoundException e) { 153 | // 154 | // } catch (NoSuchAlgorithmException e) { 155 | // 156 | // } 157 | 158 | callbackManager = CallbackManager.Factory.create(); 159 | LoginManager.getInstance().registerCallback(callbackManager, 160 | new FacebookCallback() { 161 | @Override 162 | public void onSuccess(LoginResult loginResult) { 163 | pDialog.setMessage("Preparing Flight..."); 164 | showDialog(); 165 | 166 | String accessToken = loginResult.getAccessToken().getToken(); 167 | 168 | GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() { 169 | 170 | @Override 171 | public void onCompleted(JSONObject object, GraphResponse response) { 172 | Log.i("LoginActivity", response.toString()); 173 | // Get facebook data from login 174 | Bundle bFacebookData = getFacebookData(object); 175 | 176 | try { 177 | String id = object.getString("id"); 178 | String pic_url = bFacebookData.getString("profile_pic"); //Profile Pic Url 179 | String name = bFacebookData.getString("first_name")+" " 180 | +bFacebookData.getString("last_name"); 181 | String email = bFacebookData.getString("email"); 182 | 183 | displaySnackBar(fb_login, "Teleporting..."); 184 | 185 | Bitmap img = new DownloadProfileImage().execute(pic_url).get(); 186 | String image = HelperMethods.getImageAsString(img); 187 | registerFbUser(id, name, email, image); 188 | 189 | 190 | 191 | } catch (JSONException e) { 192 | e.printStackTrace(); 193 | } catch (InterruptedException e) { 194 | e.printStackTrace(); 195 | } catch (ExecutionException e) { 196 | e.printStackTrace(); 197 | } 198 | 199 | 200 | } 201 | 202 | }); 203 | Bundle parameters = new Bundle(); 204 | parameters.putString("fields", "id, first_name, last_name, name, email"); 205 | request.setParameters(parameters); 206 | request.executeAsync(); 207 | 208 | 209 | } 210 | 211 | @Override 212 | public void onCancel() { 213 | // Toast.makeText(MainActivity.this, "Login Cancel", Toast.LENGTH_LONG).show(); 214 | } 215 | 216 | @Override 217 | public void onError(FacebookException exception) { 218 | // Toast.makeText(MainActivity.this, exception.getMessage(), Toast.LENGTH_LONG).show(); 219 | } 220 | }); 221 | 222 | 223 | fb_login.setOnClickListener(new View.OnClickListener() { 224 | @Override 225 | public void onClick(View v) { 226 | setLoginPermissions(); 227 | } 228 | }); 229 | 230 | } 231 | 232 | private void setLoginPermissions() { 233 | LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile", "email")); 234 | } 235 | 236 | private Bundle getFacebookData(JSONObject object) { 237 | 238 | 239 | Bundle bundle = new Bundle(); 240 | 241 | try { 242 | 243 | String id = object.getString("id"); 244 | 245 | URL profile_pic = new URL("https://graph.facebook.com/" + id + "/picture?width=250&height=250"); 246 | Log.i("profile_pic", profile_pic + ""); 247 | bundle.putString("profile_pic", profile_pic+""); 248 | 249 | bundle.putString("idFacebook", id); 250 | if (object.has("first_name")) 251 | bundle.putString("first_name", object.getString("first_name")); 252 | if (object.has("last_name")) 253 | bundle.putString("last_name", object.getString("last_name")); 254 | if (object.has("email")) 255 | bundle.putString("email", object.getString("email")); 256 | 257 | 258 | } catch (JSONException e) { 259 | e.printStackTrace(); 260 | } catch (MalformedURLException e) { 261 | e.printStackTrace(); 262 | } 263 | 264 | 265 | return bundle; 266 | 267 | } 268 | 269 | @Override 270 | protected void onActivityResult(int requestCode, int resultCode, Intent data) { 271 | callbackManager.onActivityResult(requestCode, resultCode, data); 272 | } 273 | 274 | /** 275 | * function to verify login details in mysql db 276 | * */ 277 | private void checkLogin(final String email, final String password) { 278 | // Tag used to cancel the request 279 | String tag_string_req = "req_login"; 280 | 281 | pDialog.setMessage("Preparing Flight ..."); 282 | showDialog(); 283 | 284 | StringRequest strReq = new StringRequest(Request.Method.POST, 285 | Config.URL_LOGIN, new Response.Listener() { 286 | 287 | @Override 288 | public void onResponse(String response) { 289 | Log.d(TAG, "Login Response: " + response.toString()); 290 | hideDialog(); 291 | 292 | try { 293 | JSONObject jObj = new JSONObject(response); 294 | boolean error = jObj.getBoolean("error"); 295 | 296 | // Check for error node in json 297 | if (!error) { 298 | // user successfully logged in 299 | // Create login session 300 | session.setLogin(true); 301 | 302 | // Now store the user in SQLite 303 | String uid = jObj.getString("uid"); 304 | 305 | JSONObject user = jObj.getJSONObject("user"); 306 | String name = user.getString("name"); 307 | String email = user.getString("email"); 308 | String image = user.getString("image"); 309 | String created_at = user 310 | .getString("created_at"); 311 | 312 | // Inserting row in users table 313 | db.addUser(name, email,image, uid,0, created_at); 314 | 315 | // Launch main activity 316 | Intent intent = new Intent(LoginActivity.this, 317 | MainActivity.class); 318 | startActivity(intent); 319 | finish(); 320 | } else { 321 | // Error in login. Get the error message 322 | String errorMsg = jObj.getString("error_msg"); 323 | // Toast.makeText(getApplicationContext(), 324 | // errorMsg, Toast.LENGTH_LONG).show(); 325 | displaySnackBar(getCurrentFocus(),errorMsg); 326 | 327 | 328 | } 329 | } catch (JSONException e) { 330 | // JSON error 331 | e.printStackTrace(); 332 | // Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show(); 333 | displaySnackBar(getCurrentFocus(), "Json error: " + e.getMessage()); 334 | } 335 | 336 | } 337 | }, new Response.ErrorListener() { 338 | 339 | @Override 340 | public void onErrorResponse(VolleyError error) { 341 | Log.e(TAG, "Login Error: " + error.getMessage()); 342 | 343 | NetworkResponse networkResponse = error.networkResponse; 344 | if (networkResponse != null) { 345 | Log.e("Volley", "Error. HTTP Status Code:"+networkResponse.statusCode); 346 | } 347 | 348 | if (error instanceof TimeoutError) { 349 | Log.e("Volley", "TimeoutError"); 350 | }else if(error instanceof NoConnectionError){ 351 | Log.e("Volley", "NoConnectionError"); 352 | } else if (error instanceof AuthFailureError) { 353 | Log.e("Volley", "AuthFailureError"); 354 | } else if (error instanceof ServerError) { 355 | Log.e("Volley", "ServerError"); 356 | } else if (error instanceof NetworkError) { 357 | Log.e("Volley", "NetworkError"); 358 | } else if (error instanceof ParseError) { 359 | Log.e("Volley", "ParseError"); 360 | } 361 | 362 | hideDialog(); 363 | displaySnackBar(getCurrentFocus(),error.getLocalizedMessage()); 364 | } 365 | }) { 366 | 367 | @Override 368 | protected Map getParams() { 369 | // Posting parameters to login url 370 | Map params = new HashMap(); 371 | params.put("email", email); 372 | params.put("password", password); 373 | 374 | return params; 375 | } 376 | 377 | }; 378 | 379 | // Adding request to request queue 380 | AppController.getInstance().addToRequestQueue(strReq, tag_string_req); 381 | } 382 | 383 | /** 384 | * function to verify login details in mysql db 385 | * */ 386 | private void doFbLogin(final String email) { 387 | // Tag used to cancel the request 388 | String tag_string_req = "req_login"; 389 | 390 | pDialog.setMessage("Logging the Heat"); 391 | // showDialog(); 392 | 393 | StringRequest strReq = new StringRequest(Request.Method.POST, 394 | Config.URL_LOGIN, new Response.Listener() { 395 | 396 | @Override 397 | public void onResponse(String response) { 398 | // Log.d(TAG, "Login Response: " + response.toString()); 399 | hideDialog(); 400 | 401 | try { 402 | JSONObject jObj = new JSONObject(response); 403 | boolean error = jObj.getBoolean("error"); 404 | 405 | // Check for error node in json 406 | if (!error) { 407 | // user successfully logged in 408 | // Create login session 409 | session.setLogin(true); 410 | 411 | // Now store the user in SQLite 412 | String uid = jObj.getString("uid"); 413 | 414 | JSONObject user = jObj.getJSONObject("user"); 415 | String name = user.getString("name"); 416 | String email = user.getString("email"); 417 | String image = user.getString("image"); 418 | String created_at = user 419 | .getString("created_at"); 420 | 421 | // Inserting row in users table 422 | db.addUser(name, email,image, uid,1, created_at); 423 | 424 | // Launch main activity 425 | Intent intent = new Intent(LoginActivity.this, 426 | MainActivity.class); 427 | startActivity(intent); 428 | finish(); 429 | } else { 430 | // Error in login. Get the error message 431 | String errorMsg = jObj.getString("error_msg"); 432 | // Toast.makeText(getApplicationContext(), 433 | // errorMsg, Toast.LENGTH_LONG).show(); 434 | displaySnackBar(getCurrentFocus(),errorMsg); 435 | 436 | 437 | } 438 | } catch (JSONException e) { 439 | // JSON error 440 | hideDialog(); 441 | e.printStackTrace(); 442 | // Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show(); 443 | displaySnackBar(getCurrentFocus(), "Json error: " + e.getMessage()); 444 | } 445 | 446 | } 447 | }, new Response.ErrorListener() { 448 | 449 | @Override 450 | public void onErrorResponse(VolleyError error) { 451 | Log.e(TAG, "Login Error: " + error.getMessage()); 452 | NetworkResponse networkResponse = error.networkResponse; 453 | if (networkResponse != null) { 454 | Log.e("Volley", "Error. HTTP Status Code:"+networkResponse.statusCode); 455 | } 456 | 457 | if (error instanceof TimeoutError) { 458 | Log.e("Volley", "TimeoutError"); 459 | }else if(error instanceof NoConnectionError){ 460 | Log.e("Volley", "NoConnectionError"); 461 | } else if (error instanceof AuthFailureError) { 462 | Log.e("Volley", "AuthFailureError"); 463 | } else if (error instanceof ServerError) { 464 | Log.e("Volley", "ServerError"); 465 | } else if (error instanceof NetworkError) { 466 | Log.e("Volley", "NetworkError"); 467 | } else if (error instanceof ParseError) { 468 | Log.e("Volley", "ParseError"); 469 | } 470 | 471 | displaySnackBar(getCurrentFocus(),error.getLocalizedMessage()); 472 | hideDialog(); 473 | } 474 | }) { 475 | 476 | @Override 477 | protected Map getParams() { 478 | // Posting parameters to login url 479 | Map params = new HashMap(); 480 | params.put("email", email); 481 | 482 | return params; 483 | } 484 | 485 | }; 486 | 487 | // Adding request to request queue 488 | AppController.getInstance().addToRequestQueue(strReq, tag_string_req); 489 | } 490 | 491 | /** 492 | * Function to store user in MySQL database will post params(tag, name, 493 | * email, password) to register url 494 | * */ 495 | private void registerFbUser(final String uid, final String name, final String email, final String image) { 496 | // Tag used to cancel the request 497 | String tag_string_req = "req_register"; 498 | 499 | pDialog.setMessage("Flight in air ..."); 500 | //showDialog(); 501 | 502 | StringRequest strReq = new StringRequest(Request.Method.POST, 503 | Config.URL_REGISTER, new Response.Listener() { 504 | 505 | @Override 506 | public void onResponse(String response) { 507 | Log.d(TAG, "Register Response: " + response.toString()); 508 | // hideDialog(); 509 | 510 | try { 511 | JSONObject jObj = new JSONObject(response); 512 | boolean error = jObj.getBoolean("error"); 513 | if (!error) { 514 | doFbLogin(email); 515 | 516 | 517 | } else { 518 | int code = jObj.getInt("code"); 519 | if(code==101){ 520 | doFbLogin(email); 521 | }else{ 522 | // Error occurred in registration. Get the error 523 | // message 524 | String errorMsg = jObj.getString("error_msg"); 525 | // Toast.makeText(getApplicationContext(), 526 | // errorMsg, Toast.LENGTH_LONG).show(); 527 | displaySnackBar(getCurrentFocus(), errorMsg); 528 | hideDialog(); 529 | } 530 | 531 | } 532 | } catch (JSONException e) { 533 | e.printStackTrace(); 534 | } 535 | 536 | } 537 | }, new Response.ErrorListener() { 538 | 539 | @Override 540 | public void onErrorResponse(VolleyError error) { 541 | Log.e(TAG, "Registration Error: " + error.getMessage()); 542 | // Toast.makeText(getApplicationContext(), 543 | // error.getMessage(), Toast.LENGTH_LONG).show(); 544 | displaySnackBar(getCurrentFocus(), error.getLocalizedMessage()); 545 | hideDialog(); 546 | } 547 | }) { 548 | 549 | @Override 550 | protected Map getParams() { 551 | // Posting params to register url 552 | Map params = new HashMap(); 553 | params.put("uid",uid); 554 | params.put("name", name); 555 | params.put("email", email); 556 | params.put("image", image); 557 | 558 | return params; 559 | } 560 | 561 | }; 562 | 563 | // Adding request to request queue 564 | AppController.getInstance().addToRequestQueue(strReq, tag_string_req); 565 | } 566 | 567 | private void showDialog() { 568 | if (!pDialog.isShowing()) 569 | pDialog.show(); 570 | } 571 | 572 | private void hideDialog() { 573 | if (pDialog.isShowing()) 574 | pDialog.dismiss(); 575 | } 576 | 577 | private void displaySnackBar(View view, String str){ 578 | Log.e("LoginActivity", "Displaying snackbar"); 579 | 580 | Snackbar snackbar = Snackbar 581 | .make(view, str, Snackbar.LENGTH_LONG); 582 | 583 | snackbar.show(); 584 | } 585 | private class DownloadProfileImage extends AsyncTask { 586 | protected Bitmap doInBackground(String... urls) { 587 | try { 588 | 589 | URL img_value = new URL(urls[0].trim()); 590 | Bitmap myBitmap = BitmapFactory.decodeStream(img_value.openConnection().getInputStream()); 591 | return myBitmap; 592 | } catch (IOException e) { 593 | e.printStackTrace(); 594 | } 595 | return null; 596 | } 597 | } 598 | } -------------------------------------------------------------------------------- /app/src/main/java/com/codelycan/foodiedoodie/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.codelycan.foodiedoodie; 2 | 3 | import android.content.Intent; 4 | import android.graphics.Bitmap; 5 | import android.support.v7.app.AppCompatActivity; 6 | import android.os.Bundle; 7 | import android.view.View; 8 | import android.widget.Button; 9 | import android.widget.ImageView; 10 | import android.widget.TextView; 11 | 12 | import com.codelycan.foodiedoodie.Util.HelperMethods; 13 | import com.codelycan.foodiedoodie.Util.SQLiteHandler; 14 | import com.codelycan.foodiedoodie.Util.SessionManager; 15 | import com.facebook.FacebookSdk; 16 | import com.facebook.appevents.AppEventsLogger; 17 | 18 | import java.util.HashMap; 19 | 20 | public class MainActivity extends AppCompatActivity { 21 | 22 | private TextView txtName; 23 | private TextView txtEmail; 24 | private Button btnLogout; 25 | private ImageView imgV; 26 | 27 | private SQLiteHandler db; 28 | private SessionManager session; 29 | 30 | 31 | 32 | @Override 33 | protected void onCreate(Bundle savedInstanceState) { 34 | super.onCreate(savedInstanceState); 35 | setContentView(R.layout.activity_main); 36 | 37 | // String temp = getIntent().getStringExtra("str"); 38 | // TextView tv = (TextView)findViewById(R.id.temp_text); 39 | // tv.setText(temp+""); 40 | 41 | txtName = (TextView) findViewById(R.id.name); 42 | txtEmail = (TextView) findViewById(R.id.email); 43 | btnLogout = (Button) findViewById(R.id.btnLogout); 44 | imgV = (ImageView) findViewById(R.id.display); 45 | 46 | // SqLite database handler 47 | db = new SQLiteHandler(getApplicationContext()); 48 | 49 | // session manager 50 | session = new SessionManager(getApplicationContext()); 51 | 52 | if (!session.isLoggedIn()) { 53 | logoutUser(); 54 | } 55 | 56 | // Fetching user details from sqlite 57 | HashMap user = db.getUserDetails(); 58 | 59 | String name = user.get("name"); 60 | String email = user.get("email"); 61 | String image = user.get("image"); 62 | Bitmap dp = HelperMethods.getImageAsBitmap(image); 63 | 64 | // Displaying the user details on the screen 65 | txtName.setText(name); 66 | txtEmail.setText(email); 67 | imgV.setImageBitmap(dp); 68 | 69 | 70 | // Logout button click event 71 | btnLogout.setOnClickListener(new View.OnClickListener() { 72 | 73 | @Override 74 | public void onClick(View v) { 75 | logoutUser(); 76 | } 77 | }); 78 | } 79 | 80 | /** 81 | * Logging out the user. Will set isLoggedIn flag to false in shared 82 | * preferences Clears the user data from sqlite users table 83 | * */ 84 | private void logoutUser() { 85 | session.setLogin(false); 86 | 87 | db.deleteUsers(); 88 | 89 | // Launching the login activity 90 | Intent intent = new Intent(MainActivity.this, LoginActivity.class); 91 | startActivity(intent); 92 | finish(); 93 | } 94 | 95 | 96 | } 97 | -------------------------------------------------------------------------------- /app/src/main/java/com/codelycan/foodiedoodie/RegisterActivity.java: -------------------------------------------------------------------------------- 1 | package com.codelycan.foodiedoodie; 2 | 3 | import android.app.ProgressDialog; 4 | import android.content.Intent; 5 | import android.graphics.Bitmap; 6 | import android.graphics.BitmapFactory; 7 | import android.support.design.widget.Snackbar; 8 | import android.support.v7.app.AppCompatActivity; 9 | import android.os.Bundle; 10 | import android.util.Log; 11 | import android.view.View; 12 | import android.widget.Button; 13 | import android.widget.EditText; 14 | import android.widget.Toast; 15 | 16 | import com.android.volley.Request; 17 | import com.android.volley.Response; 18 | import com.android.volley.VolleyError; 19 | import com.android.volley.toolbox.StringRequest; 20 | import com.codelycan.foodiedoodie.Util.AppController; 21 | import com.codelycan.foodiedoodie.Util.Config; 22 | import com.codelycan.foodiedoodie.Util.HelperMethods; 23 | import com.codelycan.foodiedoodie.Util.SQLiteHandler; 24 | import com.codelycan.foodiedoodie.Util.SessionManager; 25 | 26 | import org.json.JSONException; 27 | import org.json.JSONObject; 28 | 29 | import java.util.HashMap; 30 | import java.util.Map; 31 | 32 | public class RegisterActivity extends AppCompatActivity { 33 | private static final String TAG = RegisterActivity.class.getSimpleName(); 34 | private Button btnRegister; 35 | private Button btnLinkToLogin; 36 | private EditText inputFullName; 37 | private EditText inputEmail; 38 | private EditText inputPassword; 39 | private ProgressDialog pDialog; 40 | private SessionManager session; 41 | private SQLiteHandler db; 42 | 43 | @Override 44 | public void onCreate(Bundle savedInstanceState) { 45 | super.onCreate(savedInstanceState); 46 | setContentView(R.layout.activity_register); 47 | 48 | inputFullName = (EditText) findViewById(R.id.name); 49 | inputEmail = (EditText) findViewById(R.id.email); 50 | inputPassword = (EditText) findViewById(R.id.password); 51 | btnRegister = (Button) findViewById(R.id.btnRegister); 52 | btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen); 53 | 54 | // Progress dialog 55 | pDialog = new ProgressDialog(this); 56 | pDialog.setCancelable(false); 57 | 58 | // Session manager 59 | session = new SessionManager(getApplicationContext()); 60 | 61 | // SQLite database handler 62 | db = new SQLiteHandler(getApplicationContext()); 63 | 64 | // Check if user is already logged in or not 65 | if (session.isLoggedIn()) { 66 | // User is already logged in. Take him to main activity 67 | Intent intent = new Intent(RegisterActivity.this, 68 | MainActivity.class); 69 | startActivity(intent); 70 | finish(); 71 | } 72 | 73 | // Register Button Click event 74 | btnRegister.setOnClickListener(new View.OnClickListener() { 75 | public void onClick(View view) { 76 | String name = inputFullName.getText().toString().trim(); 77 | String email = inputEmail.getText().toString().trim(); 78 | String password = inputPassword.getText().toString().trim(); 79 | 80 | if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty()) { 81 | registerUser(name, email, password); 82 | } else { 83 | // Toast.makeText(getApplicationContext(), 84 | // "Please enter your details!", Toast.LENGTH_LONG) 85 | // .show(); 86 | displaySnackBar(view,"Please enter your details!"); 87 | } 88 | } 89 | }); 90 | 91 | // Link to Login Screen 92 | btnLinkToLogin.setOnClickListener(new View.OnClickListener() { 93 | 94 | public void onClick(View view) { 95 | Intent i = new Intent(getApplicationContext(), 96 | LoginActivity.class); 97 | startActivity(i); 98 | finish(); 99 | } 100 | }); 101 | 102 | } 103 | 104 | /** 105 | * Function to store user in MySQL database will post params(tag, name, 106 | * email, password) to register url 107 | * */ 108 | private void registerUser(final String name, final String email, 109 | final String password) { 110 | // Tag used to cancel the request 111 | String tag_string_req = "req_register"; 112 | 113 | pDialog.setMessage("Registering ..."); 114 | showDialog(); 115 | 116 | StringRequest strReq = new StringRequest(Request.Method.POST, 117 | Config.URL_REGISTER, new Response.Listener() { 118 | 119 | @Override 120 | public void onResponse(String response) { 121 | Log.d(TAG, "Register Response: " + response.toString()); 122 | hideDialog(); 123 | 124 | try { 125 | JSONObject jObj = new JSONObject(response); 126 | boolean error = jObj.getBoolean("error"); 127 | if (!error) { 128 | // User successfully stored in MySQL 129 | // Now store the user in sqlite 130 | String uid = jObj.getString("uid"); 131 | 132 | JSONObject user = jObj.getJSONObject("user"); 133 | String name = user.getString("name"); 134 | String email = user.getString("email"); 135 | String created_at = user 136 | .getString("created_at"); 137 | 138 | Bitmap temp = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher); 139 | String image = HelperMethods.getImageAsString(temp); 140 | 141 | 142 | // Inserting row in users table 143 | db.addUser(name, email, image, uid, 0,created_at); 144 | 145 | // Toast.makeText(getApplicationContext(), "User successfully registered. Try login now!", Toast.LENGTH_LONG).show(); 146 | displaySnackBar(getCurrentFocus(), "User successfully registered. Try login now!"); 147 | // Launch login activity 148 | Intent intent = new Intent( 149 | RegisterActivity.this, 150 | LoginActivity.class); 151 | startActivity(intent); 152 | finish(); 153 | } else { 154 | 155 | // Error occurred in registration. Get the error 156 | // message 157 | String errorMsg = jObj.getString("error_msg"); 158 | // Toast.makeText(getApplicationContext(), 159 | // errorMsg, Toast.LENGTH_LONG).show(); 160 | displaySnackBar(getCurrentFocus(), errorMsg); 161 | } 162 | } catch (JSONException e) { 163 | e.printStackTrace(); 164 | } 165 | 166 | } 167 | }, new Response.ErrorListener() { 168 | 169 | @Override 170 | public void onErrorResponse(VolleyError error) { 171 | Log.e(TAG, "Registration Error: " + error.getMessage()); 172 | // Toast.makeText(getApplicationContext(), 173 | // error.getMessage(), Toast.LENGTH_LONG).show(); 174 | hideDialog(); 175 | displaySnackBar(getCurrentFocus(), error.getLocalizedMessage()); 176 | 177 | } 178 | }) { 179 | 180 | @Override 181 | protected Map getParams() { 182 | // Posting params to register url 183 | Map params = new HashMap(); 184 | params.put("name", name); 185 | params.put("email", email); 186 | params.put("password", password); 187 | Bitmap temp = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher); 188 | String image = HelperMethods.getImageAsString(temp); 189 | params.put("image",image); 190 | 191 | return params; 192 | } 193 | 194 | }; 195 | 196 | // Adding request to request queue 197 | AppController.getInstance().addToRequestQueue(strReq, tag_string_req); 198 | } 199 | 200 | private void showDialog() { 201 | if (!pDialog.isShowing()) 202 | pDialog.show(); 203 | } 204 | 205 | private void hideDialog() { 206 | if (pDialog.isShowing()) 207 | pDialog.dismiss(); 208 | } 209 | 210 | private void displaySnackBar(View view, String str){ 211 | Log.e("LoginActivity", "Displaying snackbar"); 212 | 213 | Snackbar snackbar = Snackbar 214 | .make(view, str, Snackbar.LENGTH_LONG); 215 | 216 | snackbar.show(); 217 | } 218 | } -------------------------------------------------------------------------------- /app/src/main/java/com/codelycan/foodiedoodie/Util/AppController.java: -------------------------------------------------------------------------------- 1 | package com.codelycan.foodiedoodie.Util; 2 | 3 | import android.app.Application; 4 | import android.content.Context; 5 | import android.text.TextUtils; 6 | 7 | import com.android.volley.Request; 8 | import com.android.volley.RequestQueue; 9 | import com.android.volley.toolbox.Volley; 10 | 11 | /** 12 | * Created by trushain on 4/16/16. 13 | */ 14 | public class AppController extends Application { 15 | 16 | public static final String TAG = AppController.class.getSimpleName(); 17 | 18 | private RequestQueue mRequestQueue; 19 | private static Context mContext; 20 | 21 | 22 | private static AppController mInstance; 23 | 24 | @Override 25 | public void onCreate() { 26 | super.onCreate(); 27 | mInstance = this; 28 | mContext = getApplicationContext(); 29 | } 30 | 31 | public static synchronized AppController getInstance() { 32 | return mInstance; 33 | } 34 | 35 | public RequestQueue getRequestQueue() { 36 | if (mRequestQueue == null) { 37 | mRequestQueue = Volley.newRequestQueue(getApplicationContext()); 38 | } 39 | 40 | return mRequestQueue; 41 | } 42 | 43 | public void addToRequestQueue(Request req, String tag) { 44 | req.setTag(TextUtils.isEmpty(tag) ? TAG : tag); 45 | getRequestQueue().add(req); 46 | } 47 | 48 | public void addToRequestQueue(Request req) { 49 | req.setTag(TAG); 50 | getRequestQueue().add(req); 51 | } 52 | 53 | public void cancelPendingRequests(Object tag) { 54 | if (mRequestQueue != null) { 55 | mRequestQueue.cancelAll(tag); 56 | } 57 | } 58 | public static Context getContext(){ 59 | return mContext; 60 | } 61 | } -------------------------------------------------------------------------------- /app/src/main/java/com/codelycan/foodiedoodie/Util/Config.java: -------------------------------------------------------------------------------- 1 | package com.codelycan.foodiedoodie.Util; 2 | 3 | /** 4 | * Created by trushain on 4/16/16. 5 | */ 6 | public class Config { 7 | 8 | public static String URL_LOGIN = "http://localhost/folder/register.php"; 9 | 10 | // Server user register url 11 | public static String URL_REGISTER = "http://localhost/folder/register.php"; 12 | } 13 | -------------------------------------------------------------------------------- /app/src/main/java/com/codelycan/foodiedoodie/Util/HelperMethods.java: -------------------------------------------------------------------------------- 1 | package com.codelycan.foodiedoodie.Util; 2 | 3 | import android.graphics.Bitmap; 4 | import android.graphics.BitmapFactory; 5 | import android.util.Base64; 6 | import android.util.Log; 7 | 8 | import java.io.ByteArrayOutputStream; 9 | 10 | /** 11 | * Created by trushain on 4/17/16. 12 | */ 13 | public class HelperMethods { 14 | 15 | public static Bitmap getImageAsBitmap(String image){ 16 | byte[] imageAsBytes = Base64.decode(image, Base64.DEFAULT); 17 | Bitmap bmp = BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length); 18 | return bmp; 19 | } 20 | 21 | public static String getImageAsString(Bitmap bmp){ 22 | ByteArrayOutputStream bYtE = new ByteArrayOutputStream(); 23 | 24 | bmp.compress(Bitmap.CompressFormat.JPEG, 100, bYtE); 25 | byte[] byteArray = bYtE.toByteArray(); 26 | String image= Base64.encodeToString(byteArray, Base64.DEFAULT); 27 | bmp.recycle(); 28 | Log.d("Converted TO : ", image); 29 | return image; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /app/src/main/java/com/codelycan/foodiedoodie/Util/SQLiteHandler.java: -------------------------------------------------------------------------------- 1 | package com.codelycan.foodiedoodie.Util; 2 | 3 | import android.content.ContentValues; 4 | import android.content.Context; 5 | import android.database.Cursor; 6 | import android.database.sqlite.SQLiteDatabase; 7 | import android.database.sqlite.SQLiteOpenHelper; 8 | import android.util.Log; 9 | import com.codelycan.foodiedoodie.R; 10 | 11 | import java.util.HashMap; 12 | 13 | /** 14 | * Created by trushain on 4/16/16. 15 | */ 16 | public class SQLiteHandler extends SQLiteOpenHelper { 17 | 18 | private static final String TAG = SQLiteHandler.class.getSimpleName(); 19 | 20 | // All Static variables 21 | // Database Version 22 | private static final int DATABASE_VERSION = 1; 23 | 24 | // Database Name 25 | private static final String DATABASE_NAME = AppController.getContext().getString(R.string.app_name); 26 | 27 | // Login table name 28 | private static final String TABLE_USER = "user"; 29 | 30 | // Login Table Columns names 31 | private static final String KEY_ID = "id"; 32 | private static final String KEY_NAME = "name"; 33 | private static final String KEY_EMAIL = "email"; 34 | private static final String KEY_IMAGE= "image"; 35 | private static final String KEY_UID = "uid"; 36 | private static final String KEY_CREATED_AT = "created_at"; 37 | private static final String KEY_IS_FB = "is_fb"; 38 | 39 | public SQLiteHandler(Context context) { 40 | super(context, DATABASE_NAME, null, DATABASE_VERSION); 41 | } 42 | 43 | // Creating Tables 44 | @Override 45 | public void onCreate(SQLiteDatabase db) { 46 | String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_USER + "(" 47 | + KEY_ID + " INTEGER PRIMARY KEY," 48 | + KEY_NAME + " TEXT," 49 | + KEY_EMAIL + " TEXT UNIQUE," 50 | + KEY_IMAGE + " TEXT," 51 | + KEY_UID + " TEXT," 52 | + KEY_IS_FB + " INTEGER," 53 | + KEY_CREATED_AT + " TEXT" + ")"; 54 | db.execSQL(CREATE_LOGIN_TABLE); 55 | 56 | Log.d(TAG, "Database tables created"); 57 | } 58 | 59 | // Upgrading database 60 | @Override 61 | public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 62 | // Drop older table if existed 63 | db.execSQL("DROP TABLE IF EXISTS " + TABLE_USER); 64 | 65 | // Create tables again 66 | onCreate(db); 67 | } 68 | 69 | /** 70 | * Storing user details in database 71 | * */ 72 | public void addUser(String name, String email, String image, String uid,int is_fb, String created_at) { 73 | SQLiteDatabase db = this.getWritableDatabase(); 74 | 75 | ContentValues values = new ContentValues(); 76 | values.put(KEY_NAME, name); // Name 77 | values.put(KEY_EMAIL, email); // Email 78 | values.put(KEY_IMAGE, image); 79 | values.put(KEY_UID, uid); // Email 80 | values.put(KEY_CREATED_AT, created_at); // Created At 81 | values.put(KEY_IS_FB,is_fb); 82 | 83 | // Inserting Row 84 | long id = db.insert(TABLE_USER, null, values); 85 | db.close(); // Closing database connection 86 | 87 | Log.d(TAG, "New user inserted into sqlite: " + id); 88 | } 89 | 90 | /** 91 | * Getting user data from database 92 | * */ 93 | public HashMap getUserDetails() { 94 | HashMap user = new HashMap(); 95 | String selectQuery = "SELECT * FROM " + TABLE_USER; 96 | 97 | SQLiteDatabase db = this.getReadableDatabase(); 98 | Cursor cursor = db.rawQuery(selectQuery, null); 99 | // Move to first row 100 | cursor.moveToFirst(); 101 | if (cursor.getCount() > 0) { 102 | user.put("name", cursor.getString(1)); 103 | user.put("email", cursor.getString(2)); 104 | user.put("image", cursor.getString(3)); 105 | user.put("uid", cursor.getString(4)); 106 | user.put("is_fb", cursor.getString(5)); 107 | user.put("created_at", cursor.getString(6)); 108 | 109 | 110 | } 111 | cursor.close(); 112 | db.close(); 113 | // return user 114 | Log.d(TAG, "Fetching user from Sqlite: " + user.toString()); 115 | 116 | return user; 117 | } 118 | 119 | /** 120 | * Re crate database Delete all tables and create them again 121 | * */ 122 | public void deleteUsers() { 123 | SQLiteDatabase db = this.getWritableDatabase(); 124 | // Delete All Rows 125 | db.delete(TABLE_USER, null, null); 126 | db.close(); 127 | 128 | Log.d(TAG, "Deleted all user info from sqlite"); 129 | } 130 | 131 | } 132 | -------------------------------------------------------------------------------- /app/src/main/java/com/codelycan/foodiedoodie/Util/SessionManager.java: -------------------------------------------------------------------------------- 1 | package com.codelycan.foodiedoodie.Util; 2 | 3 | import android.content.Context; 4 | import android.content.SharedPreferences; 5 | import android.util.Log; 6 | 7 | import com.codelycan.foodiedoodie.R; 8 | 9 | /** 10 | * Created by trushain on 4/16/16. 11 | */ 12 | public class SessionManager { 13 | // LogCat tag 14 | private static String TAG = SessionManager.class.getSimpleName(); 15 | 16 | // Shared Preferences 17 | SharedPreferences pref; 18 | 19 | SharedPreferences.Editor editor; 20 | Context _context; 21 | 22 | // Shared pref mode 23 | int PRIVATE_MODE = 0; 24 | 25 | // Shared preferences file name 26 | private static final String PREF_NAME = AppController.getContext().getString(R.string.app_name); 27 | 28 | private static final String KEY_IS_LOGGEDIN = "isLoggedIn"; 29 | 30 | public SessionManager(Context context) { 31 | this._context = context; 32 | pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE); 33 | editor = pref.edit(); 34 | } 35 | 36 | public void setLogin(boolean isLoggedIn) { 37 | 38 | editor.putBoolean(KEY_IS_LOGGEDIN, isLoggedIn); 39 | 40 | // commit changes 41 | editor.commit(); 42 | 43 | Log.d(TAG, "User login session modified!"); 44 | } 45 | 46 | public boolean isLoggedIn(){ 47 | return pref.getBoolean(KEY_IS_LOGGEDIN, false); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_login.xml: -------------------------------------------------------------------------------- 1 | 2 | 12 | 13 | 18 | 32 | 46 | 47 |