Sie sind auf Seite 1von 45

Android Login and Registration with PHP, MySQL and SQLite

1 of 45

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

Advertise Here

Like

1.1k

Tweet

Advertise Here

1/14/2016 11:10 PM

Android Login and Registration with PHP, MySQL and SQLite

2 of 45

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

1/14/2016 11:10 PM

Android Login and Registration with PHP, MySQL and SQLite

3 of 45

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

1/14/2016 11:10 PM

Android Login and Registration with PHP, MySQL and SQLite

4 of 45

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

1/14/2016 11:10 PM

Android Login and Registration with PHP, MySQL and SQLite

5 of 45

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

1/14/2016 11:10 PM

Android Login and Registration with PHP, MySQL and SQLite

6 of 45

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

create database android_api /** Creating Database **/


use android_api /** Selecting Database **/

create table users(


id int(11) primary key auto_increment,
unique_id varchar(23) not null unique,
name varchar(50) not null,
email varchar(100) not null unique,
encrypted_password varchar(80) not null,
salt varchar(10) not null,
created_at datetime,
updated_at datetime null
); /** Creating Users Table **/

1/14/2016 11:10 PM

Android Login and Registration with PHP, MySQL and SQLite

7 of 45

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

CONFIG.PHP
<?php

/**
* Database config variables
*/
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASSWORD", "root");
define("DB_DATABASE", "android_api");
?>

1/14/2016 11:10 PM

Android Login and Registration with PHP, MySQL and SQLite

8 of 45

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

DB_CONNECT.PHP

