Tuesday, May 22, 2012

how to insert and select in mysql with android?

LoginActivity.java



package tn.pack.ordre.enregistrer;


import org.json.JSONException;
import org.json.JSONObject;

import tn.pack.ordre.HomeActivity;
import tn.pack.ordre.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ecran_accueil);

}

public void btn_enrg(View v){
startActivity(new Intent(getApplicationContext(),EnregistrerActivity.class));
}


public void btn_login(View v) {

EditText u = (EditText) findViewById (R.id.editText_username);
EditText p = (EditText) findViewById (R.id.editText_motdepasse);

String username = u.getText().toString();
String password = p.getText().toString();

UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.loginUser(username, password);
Intent home =new Intent(getApplicationContext(),HomeActivity.class) ;

// check for login response
try {
if (json.getString("success") != null) {
// loginErrorMsg.setText("");
String res = json.getString("success");
if (Integer.parseInt(res) == 1) {
// user successfully logged in
// Store user details in SQLite Database
JSONObject json_user = json.getJSONObject("user");
System.out.println(" "+json_user.getString("userName")+" "+json_user.getString("created_at"));
//Bundle pass = new Bundle();
//pass.putString("userName", json_user.getString("userName"));
//pass.putString("created_at", json_user.getString("created_at"));
//home.putExtra("INTENT_EXTRA_STRING", pass);
//Log.d("test","uid:"+json.getString("uid"));
startActivity(home);
finish();
} else {
// Error in login
Toast.makeText(getApplicationContext(), "Erreur login",3000).show();
}
}
} catch (JSONException e) {
System.out.println("Connecter: "+e.toString());
}

}


}


JSONParser.java -parser class to parse api response JSON.



package tn.pack.ordre.enregistrer;

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;

}
}


EnregistrerActivity.java



package tn.pack.ordre.enregistrer;

import org.json.JSONException;
import org.json.JSONObject;

import tn.pack.ordre.enregistrer.UserFunctions;

import tn.pack.ordre.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class EnregistrerActivity extends Activity {


private TextView error;


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Fixe la mise en page d'une activité
setContentView(R.layout.inscription);

}



public void btn_valider() {

String user=((EditText)findViewById(R.id.et_un)).getText().toString();
String password=((EditText)findViewById(R.id.et_pw)).getText().toString();
String rpassword=((EditText)findViewById(R.id.et_rpw)).getText().toString();
String cin=((EditText) findViewById(R.id.et_cin)).getText().toString();
// String region = ((Spinner) findViewById (R.id.spinner_rg)).getSelectedItem().toString();



UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.registerUser(user,password,rpassword,cin);
try {

error=(TextView)findViewById(R.id.textViewerrer);
if (json.getString("success") != null) {

String res = json.getString("success");
if (Integer.parseInt(res) == 1) {

error.setText("enregistrement ok");


} else {
error.setText("erreur pendant l'enregistrement");

}
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("btnRegister: "+e.toString());
}


}

public void Annuler(View v) {

startActivity(new Intent(getApplicationContext(),LoginActivity.class));

}
}


UserFunctions.java -all the functions will interact with JSONParser.



package tn.pack.ordre.enregistrer;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

public class UserFunctions {

private JSONParser jsonParser;

private static String loginURL = "http://10.0.2.2/webservice/index.php";
private static String registerURL = loginURL;

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

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


public JSONObject loginUser(String userName, String password){
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", login_tag));
params.add(new BasicNameValuePair("userName", userName));
params.add(new BasicNameValuePair("password", password));
JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
// return json
// Log.e("JSON", json.toString());
return json;
}


public JSONObject registerUser(String userName, String password,String rpassword, String cin){
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", register_tag));
params.add(new BasicNameValuePair("userName", userName));
params.add(new BasicNameValuePair("cin", cin));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("rpassword", rpassword));
// params.add(new BasicNameValuePair("region", region));


// getting JSON Object
JSONObject json = jsonParser.getJSONFromUrl(registerURL, params);
// return json
return json;
}


}


config.php -This file contains constant variables to connect to database.



<?php

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


DB_Connect.php -This file is used to connect or disconnect to database.



