在android app中显示数据库值,怎么样?

时间:2014-06-01 14:02:09

标签: android mysql database

我正在开发一个用于android的小应用程序,我已经构建了一个mysql数据库,我想在屏幕上显示表值。是否有任何教程或模板?

我该怎么办..

我有以下关于数据库的.java:

DatabahseHander.java

    package com.minilotto.library;

    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";
private static final String TABLE_SESSION = "session";

// 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";
private static final String KEY_SID = "sid";
private static final String KEY_SNAME = "sname";    
private static final String KEY_SMAX = "smax";
private static final String KEY_SBET = "sbet";

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);

    String CREATE_SESSION_TABLE = "CREATE TABLE " + TABLE_SESSION + "("
            + KEY_SID + " INTEGER PRIMARY KEY,"
            + KEY_SNAME + " TEXT,"
            + KEY_SMAX + " TEXT,"
            + KEY_SBET + " TEXT,"
            + KEY_CREATED_AT + " TEXT" + ")";
    db.execSQL(CREATE_SESSION_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);
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_SESSION);
    // Create tables again
    onCreate(db);
}

/**
 * Storing session details in database
 * */
public void addSession(String sname, String smax, String sbet, String created_at) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_SNAME, sname); // Name
    values.put(KEY_SMAX, smax); // Email
    values.put(KEY_SBET, sbet); // Email
    values.put(KEY_CREATED_AT, created_at); // Created At

    // Inserting Row
    db.insert(TABLE_SESSION, null, values);
    db.close(); // Closing database connection
}



/**
 * 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();
}




}

UserFunctions.java

package com.minilotto.library;

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 http://10.0.2.2/ to connect to your localhost ie http://localhost/
private static String loginURL = "http://androidprojekt.esy.es/android_login_api/";
private static String registerURL = "http://androidprojekt.esy.es/android_login_api/";
private static String sessionURL = "http://androidprojekt.esy.es/android_login_api/";

private static String login_tag = "login";
private static String register_tag = "register";
private static String session_tag = "start_session";

// constructor
public UserFunctions(){
    jsonParser = new JSONParser();
}

public JSONObject openSession(String sname, String smax, String sbet){
    // Building Parameters
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("tag", session_tag));
    params.add(new BasicNameValuePair("sname", sname));
    params.add(new BasicNameValuePair("smax", smax));
    params.add(new BasicNameValuePair("sbet", sbet));
    JSONObject json = jsonParser.getJSONFromUrl(sessionURL, params);
    // return json
    // Log.e("JSON", json.toString());
    return json;
}

/**
 * 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;
}

/**
 * Function to end session
 * Reset Database
 * */
public boolean logoutSession(Context context){
    DatabaseHandler db = new DatabaseHandler(context);
    db.resetTables();
    return true;
}

   }

我的服务器上的index.php

<?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($sname)) {
        // 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 if 
($tag == 'start_session') {
    // Request type is Register new session
    $sname = $_POST['sname'];
    $smax = $_POST['smax'];
    $sbet = $_POST['sbet'];

    // check if user is already existed
    if ($db->isSessionExisted($sname)) {
        // user is already existed - error response
        $response["error"] = 3;
        $response["error_msg"] = "Session already existed";
        echo json_encode($response);
    } else {
        // store user
        $session = $db->storeSession($sname, $smax, $sbet);
        if ($session=!false) {
            // user stored successfully
            $response["success"] = 1;
            $response["sid"] = $session["unique_id"];
            $response["session"]["sname"] = $session["sname"];
            $response["session"]["smax"] = $session["smax"];
            $response["session"]["sbet"] = $session["sbet"];
            $response["session"]["created_at"] = $session["created_at"];
            $response["session"]["updated_at"] = $session["updated_at"];
            echo json_encode($response);
        } else {
            // user failed to store
            $response["error"] = 1;
            $response["error_msg"] = "SESSION Error occured in Registartion";
            echo json_encode($response);
          }
    }
} else {
    echo "Invalid Request";
}
      } else {
echo "Access Denied";
      }
      ?>

DB_functions.php

<?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;
    }
}


    /**
 * Storing new session
 * returns session details
 */
public function storeSession($sname, $smax, $sbet) {
    $usid = uniqid('', true);
    $result = mysql_query("INSERT INTO session(unique_sid, sname, smax, sbet, created_at) VALUES('$usid', '$sname', '$smax', '$sbet', NOW())");
    // check for successful store
    if ($result) {
        // get user details 
        $sid = mysql_insert_id(); // last inserted id
        $result = mysql_query("SELECT * FROM session WHERE uid = $sid");
        // 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;
    }
}

 /**
 * Check session is existed or not
 */
public function isSessionExisted($sname) {
    $result = mysql_query("SELECT sname from session WHERE sname = '$sname'");
    $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;
}

}

&GT;

我有一个包含以下行的表: unique_sid,sname,smax,sbet,created_at

我想在我的应用程序中显示来自数据库的sname的值 - 我必须在我的代码中添加,以便我可以在任何.xml中显示sname

1 个答案:

答案 0 :(得分:0)

是的,但首先您要决定如何在应用程序中显示数据,我的意思是您希望在列表视图或网格视图中显示它们,或者只是在文本视图中将它们显示为文本。

这是一个简单的帮助您从数据库中获取数据并将其显示到您的应用程序中visit it here

希望这能帮到你