Guten Tag liebe Community
Dies ist das erste einer vielzahl von Tutorial's wie man eine App für sein Forum erstellt.
In diesen Tutorials gezeigen Code's sind abweichend von dem Orginalcode der M-Core App!
Dies ist das erste einer vielzahl von Tutorial's wie man eine App für sein Forum erstellt.
In diesen Tutorials gezeigen Code's sind abweichend von dem Orginalcode der M-Core App!
1. Erstellen der MySQL Datenbank
Ihr solltet euch zuerst eine MySQL Datenbank erstellen (Navicat,..). Dazu installiert ihr nun zuerst Xampp und danach Navicat (Downloadlink's sind unten zu finden). Öffnet nun die Console in Navicat in dem Ihr rechtsklickt auf eure Verbindung und auf Console klickt. Dort gebt ihr nun folgende SQL Code's ein.
Quellcode
2. Erstellen der PHP API Klassen
Diese Funktion wird allgemein in jeder Standartverbindung der PHP API Klassen verwendet.
Erstellt nun einen Ordner in eurem xampp/htdocs namens "android_login_api" und in diesem Ordner einen Ordner namens "include"
Die folgenden PHP File's müssen in folgende Ordner:
config.php - In den "include" Ordner
DB_Connect.php - In den "include" Ordner
DB_Functions.php - In den "include" Ordner
index.php - In den "android_login_api" Ordner
config.php - Einstellung zur Verbindung der Datenbank
DB_Connect.php - Verbindung und schließen der Sitzung
PHP-Quellcode
- <?php
- class DB_Connect {
- // constructor
- function __construct() {
- }
- // destructor
- function __destruct() {
- // $this->close();
- }
- // Connecting to database
- public function connect() {
- require_once 'config.php';
- // connecting to mysql
- $con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
- // selecting database
- mysql_select_db(DB_DATABASE);
- // return database handler
- return $con;
- }
- // Closing database connection
- public function close() {
- mysql_close();
- }
- }
- ?>
DB_Functions.php -Diese Datei enthält Funktionen, um Benutzer in der Datenbank zu speichern etc.
PHP-Quellcode
- <?php
- class DB_Functions {
- private $db;
- //put your code here
- // constructor
- function __construct() {
- require_once 'DB_Connect.php';
- // connecting to database
- $this->db = new DB_Connect();
- $this->db->connect();
- }
- // 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
- $result = mysql_query("INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at) VALUES('$uuid', '$name', '$email', '$encrypted_password', '$salt', NOW())");
- // check for successful store
- if ($result) {
- // get user details
- $uid = mysql_insert_id(); // last inserted id
- $result = mysql_query("SELECT * FROM users WHERE uid = $uid");
- // return user details
- return mysql_fetch_array($result);
- } else {
- return false;
- }
- }
- /**
- * Get user by email and password
- */
- public function getUserByEmailAndPassword($email, $password) {
- $result = mysql_query("SELECT * FROM users WHERE email = '$email'") or die(mysql_error());
- // check for result
- $no_of_rows = mysql_num_rows($result);
- if ($no_of_rows > 0) {
- $result = mysql_fetch_array($result);
- $salt = $result['salt'];
- $encrypted_password = $result['encrypted_password'];
- $hash = $this->checkhashSSHA($salt, $password);
- // check for password equality
- if ($encrypted_password == $hash) {
- // user authentication details are correct
- return $result;
- }
- } else {
- // user not found
- return false;
- }
- }
- /**
- * Check user is existed or not
- */
- public function isUserExisted($email) {
- $result = mysql_query("SELECT email from users WHERE email = '$email'");
- $no_of_rows = mysql_num_rows($result);
- if ($no_of_rows > 0) {
- // user existed
- return true;
- } else {
- // user not existed
- 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;
- }
- }
- ?>
index.php Diese Datei spielt die Rolle akzeptierte anfragen Antworten zu geben.
PHP-Quellcode
- <?php
- /**
- * File to handle all API requests
- * Accepts GET and POST
- *
- * Each request will be identified by TAG
- * Response will be JSON data
- /**
- * check for POST request
- */
- if (isset($_POST['tag']) && $_POST['tag'] != '') {
- // get tag
- $tag = $_POST['tag'];
- // include db handler
- require_once 'include/DB_Functions.php';
- $db = new DB_Functions();
- // response Array
- $response = array("tag" => $tag, "success" => 0, "error" => 0);
- // check for tag type
- if ($tag == 'login') {
- // Request type is check Login
- $email = $_POST['email'];
- $password = $_POST['password'];
- // check for user
- $user = $db->getUserByEmailAndPassword($email, $password);
- if ($user != false) {
- // user found
- // echo json with success = 1
- $response["success"] = 1;
- $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 not found
- // echo json with error = 1
- $response["error"] = 1;
- $response["error_msg"] = "Incorrect email or password!";
- echo json_encode($response);
- }
- } else if ($tag == 'register') {
- // Request type is Register new user
- $name = $_POST['name'];
- $email = $_POST['email'];
- $password = $_POST['password'];
- // check if user is already existed
- if ($db->isUserExisted($email)) {
- // user is already existed - error response
- $response["error"] = 2;
- $response["error_msg"] = "User already existed";
- echo json_encode($response);
- } else {
- // store user
- $user = $db->storeUser($name, $email, $password);
- if ($user) {
- // user stored successfully
- $response["success"] = 1;
- $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"] = 1;
- $response["error_msg"] = "Error occured in Registartion";
- echo json_encode($response);
- }
- }
- } else {
- echo "Invalid Request";
- }
- } else {
- echo "Access Denied";
- }
- ?>
3. Das Android Projekt starten
Zuerst sollten wir nun Eclipse starten zum Programmieren der App, den Download findet ihr unten.
Erstellt nun ein neues Projekt indem ihr auf File -> New Android Projekt klicken. Danach füllt ihr alle Felder aus und habt nun ein neues Projekt.
Als nächstes erstellen wie ein neues Package für unsere ganzen library files. Dazu macht ihr einen Rechtsklick auf src -> New -> Package und nennt diese "library"
JSON Parser Klasse
Als nächtes brauchen wir eine Parser Klasse um die JSON zu analysieren und zu antworten.
Dazu erstellt ihr eine Neue Klasse in eurer library und nennt diese "JSONParser.java" und fügt folgenden Code unter eurem
.
Java-Quellcode
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.UnsupportedEncodingException;
- import java.util.List;
- import org.apache.http.HttpEntity;
- import org.apache.http.HttpResponse;
- import org.apache.http.NameValuePair;
- import org.apache.http.client.ClientProtocolException;
- import org.apache.http.client.entity.UrlEncodedFormEntity;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.impl.client.DefaultHttpClient;
- import org.json.JSONException;
- import org.json.JSONObject;
- import android.util.Log;
- public class JSONParser {
- static InputStream is = null;
- static JSONObject jObj = null;
- static String json = "";
- // constructor
- public JSONParser() {
- }
- public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
- // Making HTTP request
- try {
- // defaultHttpClient
- DefaultHttpClient httpClient = new DefaultHttpClient();
- HttpPost httpPost = new HttpPost(url);
- httpPost.setEntity(new UrlEncodedFormEntity(params));
- HttpResponse httpResponse = httpClient.execute(httpPost);
- HttpEntity httpEntity = httpResponse.getEntity();
- is = httpEntity.getContent();
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- } catch (ClientProtocolException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- try {
- BufferedReader reader = new BufferedReader(new InputStreamReader(
- is, "iso-8859-1"), 8);
- StringBuilder sb = new StringBuilder();
- String line = null;
- while ((line = reader.readLine()) != null) {
- sb.append(line + "n");
- }
- is.close();
- json = sb.toString();
- Log.e("JSON", json);
- } catch (Exception e) {
- Log.e("Buffer Error", "Error converting result " + e.toString());
- }
- // try parse the string to a JSON object
- try {
- jObj = new JSONObject(json);
- } catch (JSONException e) {
- Log.e("JSON Parser", "Error parsing data " + e.toString());
- }
- // return JSON String
- return jObj;
- }
- }
SQL Database Handler Klasse
Ich benutze in der Anwendung eine SQLite Datenbank zum speicher von Benutzerdaten. Doch es bleibt euch überlasse welche Ihr wählt.
Erstellt nun wieder ein neues package namens "DatabaseHandler.java" und füge folgenden Code hinzu nach
.
Java-Quellcode
- import java.util.HashMap;
- import android.content.ContentValues;
- import android.content.Context;
- import android.database.Cursor;
- import android.database.sqlite.SQLiteDatabase;
- import android.database.sqlite.SQLiteOpenHelper;
- public class DatabaseHandler extends SQLiteOpenHelper {
- // 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_LOGIN = "login";
- // Login Table Columns names
- private static final String KEY_ID = "id";
- private static final String KEY_NAME = "name";
- private static final String KEY_EMAIL = "email";
- private static final String KEY_UID = "uid";
- private static final String KEY_CREATED_AT = "created_at";
- public DatabaseHandler(Context context) {
- super(context, DATABASE_NAME, null, DATABASE_VERSION);
- }
- // Creating Tables
- @Override
- public void onCreate(SQLiteDatabase db) {
- String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_LOGIN + "("
- + KEY_ID + " INTEGER PRIMARY KEY,"
- + KEY_NAME + " TEXT,"
- + KEY_EMAIL + " TEXT UNIQUE,"
- + KEY_UID + " TEXT,"
- + KEY_CREATED_AT + " TEXT" + ")";
- db.execSQL(CREATE_LOGIN_TABLE);
- }
- // Upgrading database
- @Override
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
- // Drop older table if existed
- db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOGIN);
- // 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
- db.insert(TABLE_LOGIN, null, values);
- db.close(); // Closing database connection
- }
- /**
- * Getting user data from database
- * */
- public HashMap<String, String> getUserDetails(){
- HashMap<String,String> user = new HashMap<String,String>();
- String selectQuery = "SELECT * FROM " + TABLE_LOGIN;
- 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
- return user;
- }
- /**
- * Getting user login status
- * return true if rows are there in table
- * */
- public int getRowCount() {
- String countQuery = "SELECT * FROM " + TABLE_LOGIN;
- SQLiteDatabase db = this.getReadableDatabase();
- Cursor cursor = db.rawQuery(countQuery, null);
- int rowCount = cursor.getCount();
- db.close();
- cursor.close();
- // return row count
- return rowCount;
- }
- /**
- * Re crate database
- * Delete all tables and create them again
- * */
- public void resetTables(){
- SQLiteDatabase db = this.getWritableDatabase();
- // Delete All Rows
- db.delete(TABLE_LOGIN, null, null);
- db.close();
- }
- }
User Function Klasse
Erstellt nun wieder eine neue Klasse unter dem library package und nennt diese "UserFunctions.java"
fügt wieder folgenden Code hinzu nach:
.
Java-Quellcode
- import java.util.ArrayList;
- import java.util.List;
- import org.apache.http.NameValuePair;
- import org.apache.http.message.BasicNameValuePair;
- import org.json.JSONObject;
- import android.content.Context;
- public class UserFunctions {
- private JSONParser jsonParser;
- // Testing in localhost using wamp or xampp
- // use [URL]http://10.0.2.2/[/URL] to connect to your localhost ie [URL="http://localhost/"]BlackEvolution - Coming Soon[/URL]
- private static String loginURL = "[URL]http://10.0.2.2/ah_login_api/[/URL]";
- private static String registerURL = "[URL]http://10.0.2.2/ah_login_api/[/URL]";
- private static String login_tag = "login";
- private static String register_tag = "register";
- // constructor
- public UserFunctions(){
- jsonParser = new JSONParser();
- }
- /**
- * function make Login Request
- * @param email
- * @param password
- * */
- public JSONObject loginUser(String email, String password){
- // Building Parameters
- List<NameValuePair> params = new ArrayList<NameValuePair>();
- params.add(new BasicNameValuePair("tag", login_tag));
- params.add(new BasicNameValuePair("email", email));
- params.add(new BasicNameValuePair("password", password));
- JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
- // return json
- // Log.e("JSON", json.toString());
- return json;
- }
- /**
- * function make Login Request
- * @param name
- * @param email
- * @param password
- * */
- public JSONObject registerUser(String name, String email, String password){
- // Building Parameters
- List<NameValuePair> params = new ArrayList<NameValuePair>();
- params.add(new BasicNameValuePair("tag", register_tag));
- params.add(new BasicNameValuePair("name", name));
- params.add(new BasicNameValuePair("email", email));
- params.add(new BasicNameValuePair("password", password));
- // getting JSON Object
- JSONObject json = jsonParser.getJSONFromUrl(registerURL, params);
- // return json
- return json;
- }
- /**
- * Function get Login status
- * */
- public boolean isUserLoggedIn(Context context){
- DatabaseHandler db = new DatabaseHandler(context);
- int count = db.getRowCount();
- if(count > 0){
- // user logged in
- return true;
- }
- return false;
- }
- /**
- * Function to logout user
- * Reset Database
- * */
- public boolean logoutUser(Context context){
- DatabaseHandler db = new DatabaseHandler(context);
- db.resetTables();
- return true;
- }
- }
Teil 2 wird nächste Woche kommen und dort werde ich euch zeigen, wie man das Design der Android App mit den Funktionen verbindet.
Bis dahin
Euer Armin ♥
[HR][/HR]
Downloadlinks
Xampp
Navicat
Eclipse
Alle Downloadlinks sind von Chip.de und enthalten keinerlei Vieren etc.
Xampp
Navicat
Eclipse
Alle Downloadlinks sind von Chip.de und enthalten keinerlei Vieren etc.
[HR][/HR]
Credits
Ein besonderes Dankeschön geht an meine Kollegen von Androhive.info die mit mir daran gearbeiten haben und mir die möglichkeit geben haben solch tolle funktionen gemeinsam mit Ihnen zu erstellen. Natürlich möchte ich mein Team "LAZY" nicht vergessen die mir die bekanntschaft gemacht haben.[HR][/HR]