<?php
class DB_Connect {
private $conn;

// Connecting to database
public function connect() {
require_once 'include/Config.php';

// Connecting to mysql database


$this->conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);

// return database handler


return $this->conn;

?>

<?php

class DB_Functions {
private $conn;

// constructor
function __construct() {
require_once 'DB_Connect.php';
// connecting to database
$db = new Db_Connect();
1/14/2016 11:10 PM

Android Login and Registration with PHP, MySQL and SQLite

9 of 45

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

// destructor
function __destruct() {
}

/**
* Storing new user
* returns user details
*/
public function storeUser($name, $email, $password) {
$uuid = uniqid('', true);
$hash = $this->hashSSHA($password);
$encrypted_password = $hash["encrypted"]; // encrypted password
$salt = $hash["salt"]; // salt

$stmt = $this->conn->prepare("INSERT INTO users(unique_id, name, email, encrypted_


$stmt->bind_param("sssss", $uuid, $name, $email, $encrypted_password, $salt
$result = $stmt->execute();
$stmt->close();
// check for successful store
if ($result) {
$stmt = $this->conn->prepare("SELECT * FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();

return $user;
} else {
return false;
}

/**
* Get user by email and password
*/
public function getUserByEmailAndPassword($email, $password) {

$stmt = $this->conn->prepare("SELECT * FROM users WHERE email = ?");


$stmt->bind_param("s", $email);

if ($stmt->execute()) {
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();
return $user;
} else {
return NULL;
}

/**
* Check user is existed or not
1/14/2016 11:10 PM

Android Login and Registration with PHP, MySQL and SQLite

10 of 45

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

$stmt->bind_param("s", $email);
$stmt->execute();

$stmt->store_result();

if ($stmt->num_rows > 0) {
// user existed
$stmt->close();
return true;
} else {
// user not existed
$stmt->close();
return false;
}

/**
* Encrypting password
* @param password
* returns salt and encrypted password
*/
public function hashSSHA($password) {

$salt = sha1(rand());
$salt = substr($salt, 0, 10);
$encrypted = base64_encode(sha1($password . $salt, true) . $salt);
$hash = array("salt" => $salt, "encrypted" => $encrypted);
return $hash;

/**
* Decrypting password
* @param salt, password
* returns hash string
*/
public function checkhashSSHA($salt, $password) {

$hash = base64_encode(sha1($password . $salt, true) . $salt);

return $hash;

?>

1/14/2016 11:10 PM

Android Login and Registration with PHP, MySQL and SQLite

11 of 45

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

REGISTER.PHP

<?php

require_once 'include/DB_Functions.php';
$db = new DB_Functions();
// json response array
$response = array("error" => FALSE);

if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['password'])) {


// receiving the post params
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];

// check if user is already existed with the same email


if ($db->isUserExisted($email)) {
// user already existed
$response["error"] = TRUE;
$response["error_msg"] = "User already existed with " . $email;
echo json_encode($response);
} else {
// create a new user
$user = $db->storeUser($name, $email, $password);
if ($user) {
// user stored successfully
$response["error"] = FALSE;
$response["uid"] = $user["unique_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user failed to store
$response["error"] = TRUE;
$response["error_msg"] = "Unknown error occurred in registration!";
echo json_encode($response);
}
}
} else {
$response["error"] = TRUE;
$response["error_msg"] = "Required parameters (name, email or password) is missing!"
echo json_encode($response);
1/14/2016 11:10 PM

Android Login and Registration with PHP, MySQL and SQLite

12 of 45

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

LOGIN.PHP

<?php
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
// json response array
$response = array("error" => FALSE);

if (isset($_POST['email']) && isset($_POST['password'])) {


// receiving the post params
$email = $_POST['email'];
$password = $_POST['password'];

// get the user by email and password


$user = $db->getUserByEmailAndPassword($email, $password);

if ($user != false) {
// use is found
$response["error"] = FALSE;
$response["uid"] = $user["unique_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user is not found with the credentials
$response["error"] = TRUE;
$response["error_msg"] = "Login credentials are wrong. Please try again!"
echo json_encode($response);
}
} else {
// required post params is missing
$response["error"] = TRUE;
$response["error_msg"] = "Required parameters email or password is missing!";
echo json_encode($response);
}
1/14/2016 11:10 PM

Android Login and Registration with PHP, MySQL and SQLite

13 of 45

{
}

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

"error": false,
"uid": "55fa7220a2c187.50984590",
"user": {
"name": "Ravi Tamada",
"email": "ravi@androidhive.info",
"created_at": "2015-09-17 13:26:16",
"updated_at": null
}

"error": 1,
"error_msg": "Unknown error occurred in registration!"

1/14/2016 11:10 PM

Android Login and Registration with PHP, MySQL and SQLite

14 of 45

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

"error": 2,
"error_msg": "User already existed with ravi8x@androidhive.info"

"error": false,
"uid": "55fa7220a2c187.50984590",
"user": {
"name": "Ravi Tamada",
"email": "ravi@androidhive.info",
"created_at": "2015-09-17 13:26:16",
"updated_at": null
}

"tag": "login",
"success": 0,
"error": 1,
"error_msg": "Login credentials are incorrect. Please try again!"

1/14/2016 11:10 PM

Android Login and Registration with PHP, MySQL and SQLite

15 of 45

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

BUILD.GRADLE

dependencies {
compile 'com.android.support:appcompat-v7:21.0.3'
compile 'com.android.support:support-v4:21.0.3'
compile 'com.mcxiaoke.volley:library-aar:1.0.0'
}

STRINGS.XML

<?xml version="1.0" encoding="utf-8"?>


<resources>
<string
<string
<string
<string
<string
<string
<string
<string
<string
<string
<string

</resources>

name="app_name">Android Login and Registration</string>


name="hint_email">Email</string>
name="hint_password">Password</string>
name="hint_name">Fullname</string>
name="btn_login">LOGIN</string>
name="btn_register">REGISTER</string>
name="btn_link_to_register">Not a member? Sign up now.</string>
name="btn_link_to_login">Already registred! Login Me.</string>
name="welcome">Welcome</string>
name="btn_logout">LOGOUT</string>
name="name">Fullname</string>

1/14/2016 11:10 PM

Android Login and Registration with PHP, MySQL and SQLite

16 of 45

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

<?xml version="1.0" encoding="utf-8"?>


<resources>
<color
<color
<color
<color
<color
<color
<color
<color
<color
<color
<color
<color
<color

name="bg_login">#26ae90</color>
name="bg_register">#2e3237</color>
name="bg_main">#428bca</color>
name="white">#ffffff</color>
name="input_login">#222222</color>
name="input_login_hint">#999999</color>
name="input_register">#888888</color>
name="input_register_bg">#3b4148</color>
name="input_register_hint">#5e6266</color>
name="btn_login">#26ae90</color>
name="btn_login_bg">#eceef1</color>
name="lbl_name">#333333</color>
name="btn_logut_bg">#ff6861</color>

</resources>

APPCONFIG.JAVA

package info.androidhive.loginandregistration.app;

public class AppConfig {


// Server user login url
public static String URL_LOGIN = "http://192.168.0.102:8888/android_login_api/login.ph
}

// Server user register url


public static String URL_REGISTER = "http://192.168.0.102:8888/android_login_api/regis

APPCONTROLLER.JAVA

package info.androidhive.loginandregistration.app;

1/14/2016 11:10 PM

Android Login and Registration with PHP, MySQL and SQLite

17 of 45

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

public class AppController extends Application {

public static final String TAG = AppController.class.getSimpleName();


private RequestQueue mRequestQueue;

private static AppController mInstance;


@Override
public void onCreate() {
super.onCreate();
mInstance = this;
}

public static synchronized AppController getInstance() {


return mInstance;
}

public RequestQueue getRequestQueue() {


if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
}

return mRequestQueue;

public <T> void addToRequestQueue(Request<T> req, String tag) {


req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}

public void cancelPendingRequests(Object tag) {


if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}

1/14/2016 11:10 PM

Android Login and Registration with PHP, MySQL and SQLite

18 of 45

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

ANDROIDMANIFEST.XML

<?xml version="1.0" encoding="utf-8"?>


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="info.androidhive.loginandregistration"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="21" />

<uses-permission android:name="android.permission.INTERNET" />

<application
android:name="info.androidhive.loginandregistration.app.AppController"
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".LoginActivity"
android:label="@string/app_name"
android:launchMode="singleTop"
android:windowSoftInputMode="adjustPan" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".RegisterActivity"
android:label="@string/app_name"
android:launchMode="singleTop"
android:windowSoftInputMode="adjustPan" />
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:launchMode="singleTop" />
</application>

</manifest>

1/14/2016 11:10 PM

Android Login and Registration with PHP, MySQL and SQLite

19 of 45

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

SESSIONMANAGER.JAVA

package info.androidhive.loginandregistration.helper;
import
import
import
import

android.content.Context;
android.content.SharedPreferences;
android.content.SharedPreferences.Editor;
android.util.Log;

public class SessionManager {


// LogCat tag
private static String TAG = SessionManager.class.getSimpleName();
// Shared Preferences
SharedPreferences pref;
Editor editor;
Context _context;

// Shared pref mode


int PRIVATE_MODE = 0;

// Shared preferences file name


private static final String PREF_NAME = "AndroidHiveLogin";
private static final String KEY_IS_LOGGEDIN = "isLoggedIn";

public SessionManager(Context context) {


this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void setLogin(boolean isLoggedIn) {

editor.putBoolean(KEY_IS_LOGGEDIN, isLoggedIn);
// commit changes
editor.commit();

Log.d(TAG, "User login session modified!");

public boolean isLoggedIn(){


return pref.getBoolean(KEY_IS_LOGGEDIN, false);
}

1/14/2016 11:10 PM

Android Login and Registration with PHP, MySQL and SQLite

20 of 45

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

SQLITEHANDLER.JAVA

/**
* Author: Ravi Tamada
* URL: www.androidhive.info
* twitter: http://twitter.com/ravitamada
* */
package info.androidhive.loginandregistration.helper;
import
import
import
import
import
import

android.content.ContentValues;
android.content.Context;
android.database.Cursor;
android.database.sqlite.SQLiteDatabase;
android.database.sqlite.SQLiteOpenHelper;
android.util.Log;

import java.util.HashMap;

public class SQLiteHandler extends SQLiteOpenHelper {

private static final String TAG = SQLiteHandler.class.getSimpleName();


// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "android_api";
// Login table name
private static final String TABLE_USER = "user";
// Login Table
private static
private static
private static
private static
private static

Columns names
final String KEY_ID = "id";
final String KEY_NAME = "name";
final String KEY_EMAIL = "email";
final String KEY_UID = "uid";
final String KEY_CREATED_AT = "created_at";

public SQLiteHandler(Context context) {


super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_USER + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_EMAIL + " TEXT UNIQUE," + KEY_UID + " TEXT,"
+ KEY_CREATED_AT + " TEXT" + ")";
db.execSQL(CREATE_LOGIN_TABLE);
Log.d(TAG, "Database tables created");

1/14/2016 11:10 PM

Android Login and Registration with PHP, MySQL and SQLite

21 of 45

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_USER);
}

// Create tables again


onCreate(db);

/**
* Storing user details in database
* */
public void addUser(String name, String email, String uid, String created_at) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, name); // Name
values.put(KEY_EMAIL, email); // Email
values.put(KEY_UID, uid); // Email
values.put(KEY_CREATED_AT, created_at); // Created At
// Inserting Row
long id = db.insert(TABLE_USER, null, values);
db.close(); // Closing database connection
}

Log.d(TAG, "New user inserted into sqlite: " + id);

/**
* Getting user data from database
* */
public HashMap<String, String> getUserDetails() {
HashMap<String, String> user = new HashMap<String, String>();
String selectQuery = "SELECT * FROM " + TABLE_USER;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if (cursor.getCount() > 0) {
user.put("name", cursor.getString(1));
user.put("email", cursor.getString(2));
user.put("uid", cursor.getString(3));
user.put("created_at", cursor.getString(4));
}
cursor.close();
db.close();
// return user
Log.d(TAG, "Fetching user from Sqlite: " + user.toString());

return user;

/**
1/14/2016 11:10 PM

Android Login and Registration with PHP, MySQL and SQLite

22 of 45

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

SQLiteDatabase db = this.getWritableDatabase();
// Delete All Rows
db.delete(TABLE_USER, null, null);
db.close();

Log.d(TAG, "Deleted all user info from sqlite");

ACTIVITY_LOGIN.XML

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/bg_login"
android:gravity="center"
android:orientation="vertical"
android:padding="10dp" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical"
android:paddingLeft="20dp"
android:paddingRight="20dp" >

<EditText
android:id="@+id/email"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="@color/white"
android:hint="@string/hint_email"
android:inputType="textEmailAddress"
android:padding="10dp"
android:singleLine="true"
android:textColor="@color/input_login"
1/14/2016 11:10 PM

Android Login and Registration with PHP, MySQL and SQLite

23 of 45

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

android:id="@+id/password"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="@color/white"
android:hint="@string/hint_password"
android:inputType="textPassword"
android:padding="10dp"
android:singleLine="true"
android:textColor="@color/input_login"
android:textColorHint="@color/input_login_hint" />

<!-- Login Button -->

<Button
android:id="@+id/btnLogin"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dip"
android:background="@color/btn_login_bg"
android:text="@string/btn_login"
android:textColor="@color/btn_login" />
<!-- Link to Login Screen -->

<Button
android:id="@+id/btnLinkToRegisterScreen"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dip"
android:background="@null"
android:text="@string/btn_link_to_register"
android:textAllCaps="false"
android:textColor="@color/white"
android:textSize="15dp" />
</LinearLayout>

</LinearLayout>

LOGINACTIVITY.JAVA

/**
* Author: Ravi Tamada
* URL: www.androidhive.info
* twitter: http://twitter.com/ravitamada
1/14/2016 11:10 PM

Android Login and Registration with PHP, MySQL and SQLite

24 of 45

import
import
import
import
import
import
import
import
import
import
import
import
import

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

android.app.Activity;
android.app.ProgressDialog;
android.content.Intent;
android.os.Bundle;
android.util.Log;
android.view.View;
android.widget.Button;
android.widget.EditText;
android.widget.Toast;

com.android.volley.Request.Method;
com.android.volley.Response;
com.android.volley.VolleyError;
com.android.volley.toolbox.StringRequest;

import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import
import
import
import
import

info.androidhive.loginandregistration.R;
info.androidhive.loginandregistration.app.AppConfig;
info.androidhive.loginandregistration.app.AppController;
info.androidhive.loginandregistration.helper.SQLiteHandler;
info.androidhive.loginandregistration.helper.SessionManager;

public class LoginActivity extends Activity {


private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnLogin;
private Button btnLinkToRegister;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);

inputEmail = (EditText) findViewById(R.id.email);


inputPassword = (EditText) findViewById(R.id.password);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);

// SQLite database handler


db = new SQLiteHandler(getApplicationContext());

1/14/2016 11:10 PM

Android Login and Registration with PHP, MySQL and SQLite

25 of 45

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

// Check if user is already logged in or not


if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {

public void onClick(View view) {


String email = inputEmail.getText().toString().trim();
String password = inputPassword.getText().toString().trim();

});

// Check for empty data in the form


if (!email.isEmpty() && !password.isEmpty()) {
// login user
checkLogin(email, password);
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Please enter the credentials!", Toast.LENGTH_LONG)
.show();
}

// Link to Register Screen


btnLinkToRegister.setOnClickListener(new View.OnClickListener() {

});

public void onClick(View view) {


Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
finish();
}

/**
* function to verify login details in mysql db
* */
private void checkLogin(final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Logging in ...");
showDialog();

StringRequest strReq = new StringRequest(Method.POST,


AppConfig.URL_LOGIN, new Response.Listener<String>() {
1/14/2016 11:10 PM

Android Login and Registration with PHP, MySQL and SQLite

26 of 45

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

Log.d(TAG, "Login Response: " + response.toString());


hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);

// Now store the user in SQLite


String uid = jObj.getString("uid");

JSONObject user = jObj.getJSONObject("user");


String name = user.getString("name");
String email = user.getString("email");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUser(name, email, uid, created_at);

// Launch main activity


Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
finish();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(
}

}
}, new Response.ErrorListener() {

}) {

@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}

1/14/2016 11:10 PM

Android Login and Registration with PHP, MySQL and SQLite

27 of 45

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

Map<String, String> params = new HashMap<String, String>();


params.put("email", email);
params.put("password", password);

};
}

return params;

// Adding request to request queue


AppController.getInstance().addToRequestQueue(strReq, tag_string_req);

private void showDialog() {


if (!pDialog.isShowing())
pDialog.show();
}

private void hideDialog() {


if (pDialog.isShowing())
pDialog.dismiss();
}

1/14/2016 11:10 PM

Android Login and Registration with PHP, MySQL and SQLite

28 of 45

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

ACTIVITY_REGISTER.XML

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
1/14/2016 11:10 PM

Android Login and Registration with PHP, MySQL and SQLite

29 of 45

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

android:padding="10dp" >

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical"
android:paddingLeft="20dp"
android:paddingRight="20dp" >

<EditText
android:id="@+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="@color/input_register_bg"
android:hint="@string/hint_name"
android:padding="10dp"
android:singleLine="true"
android:inputType="textCapWords"
android:textColor="@color/input_register"
android:textColorHint="@color/input_register_hint" />
<EditText
android:id="@+id/email"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="@color/input_register_bg"
android:hint="@string/hint_email"
android:inputType="textEmailAddress"
android:padding="10dp"
android:singleLine="true"
android:textColor="@color/input_register"
android:textColorHint="@color/input_register_hint" />
<EditText
android:id="@+id/password"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="@color/input_register_bg"
android:hint="@string/hint_password"
android:inputType="textPassword"
android:padding="10dp"
android:singleLine="true"
android:textColor="@color/input_register"
android:textColorHint="@color/input_register_hint" />
<!-- Login Button -->

<Button
android:id="@+id/btnRegister"
android:layout_width="fill_parent"
1/14/2016 11:10 PM

Android Login and Registration with PHP, MySQL and SQLite

30 of 45

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

android:text="@string/btn_register"
android:textColor="@color/white" />

<!-- Link to Login Screen -->

<Button
android:id="@+id/btnLinkToLoginScreen"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dip"
android:background="@null"
android:text="@string/btn_link_to_login"
android:textAllCaps="false"
android:textColor="@color/white"
android:textSize="15dp" />
</LinearLayout>

</LinearLayout>

REGISTERACTIVITY.JAVA

/**
* Author: Ravi Tamada
* URL: www.androidhive.info
* twitter: http://twitter.com/ravitamada
*/
package info.androidhive.loginandregistration.activity;
import
import
import
import
import
import
import
import
import
import
import
import
import

android.app.Activity;
android.app.ProgressDialog;
android.content.Intent;
android.os.Bundle;
android.util.Log;
android.view.View;
android.widget.Button;
android.widget.EditText;
android.widget.Toast;

com.android.volley.Request.Method;
com.android.volley.Response;
com.android.volley.VolleyError;
com.android.volley.toolbox.StringRequest;
1/14/2016 11:10 PM

Android Login and Registration with PHP, MySQL and SQLite

31 of 45

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

import java.util.HashMap;
import java.util.Map;
import
import
import
import
import

info.androidhive.loginandregistration.R;
info.androidhive.loginandregistration.app.AppConfig;
info.androidhive.loginandregistration.app.AppController;
info.androidhive.loginandregistration.helper.SQLiteHandler;
info.androidhive.loginandregistration.helper.SessionManager;

public class RegisterActivity extends Activity {


private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnRegister;
private Button btnLinkToLogin;
private EditText inputFullName;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);

inputFullName = (EditText) findViewById(R.id.name);


inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);

// Session manager
session = new SessionManager(getApplicationContext());
// SQLite database handler
db = new SQLiteHandler(getApplicationContext());

// Check if user is already logged in or not


if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(RegisterActivity.this,
MainActivity.class);
startActivity(intent);
finish();
}
// Register Button Click event
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {

1/14/2016 11:10 PM

Android Login and Registration with PHP, MySQL and SQLite

32 of 45

});

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty()) {


registerUser(name, email, password);
} else {
Toast.makeText(getApplicationContext(),
"Please enter your details!", Toast.LENGTH_LONG)
.show();
}

// Link to Login Screen


btnLinkToLogin.setOnClickListener(new View.OnClickListener() {

});

public void onClick(View view) {


Intent i = new Intent(getApplicationContext(),
LoginActivity.class);
startActivity(i);
finish();
}

/**
* Function to store user in MySQL database will post params(tag, name,
* email, password) to register url
* */
private void registerUser(final String name, final String email,
final String password) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Registering ...");
showDialog();

StringRequest strReq = new StringRequest(Method.POST,


AppConfig.URL_REGISTER, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
// User successfully stored in MySQL
// Now store the user in sqlite
String uid = jObj.getString("uid");

JSONObject user = jObj.getJSONObject("user");


String name = user.getString("name");
1/14/2016 11:10 PM

Android Login and Registration with PHP, MySQL and SQLite

33 of 45

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

// Inserting row in users table


db.addUser(name, email, uid, created_at);

Toast.makeText(getApplicationContext(), "User successfully registe

// Launch login activity


Intent intent = new Intent(
RegisterActivity.this,
LoginActivity.class);
startActivity(intent);
finish();
} else {

// Error occurred in registration. Get the error


// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();

}
} catch (JSONException e) {
e.printStackTrace();
}

}
}, new Response.ErrorListener() {

}) {

};
}

@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
@Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("name", name);
params.put("email", email);
params.put("password", password);
}

return params;

// Adding request to request queue


AppController.getInstance().addToRequestQueue(strReq, tag_string_req);

private void showDialog() {


1/14/2016 11:10 PM

Android Login and Registration with PHP, MySQL and SQLite

34 of 45

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

private void hideDialog() {


if (pDialog.isShowing())
pDialog.dismiss();
}

1/14/2016 11:10 PM

Android Login and Registration with PHP, MySQL and SQLite

35 of 45

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

1/14/2016 11:10 PM

Android Login and Registration with PHP, MySQL and SQLite

36 of 45

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:gravity="center"
android:orientation="vertical" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/welcome"
android:textSize="20dp" />
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:textColor="@color/lbl_name"
android:textSize="24dp" />
<TextView
android:id="@+id/email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="13dp" />

<Button
android:id="@+id/btnLogout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dip"
android:background="@color/btn_logut_bg"
android:text="@string/btn_logout"
android:textAllCaps="false"
android:textColor="@color/white"
android:textSize="15dp" />
</LinearLayout>

</RelativeLayout>

1/14/2016 11:10 PM

Android Login and Registration with PHP, MySQL and SQLite

37 of 45

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

MAINACTIVITY.JAVA

package info.androidhive.loginandregistration;

import info.androidhive.loginandregistration.helper.SQLiteHandler;
import info.androidhive.loginandregistration.helper.SessionManager;
import java.util.HashMap;
import
import
import
import
import
import

android.app.Activity;
android.content.Intent;
android.os.Bundle;
android.view.View;
android.widget.Button;
android.widget.TextView;

public class MainActivity extends Activity {


private TextView txtName;
private TextView txtEmail;
private Button btnLogout;

private SQLiteHandler db;


private SessionManager session;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

txtName = (TextView) findViewById(R.id.name);


txtEmail = (TextView) findViewById(R.id.email);
btnLogout = (Button) findViewById(R.id.btnLogout);
// SqLite database handler
db = new SQLiteHandler(getApplicationContext());

// session manager
session = new SessionManager(getApplicationContext());
if (!session.isLoggedIn()) {
logoutUser();
}

// Fetching user details from sqlite


HashMap<String, String> user = db.getUserDetails();
String name = user.get("name");
String email = user.get("email");

// Displaying the user details on the screen


txtName.setText(name);
txtEmail.setText(email);
1/14/2016 11:10 PM

Android Login and Registration with PHP, MySQL and SQLite

38 of 45

});

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

@Override
public void onClick(View v) {
logoutUser();
}

/**
* Logging out the user. Will set isLoggedIn flag to false in shared
* preferences Clears the user data from sqlite users table
* */
private void logoutUser() {
session.setLogin(false);
db.deleteUsers();

// Launching the login activity


Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();

1/14/2016 11:10 PM

Android Login and Registration with PHP, MySQL and SQLite

39 of 45

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

1/14/2016 11:10 PM

Android Login and Registration with PHP, MySQL and SQLite

40 of 45

1.1k

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

Tweet

Like

1/14/2016 11:10 PM

Android Login and Registration with PHP, MySQL and SQLite

41 of 45

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

Advertise Here

1/14/2016 11:10 PM

Android Login and Registration with PHP, MySQL and SQLite

42 of 45

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

AndroidHive

34,171 likes

Be the first of your friends to like this

1/14/2016 11:10 PM

Android Login and Registration with PHP, MySQL and SQLite

43 of 45

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

1/14/2016 11:10 PM

Android Login and Registration with PHP, MySQL and SQLite

44 of 45

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

1/14/2016 11:10 PM

Android Login and Registration with PHP, MySQL and SQLite

45 of 45

http://www.androidhive.info/2012/01/android-login-and-registration-wit...

1/14/2016 11:10 PM

Das könnte Ihnen auch gefallen