<?php
class DB_Connect {

// constructor
function __construct() {

}

// destructor
function __destruct() {
// $this->close();
}

// Connecting to database
public function connect() {
require_once 'include/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 -This file contains functions to store user in database, get user from database.



 <?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($userName,$cin , $password, $repassword) {
$uuid = uniqid('', true);
$hash = $this->hashSSHA($password);
$encrypted_password = $hash["encrypted"]; // encrypted password
$salt = $hash["salt"]; // salt
$result = mysql_query("INSERT INTO user_appmobile(unique_id, user_name, cin, encrypted_password,encrypted_repassword, salt, created_at, updated_at) VALUES('$uuid','$userName', $cin,'$encrypted_password', $encrypted_repassword,'$salt', NOW())");
// check for successful store
if ($result) {
// get user details
$uid = mysql_insert_id(); // last inserted id
$result = mysql_query("SELECT * FROM user_appmobile WHERE uid = $uid");
// return user details
return mysql_fetch_array($result);
} else {
return false;
}
}

/**
* Get user by email and password
*/
public function getUserByCinAndPassword($cin, $password) {
$result = mysql_query("SELECT * FROM user_appmobile WHERE cin = '$cin'") 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;
}
}

/**
* Get user by userName and password
*/
public function getUserByUserNameAndPassword($userName, $password) {
$result = mysql_query("SELECT * FROM user_appmobile WHERE user_name = '$userName'") 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($cin) {
$result = mysql_query("SELECT cin from user_appmobile WHERE cin = '$cin'");
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
// user existed
return true;
} else {
// user not existed
return false;
}
}

/**
* Check user is existed or not
*/
public function isUserNameExisted($userName) {
$result = mysql_query("SELECT username from user_appmobile WHERE username = '$userName'");
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
// user Name existed
return true;
} else {
// user Name not existed
return false;
}
}
public function isCinExisted($cin) {
$result = mysql_query("SELECT username from user_appmobile WHERE cin = '$cin'");
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
// user Name existed
return true;
} else {
// user Name 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 -This file plays role of accepting requests and giving response. GET and POST requests.



<?php

/**
* 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
$userName = $_POST['userName'];
$password = $_POST['password'];

// check for user
$user = $db->getUserByUserNameAndPassword($userName, $password);
if ($user != false) {
// user found
// echo json with success = 1
$response["success"] = 1;
$response["uid"] = $user["unique_id"];
$response["user"]["userName"] = $user["user_name"];
$response["user"]["cin"] = $user["cin"];
$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 username or password!";
echo json_encode($response);
}
} else if ($tag == 'register') {
// Request type is Register new user


$userName = $_POST['userName'];
$cin = $_POST['cin'];
$password = $_POST['password'];
$repassword = $_POST['repassword'];
$region = $_POST['region'];

// check if user is already existed a separer (cas cin & cas username )
if ( ($db->isUserNameExisted($userName))&&($db->isCinExisted($cin)) ) {
// 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($userName, $cin, $password, $repassword);
if ($user) {
// user stored successfully
$response["success"] = 1;
$response["uid"] = $user["unique_id"];
$response["user"]["userName"] = $user["user_name"];
$response["user"]["cin"] = $user["cin"];
$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";
}
?>


Data Base:



    -- Base de données: `appactel`
--
-- Structure de la table `user_appmobile`
--

CREATE TABLE IF NOT EXISTS `user_appmobile` (
`uid` int(11) NOT NULL AUTO_INCREMENT,
`unique_id` varchar(23) NOT NULL,
`user_name` varchar(20) NOT NULL,
`cin` int(10) NOT NULL,
`password` varchar(20) NOT NULL,
`repassword` varchar(20) NOT NULL,
`salt` varchar(10) NOT NULL,
`created_at` datetime DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
PRIMARY KEY (`uid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;


the problem:



enter image description here



enter image description here



enter image description here



05-21 14:34:01.185: D/ddm-heap(223): Got feature list request
05-21 14:34:01.405: D/dalvikvm(223): GC freed 515 objects / 46800 bytes in 91ms
05-21 14:34:35.785: D/AndroidRuntime(223): Shutting down VM
05-21 14:34:35.785: W/dalvikvm(223): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
05-21 14:34:35.785: E/AndroidRuntime(223): Uncaught handler: thread main exiting due to uncaught exception
05-21 14:34:35.835: E/AndroidRuntime(223): java.lang.IllegalStateException: Could not find a method btn_valider(View) in the activity
05-21 14:34:35.835: E/AndroidRuntime(223): at android.view.View$1.onClick(View.java:2020)
05-21 14:34:35.835: E/AndroidRuntime(223): at android.view.View.performClick(View.java:2364)
05-21 14:34:35.835: E/AndroidRuntime(223): at android.view.View.onTouchEvent(View.java:4179)
05-21 14:34:35.835: E/AndroidRuntime(223): at android.widget.TextView.onTouchEvent(TextView.java:6541)
05-21 14:34:35.835: E/AndroidRuntime(223): at android.view.View.dispatchTouchEvent(View.java:3709)
05-21 14:34:35.835: E/AndroidRuntime(223): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
05-21 14:34:35.835: E/AndroidRuntime(223): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
05-21 14:34:35.835: E/AndroidRuntime(223): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
05-21 14:34:35.835: E/AndroidRuntime(223): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
05-21 14:34:35.835: E/AndroidRuntime(223): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
05-21 14:34:35.835: E/AndroidRuntime(223): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:884)
05-21 14:34:35.835: E/AndroidRuntime(223): at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1659)
05-21 14:34:35.835: E/AndroidRuntime(223): at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1107)
05-21 14:34:35.835: E/AndroidRuntime(223): at android.app.Activity.dispatchTouchEvent(Activity.java:2061)
05-21 14:34:35.835: E/AndroidRuntime(223): at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1643)
05-21 14:34:35.835: E/AndroidRuntime(223): at android.view.ViewRoot.handleMessage(ViewRoot.java:1691)
05-21 14:34:35.835: E/AndroidRuntime(223): at android.os.Handler.dispatchMessage(Handler.java:99)
05-21 14:34:35.835: E/AndroidRuntime(223): at android.os.Looper.loop(Looper.java:123)
05-21 14:34:35.835: E/AndroidRuntime(223): at android.app.ActivityThread.main(ActivityThread.java:4363)
05-21 14:34:35.835: E/AndroidRuntime(223): at java.lang.reflect.Method.invokeNative(Native Method)
05-21 14:34:35.835: E/AndroidRuntime(223): at java.lang.reflect.Method.invoke(Method.java:521)
05-21 14:34:35.835: E/AndroidRuntime(223): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
05-21 14:34:35.835: E/AndroidRuntime(223): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
05-21 14:34:35.835: E/AndroidRuntime(223): at dalvik.system.NativeStart.main(Native Method)
05-21 14:34:35.835: E/AndroidRuntime(223): Caused by: java.lang.NoSuchMethodException: btn_valider
05-21 14:34:35.835: E/AndroidRuntime(223): at java.lang.ClassCache.findMethodByName(ClassCache.java:308)
05-21 14:34:35.835: E/AndroidRuntime(223): at java.lang.Class.getMethod(Class.java:1014)
05-21 14:34:35.835: E/AndroidRuntime(223): at android.view.View$1.onClick(View.java:2017)
05-21 14:34:35.835: E/AndroidRuntime(223): ... 23 more
05-21 14:34:35.875: I/dalvikvm(223): threadid=7: reacting to signal 3
05-21 14:34:35.895: I/dalvikvm(223): Wrote stack trace to '/data/anr/traces.txt'
05-21 14:34:39.275: I/Process(223): Sending signal. PID: 223 SIG: 9
05-21 14:34:39.924: D/dalvikvm(232): GC freed 542 objects / 47816 bytes in 84ms
05-21 14:35:15.314: W/ActivityThread(254): Application tn.pack.ordre is waiting for the debugger on port 8100...
05-21 14:35:15.326: I/System.out(254): Sending WAIT chunk
05-21 14:35:15.878: I/dalvikvm(254): Debugger is active
05-21 14:35:16.005: I/System.out(254): Debugger has connected
05-21 14:35:16.005: I/System.out(254): waiting for debugger to settle...
05-21 14:35:16.215: I/System.out(254): waiting for debugger to settle...
05-21 14:35:16.443: I/System.out(254): waiting for debugger to settle...
05-21 14:35:16.645: I/System.out(254): waiting for debugger to settle...
05-21 14:35:16.866: I/System.out(254): waiting for debugger to settle...
05-21 14:35:17.126: I/System.out(254): waiting for debugger to settle...
05-21 14:35:17.348: I/System.out(254): waiting for debugger to settle...
05-21 14:35:17.585: I/System.out(254): waiting for debugger to settle...
05-21 14:35:17.829: I/System.out(254): waiting for debugger to settle...
05-21 14:35:18.077: I/System.out(254): waiting for debugger to settle...
05-21 14:35:18.300: I/System.out(254): waiting for debugger to settle...
05-21 14:35:18.511: I/System.out(254): waiting for debugger to settle...
05-21 14:35:18.721: I/System.out(254): waiting for debugger to settle...
05-21 14:35:18.930: I/System.out(254): waiting for debugger to settle...
05-21 14:35:19.159: I/System.out(254): waiting for debugger to settle...
05-21 14:35:19.366: I/System.out(254): waiting for debugger to settle...
05-21 14:35:19.576: I/System.out(254): waiting for debugger to settle...
05-21 14:35:19.795: I/System.out(254): debugger has settled (1483)




No comments:

Post a Comment