title: Display database value in android app, how?
body: <p>i am working on a small application for android, i already built a mysql database and i want to display table values on the screen.is there any tutorial or template for this?</p>
  
  <p>how can I do it..</p>
  
  <p>I have the following .java concerning database:</p>
  
  <p>DatabahseHander.java</p>
  
  <pre><code>    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&lt;String, String&gt; getUserDetails(){
      HashMap&lt;String,String&gt; user = new HashMap&lt;String,String&gt;();
      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() &gt; 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();
  }
  
  
  
  
  }
  </code></pre>
  
  <p>UserFunctions.java</p>
  
  <pre><code>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&lt;NameValuePair&gt; params = new ArrayList&lt;NameValuePair&gt;();
      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&lt;NameValuePair&gt; params = new ArrayList&lt;NameValuePair&gt;();
      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&lt;NameValuePair&gt; params = new ArrayList&lt;NameValuePair&gt;();
      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 &gt; 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;
  }
  
     }
  </code></pre>
  
  <p>index.php on my server</p>
  
  <pre><code>&lt;?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']) &amp;&amp; $_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" =&gt; $tag, "success" =&gt; 0, "error" =&gt; 0);
  
  // check for tag type
  if ($tag == 'login') {
      // Request type is check Login
      $email = $_POST['email'];
      $password = $_POST['password'];
  
      // check for user
      $user = $db-&gt;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-&gt;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-&gt;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-&gt;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-&gt;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";
        }
        ?&gt;
  </code></pre>
  
  <p>DB_functions.php</p>
  
  <pre><code>&lt;?php
  
  class DB_Functions {
  
  private $db;
  
  //put your code here
  // constructor
  function __construct() {
      require_once 'DB_Connect.php';
      // connecting to database
      $this-&gt;db = new DB_Connect();
      $this-&gt;db-&gt;connect();
  }
  
  // destructor
  function __destruct() {
  
  }
  
  /**
   * Storing new user
   * returns user details
   */
  public function storeUser($name, $email, $password) {
      $uuid = uniqid('', true);
      $hash = $this-&gt;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 &gt; 0) {
          $result = mysql_fetch_array($result);
          $salt = $result['salt'];
          $encrypted_password = $result['encrypted_password'];
          $hash = $this-&gt;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 &gt; 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 &gt; 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" =&gt; $salt, "encrypted" =&gt; $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;
  }
  </code></pre>
  
  <p>}</p>
  
  <p>?></p>
  
  <p>I have a table with the following rows:
  unique_sid, sname, smax, sbet, created_at</p>
  
  <p>i want to show on my application the values from sname from the database - what i have to add in my code so i can show the sname in any .xml</p>