FATAL EXCEPTION: AsyncTask #1, android remote database registration - java

I've been trying to build a registration system for android using php and mysql but i have come across an error that i am unable to fix. Could someone have a look at it and see if they spot anything that i don't please.
register code:
public class RegisterActivity extends Activity implements OnClickListener {
private EditText user, pass;
private Button mRegister;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "http://95.85.22.140/webservice/register.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
user = (EditText)findViewById(R.id.registerUsername);
pass = (EditText)findViewById(R.id.registerPassword);
mRegister = (Button)findViewById(R.id.btnRegisterDetails);
mRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new CreateUser().execute();
}
class CreateUser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(RegisterActivity.this);
pDialog.setMessage("Creating User...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST", params);
// full json response
Log.d("Login attempt", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("User Created!", json.toString());
finish();
return json.getString(TAG_MESSAGE);
}else{
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(RegisterActivity.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
register.php
<?php
require("config.inc.php");
// If posted data is not empty
if(!empty($_POST))
{
// If the username or password submition is empty
if(empty($_POST['username']) || empty($_POST['password']))
{
// Create a JSON response
$response["success"] = 0;
$response["message"] = "Please enter a username and a password.";
die(json_encode($response));
}
// Check to see if there is already a user with the username
$query = "SELECT 1 FROM registration WHERE username = :user";
// update the empty :user variable
$query_params = array(':user' => $_POST['username']);
// run query against database
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex)
{
$response["success"] = 0;
$response["message"] = "Database Error1. Please Try Again!";
die(json_encode($response));
}
//return username data if already in use
$row = $stmt->fetch();
if($row)
{
$response["success"] = 0;
$response["message"] = "I'm sorry, this username is already in use";
die(json_encode($response));
}
// Query to create a user
$query = "INSERT INTO registration (username, password) VALUES (:user, :pass)";
// Update variables with actual data
$query_params = array(':user' => $_POST['username'], ':pass' => $_POST['password']);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
$response["success"] = 0;
$response["message"] = "Database Errror2. Please Try Again!";
die(json_encode($response));
}
// By this point, user has been added
$response["success"] = 1;
$response["message"] = "User Successfully Added!";
echo json_encode($response);
}
else{
?>
<h1>Register</h1>
<form action="register.php" method="post">
Username:<br />
<input type = "text" name="username" value ="" />
<br /><br />
Password:<br />
<input type="password" name="password" value="" />
<br /><br />
<input type="submit" value="Register New User" />
</form>
<?php
}
?>
logcat error:
04-05 13:35:53.441: W/dalvikvm(8373): threadid=11: thread exiting with uncaught exception (group=0x418b3898)
04-05 13:35:53.471: E/AndroidRuntime(8373): FATAL EXCEPTION: AsyncTask #1
04-05 13:35:53.471: E/AndroidRuntime(8373): java.lang.RuntimeException: An error occured while executing doInBackground()
04-05 13:35:53.471: E/AndroidRuntime(8373): at android.os.AsyncTask$3.done(AsyncTask.java:299)
Any help would be great thanks

I too had similar issue and i solved by changing it's onPostExecute method. just give a try to below code.
protected void onPostExecute(String file_url) {
if (pDialog != null) {
if (pDialog.isShowing()) {
pDialog.dismiss();
}
}
}

Related

java.lang.String cannot be converted to JSONObject in Android Login&Register

I have a problem creating a login and registration in java. I am able to create a user however it returns error. It returns JSON + Error.
This is the JSON and error when I try to log in:
D/RegisterActivity: Login Response: login.php
DB_Connect.php
Config.php
{"error":false,"uid":"592da509e15a88.38765516","user":{"name":"P","email":"p","created_at":"2017-05-30 17:59:53"}}
W/System.err: org.json.JSONException: Value login.php of type java.lang.String cannot be converted to JSONObject
W/System.err:at activity.LoginActivity$3.onResponse(LoginActivity.java:125)
W/System.err:at activity.LoginActivity$3.onResponse(LoginActivity.java:117)
This is the login.java
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());
// Session manager
session = new SessionManager(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(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>() {
#Override
public void onResponse(String response) {
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(), Toast.LENGTH_LONG).show();
}
}
}, 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();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
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();
}}
login.php code:
<?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"];
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);
}
?>
I have spend hours on this could anyone point me in the right direction ? Thank you
Login Response: login.php DB_Connect.php Config.php
{"error":false,"uid":"592da509e15a88.38765516","user":{"name‌​":"P","email":"p","c‌​reated_at":"2017-05-‌​30 17:59:53"}}
As per your attached response message, it seems totally wrong.
Your response is not an JSON formatted string that's why its unable to create JSONObject from this response string.
Make sure your response contains only JSONObject:
{"error":false,"uid":"592da509e15a88.38765516","user":{"name‌​":"P","email":"p","c‌​reated_at":"2017-05-‌​30 17:59:53"}}
Remove unnecessary string "login.php DB_Connect.php Config.php" from response message. Check your server side code, why its adding string "login.php DB_Connect.php Config.php" with JSONObject.
I think this will solve your problem.

Error loading a JSON object

in local when i click on button "LOGIN" i have this exception?
> W/System.err: org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
Here is my code;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
DBConnect.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;
}
}
DBFunction.php:
class DB_Functions {
private $conn;
// constructor
function __construct() {
require_once 'DB_Connect.php';
// connecting to database
$db = new Db_Connect();
$this->conn = $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
$stmt = $this->conn->prepare("INSERT INTO users(unique_id, name, email, encrypted_password, salt, created_at) VALUES(?, ?, ?, ?, ?, NOW())");
$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();
// verifying user password
$salt = $user['salt'];
$encrypted_password = $user['encrypted_password'];
$hash = $this->checkhashSSHA($salt, $password);
// check for password equality
if ($encrypted_password == $hash) {
// user authentication details are correct
return $user;
}
} else {
return NULL;
}
}
/**
* Check user is existed or not
*/
public function isUserExisted($email) {
$stmt = $this->conn->prepare("SELECT email from users WHERE email = ?");
$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;
}
}
REGISTER ACTIVITY.java:
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) {
String name = inputFullName.getText().toString().trim();
String email = inputEmail.getText().toString().trim();
String password = inputPassword.getText().toString().trim();
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");
String email = user.getString("email");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUser(name, email, uid, created_at);
Toast.makeText(getApplicationContext(), "User successfully registered. Try login now!", Toast.LENGTH_LONG).show();
// 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() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
LOGIN ACTIVITY.java:
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());
// Session manager
session = new SessionManager(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(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>() {
#Override
public void onResponse(String response) {
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(), Toast.LENGTH_LONG).show();
}
}
}, 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();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
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();
}
}
And here is AppConfig.java
public class AppConfig {
// Server user login url
// public static String URL_LOGIN = "http://192.168.0.102/android_login_api/login.php";
//public static String URL_LOGIN = "http://10.0.2.2:8888/android_login_api/login.php";
public static String URL_LOGIN = "http://10.0.2.2:8888/phpmyadmin/import.php#PMAURL-0:tbl_structure.php?db=android_api&table=users&server=1&target=&token=809562ca509cc18a182d0f6b0bef5485/login.php";
// Server user register url
//public static String URL_REGISTER = "http://10.0.2.2:8888/android_login_api/register.php";
public static String URL_REGISTER = "http://10.0.2.2:8888/phpmyadmin/import.php#PMAURL-0:tbl_structure.php?db=android_api&table=users&server=1&target=&token=809562ca509cc18a182d0f6b0bef5485/register.php";
}
register.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);
}
LOGIN.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);
}
LOGCAT:
07-13 19:55:24.137 11917-11917/ W/System.err: org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
07-13 19:55:24.137 11917-11917/ W/System.err: at org.json.JSON.typeMismatch(JSON.java:111)
07-13 19:55:24.137 11917-11917/ W/System.err: at org.json.JSONObject.<init>(JSONObject.java:158)
07-13 19:55:24.137 11917-11917/ W/System.err: at org.json.JSONObject.<init>(JSONObject.java:171)
07-13 19:55:24.137 11917-11917/ W/System.err: at info.androidhive.loginandregistration.activity.RegisterActivity$3.onResponse(RegisterActivity.java:127)
07-13 19:55:24.137 11917-11917/ W/System.err: at info.androidhive.loginandregistration.activity.RegisterActivity$3.onResponse(RegisterActivity.java:119)
07-13 19:55:24.137 11917-11917/ W/System.err: at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
07-13 19:55:24.137 11917-11917/ W/System.err: at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
07-13 19:55:24.137 11917-11917/ W/System.err: at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
07-13 19:55:24.137 11917-11917/ W/System.err: at android.os.Handler.handleCallback(Handler.java:605)
07-13 19:55:24.137 11917-11917/ W/System.err: at android.os.Handler.dispatchMessage(Handler.java:92)
07-13 19:55:24.137 11917-11917/ W/System.err: at android.os.Looper.loop(Looper.java:137)
07-13 19:55:24.137 11917-11917/ W/System.err: at android.app.ActivityThread.main(ActivityThread.java:4424)
07-13 19:55:24.137 11917-11917/W/System.err: at java.lang.reflect.Method.invokeNative(Native Method)
07-13 19:55:24.137 11917-11917/ W/System.err: at java.lang.reflect.Method.invoke(Method.java:511)
07-13 19:55:24.137 11917-11917/ W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
07-13 19:55:24.137 11917-11917/ W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
07-13 19:55:24.137 11917-11917/ W/System.err: at dalvik.system.NativeStart.main(Native Method)
json_encode() your output then try to parse it. It will solve your issue.
I had faced same situation and i created module for it.I am attaching a sample code how to retrive json object from php to android .
your php code must be :-
<?php
// Include Database handler
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
$class_id="2";
function getClassById($class_id) {
$ss="SELECT * FROM student WHERE class_id = '$class_id'";
$result = mysql_query($ss) or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
$result = mysql_fetch_array($result);
return $result;
}
else {
// user not found
return false;
}
}
$user =getClassById($class_id);
if ($user != false) {
$response["success"] = 1;
$response["user"]["class_id"] = $user["class_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["enrolment"] = $user["enrolment"];
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);
}
?>
Now your code can be anything which you want but it must have json_encode() for getting json object in android.
Now your android coding must be like .
public class UserFunctions {
private JSONParser jsonParser;
private static final String TAG_RESULTS="result";
private static final String TAG_ID = "id";
private static final String TAG_YEAR = "yearof";
private static final String TAG_BRANCH ="branchof";
private static final String TAG_SECTION ="sectionof";
private static final String TAG_ClassKey ="classkey";
private static final String TAG_cordinator ="coordinatoremail";
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
//URL of the PHP API
private static String GetbunkstudentURL = "http://169.254.90.189/learn2crack_login_api/getabsentstudent/getabsentstudent.php";
private static String bunk_tag = "bunk";
private static String register_tag = "register"; // constructor
public UserFunctions(){
jsonParser = new JSONParser();
}
public JSONObject getBunkStudent(String lecture1, String lecture2) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", bunk_tag));
params.add(new BasicNameValuePair("lec1", lecture1));
params.add(new BasicNameValuePair("lec2", lecture2));
JSONObject json = jsonParser.getJSONFromUrl(GetbunkstudentURL, params);
return json;
}
}
Now your jsonparser.java class must be like:-
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;
}
}
code to call those function in activity or in fragment is here,
public class seeBunkedStudentFragment extends ListFragment {
String myJSON;
private static final String KEY_STUDENT="student";
private static final String TAG_RESULTS="result";
private static final String TAG_ID = "id";
private static final String TAG_ClassDet = "classdetails";
private static final String TAG_YEAR = "yearof";
private static final String TAG_BRANCH ="branchof";
private static String KEY_SUCCESS = "success";
private static String KEY_UID = "uid";
private static String KEY_USERNAME = "uname";
private static String KEY_FIRSTNAME = "fname";
private static String KEY_LASTNAME = "lname";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
private static final String TAG_SECTION ="sectionof";
//////tags
private static final String TAG_TID = "tid";
private static final String Tag_Classid="classid";
private static final String Tag_Classkey="classkey";
private static final String Tag_schedid="scheduleid";
////////
JSONArray peoples = null;
JSONArray contacts = null;
ArrayList<HashMap<String, String>> contactList;
public ArrayList<HashMap<String, String>> personList;
ListView list;
private HashMap<String, String> singleclass;
String userdetail[]=new String[5];
private String todayda;
private String result;
private String ccid,ssid;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v= inflater.inflate(R.layout.bunkstudentlist,null);
list = (ListView) v.findViewById(R.id.list);
NetAsync(v);
contactList = new ArrayList<HashMap<String, String>>();
personList = new ArrayList<HashMap<String,String>>();
return v;
}
private class NetCheck extends AsyncTask<String,String,Boolean>
{
private ProgressDialog nDialog;
#Override
protected void onPreExecute(){
super.onPreExecute();
nDialog = new ProgressDialog(getActivity());
nDialog.setTitle("Checking Network");
nDialog.setMessage("Loading..");
nDialog.setIndeterminate(false);
nDialog.setCancelable(true);
nDialog.show();
}
#Override
protected Boolean doInBackground(String... args){
/**
* Gets current device state and checks for working internet connection by trying Google.
**/
/*
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}*/
// return false;
return true;
}
#TargetApi(Build.VERSION_CODES.CUPCAKE)
#Override
protected void onPostExecute(Boolean th){
if(th == true){
nDialog.dismiss();
new ProcessLogin().execute();
}
else{
nDialog.dismiss();
Toast.makeText(getActivity().getApplicationContext(), "Error in Network Connection", Toast.LENGTH_LONG).show();
}
}
}
private class ProcessLogin extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
String uniq;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setTitle("Contacting Servers");
pDialog.setMessage("Logging in ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
String lecture1="1";
String lecture2="2";
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.getBunkStudent(lecture1,lecture2);
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = null;
try {
res = json.getString(KEY_SUCCESS);
} catch (JSONException e1) {
e1.printStackTrace();
}
res= json.getString("success");
JSONArray json_user = json.getJSONArray("user");
int llenggt=json_user.length();
if(Integer.parseInt(res) == 1){
for (int i = 0; i < json_user.length(); i++) {
JSONObject c = json_user.getJSONObject(i);
String tid = c.getString("teacherid");
String classid= c.getString("enrollmentnumber");
String classkey= c.getString("classid");
Log.d("firstjson",tid+""+classid+""+classkey);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
//TAG_TID, Tag_Classid, Tag_Classkey // adding each child node to HashMap key => value
contact.put(TAG_TID, tid);
contact.put(Tag_Classid, classid);
contact.put(Tag_Classkey, classkey);
// adding contact to contact list
contactList.add(contact);
}
}
}
} catch (JSONException e1) {
e1.printStackTrace();
}
////
myJSON=result;
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
if (pDialog.isShowing())
pDialog.dismiss();
ListAdapter adapter = new SimpleAdapter(
getActivity(), contactList,
R.layout.item_fetch_lec2, new String[]{TAG_TID, Tag_Classid,
Tag_Classkey}, new int[]{R.id.name,
R.id.email, R.id.mobile});
setListAdapter(adapter);
}
}
public void NetAsync(View view){
new NetCheck().execute();
}
//////code for othere async task
}
i think it will help , you just take reference from these code it will help .
Add this code before the line of your JSONObject,
Log.i("tagconvertstr", "["+response+"]");
Then you can know what's your error.
And don't forget to call your AppController class in Manifest.xml

AsyncTask not completing as expected [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I have a CreateUser class which creates a user. This worked correctly until I tried to add a new field for a password check.
In the task I'm checking to see if the password fields match and if they dont I cancel the execution and move to a toast.
It correctly checks the passwords and toasts when incorrect but if they match it still cancels execution and never completes creating a new user.
CODE:
public class Register extends Activity implements OnClickListener{
private EditText user, pass, confirmPass;
private Button mRegister;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "https://xxx.xxx.xxx.xxx/xxx.php";
//ids
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
user = (EditText)findViewById(R.id.username);
pass = (EditText)findViewById(R.id.password);
confirmPass = (EditText)findViewById(R.id.passwordConfirm);
mRegister = (Button)findViewById(R.id.register);
mRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
new CreateUser().execute();
}
class CreateUser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Register.this);
pDialog.setMessage("Creating User...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
String passwordCheck = confirmPass.getText().toString();
try {
//-----------------------------------------------------------------------------Password Check
if (password != passwordCheck) {
cancel(true);
}
if (!this.isCancelled()) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// full json response
Log.d("Login attempt", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("User Created!", json.toString());
finish();
return json.getString(TAG_MESSAGE);
} else {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
}
}catch(JSONException e){
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(Register.this, file_url, Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCancelled() {
pDialog.dismiss();
Toast.makeText(Register.this, "Passwords do not match", Toast.LENGTH_SHORT).show();
}
}}
In your doInBackground, you're comparing 2 strings using != this will only compare the memory addresses of the strings and therefore will evaluate to false even if the value of the two strings is the same. Change it to equals()

Error parsing JSON after updating php file. Works before PDO, now JSON parsing error

Through chrome i can log in using a member from the database (MySQL), and i can make a new user. When i use the app, i can make a new user but the app crashes.
Using simple php (below) i get a proper response, and the new activity is launched. The problem here is both correct and incorrect credentials work.
<?php
$response = array();
if (isset($_POST['username'], $_POST['password'])) {
$response["success"] = 1;
$response["message"] = "User Name and password are set";
} else {
$response["success"] = 0;
$response["message"] = "User Name and password not set";
}
echo json_encode($response);
The following is my login.java file:
package com.amity.paul.amity;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import library.JSONParser;
public class login extends Activity implements OnClickListener{
private EditText user, pass;
private Button mSubmit, mRegister;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
//php login script location:
//localhost :
//testing on your device
//put your local ip instead, on windows, run CMD > ipconfig
//or in mac's terminal type ifconfig and look for the ip under en0 or en1
// private static final String LOGIN_URL = "http://xxx.xxx.x.x:1234/webservice/login.php";
//testing on Emulator:
private static final String LOGIN_URL = "http://10.0.2.2/amity/login.php";
//testing from a real server:
//private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/login.php";
//JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
//setup input fields
user = (EditText)findViewById(R.id.username);
pass = (EditText)findViewById(R.id.password);
//setup buttons
mSubmit = (Button)findViewById(R.id.login);
mRegister = (Button)findViewById(R.id.register);
//register listeners
mSubmit.setOnClickListener(this);
mRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.login:
new AttemptLogin().execute();
break;
case R.id.register:
Intent i = new Intent(this, register.class);
startActivity(i);
break;
default:
break;
}
}
class AttemptLogin extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(login.this);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
//save user data
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(login.this);
SharedPreferences.Editor edit = sp.edit();
edit.putString("username",username);
edit.commit();
Intent i = new Intent(login.this, home.class);
finish();
startActivity(i);
return json.getString(TAG_MESSAGE);
}else{
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(login.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
I then changed the php to be more advanced, as below:
<?php
$response = array();
if (isset($_POST['username'], $_POST['password'])) {
require("config.inc.php");
try {
$query = "
SELECT
id,
username,
password
FROM users
WHERE
username = :username
AND password = :password
";
$stmt = $db->prepare($query);
$result = $stmt->execute(array(':username' => $_POST['username'],
':password' => $_POST['password']
));
if($stmt->rowCount() == 1){
$response["success"] = true;
$response["message"] = "user found";
}else{
$response["success"] = false;
$response["message"] = "user not found";
}
}
catch (PDOException $ex) {
$response["success"] = false;
$response["message"] = "Database Error1. Please Try Again!";
}
} else {
$response["success"] = false;
$response["message"] = "User Name and password not set";
}
echo json_encode($response);
Problem now is parsing error. Logcat:
08-16 15:39:40.620 841-856/com.amity.paul.amity E/JSON Parser﹕ Error parsing data org.json.JSONException: Value of type java.lang.String cannot be converted to JSONObject
08-16 15:39:40.630 841-856/com.amity.paul.amity W/dalvikvm﹕ threadid=11: thread exiting with uncaught exception (group=0xb3a21ba8)
08-16 15:39:40.670 841-856/com.amity.paul.amity E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.amity.paul.amity, PID: 841
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NullPointerException
at com.amity.paul.amity.login$AttemptLogin.doInBackground(login.java:117)
at com.amity.paul.amity.login$AttemptLogin.doInBackground(login.java:97)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Please make the solution 'noob friendly' as I am new to android app development. Thanks!
Edit:
I fixed the issue using the following php:
<?php
$response = array();
if (isset($_POST['username'], $_POST['password'])) {
require("config.inc.php");
try {
$query = "
SELECT
id,
username,
password
FROM users
WHERE
username = :username
AND password = :password
";
$stmt = $db->prepare($query);
$result = $stmt->execute(array(':username' => $_POST['username'],
':password' => $_POST['password']
));
if($stmt->rowCount() == 1){
$response["success"] = true;
$response["message"] = "user found";
}else{
$response["success"] = false;
$response["message"] = "user not found";
}
}
catch (PDOException $ex) {
$response["success"] = false;
$response["message"] = "Database Error1. Please Try Again!";
}
} else {
$response["success"] = false;
$response["message"] = "User Name and password not set";
}
echo json_encode($response);
One last issue, in logcat, it will tell me if success = true / false. How can i make a message appear to say incorrect credentials, and if the right combo is entered, to launch the new activity?
You should remove the ':' char in the array you're pasing to prepare():
$result = $stmt->execute(array('username' => $_POST['username'],
'password' => $_POST['password']
Because otherwise PDO would return an empty response or worse, a "Warning" or "Error" php statement that will add up before the JSON you're generating at the end, and thus generate a parsing exception. Your php response would look like:
Error in line BLA BLA BLA ...
["success": "false", "message":"blablabla"]
Which you would unable to parse with your Java app.
So it's not actually an issue in your Android code!
The ':' in the request means "check in the given array the value after ':'".
Assuming that the second php code is for login, I didn't use isset function before but you can use this code. It's really straightforward.
if (!empty($_POST)) {
//gets user's info based off of a username.
$query = "
SELECT
username,
password
FROM login
WHERE
username = :username
";
$query_params = array(
':username' => $_POST['username']
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one to product JSON data:
$response->{"success"} = 0;
$response->{"message"} = "Database Error";
die(json_encode($response));
}
//This will be the variable to determine whether or not the user's information is correct.
//we initialize it as false.
$validated_info = false;
//fetching all the rows from the query
$row = $stmt->fetch();
$login_ok = false;
if ($row) {
//if we encrypted the password, we would unencrypt it here, but in our case we just
//compare the two passwords
if ($_POST['password'] === $row['password']) {
$login_ok = true;
}
}
// If the user logged in successfully, then we send them to the private members-only page
// Otherwise, we display a login failed message and show the login form again
if ($login_ok) {
$response->{"success"} = 1;
$response->{"message"} = "Login Succesfull";
die(json_encode($response));
} else {
$response->{"success"} = 0;
$response->{"message"} = "Wrong Password";
die(json_encode($response));
}
}

Android Json value not returning

I am developing an Android app in which I am using JSon to get values from databas. In database there is particular text for each string A-Z. and when a string is returned from A-Z the corresponding result has to be displayed... I am giving the code for that.. but the problem result is not displayin.. I used PHP code for connceting..
PHP
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for post data
if (isset($_GET["costone"]))
{
$costone = $_GET['costone'];
// get a product from products table
$result = mysql_query("SELECT *FROM sletter WHERE costone = $costone");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$product = array();
$product["pid"] = $result["pid"];
$product["costone"] = $result["costone"];
$product["custone"] = $result["custone"];
$product["fvowel"] = $result["fvowel"];
$product["cornerstone"] = $result["cornerstone"];
$product["cupstone"] = $result["cupstone"];
$product["firstvowel"] = $result["firstvowel"];
$product["created_at"] = $result["created_at"];
$product["updated_at"] = $result["updated_at"];
// success
$response["success"] = 1;
// user node
$response["product"] = array();
array_push($response["product"], $product);
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
Activity
String custone, costone;
TextView txtName9, txtNzme10;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String url_cup_stone = "http://iascpl.com/app/get_cup_stone.php";
private static final String url_first_vowel = "http://iascpl.com/app/get_first_vowel.php";
private static final String TAG_CUPSTONE = "cupstone";
private static final String TAG_FIRSTVOWEL = "firstvowel";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fullexplanation_xm);
txt27.setText(getIntent().getStringExtra("aChar"));
TextView txt28 = (TextView) findViewById(R.id.textView51);
txt28.setText(getIntent().getStringExtra("aChar1"));
costone = txt27.getText().toString();
custone = txt28.getText().toString();
/**
* Background Async Task to Get complete product details
* */
class GetProductDetails extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(FullExplanation.this);
pDialog.setMessage("Loading the result... Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting product details in background thread
* */
protected String doInBackground(String... args)
{
TextView txt27 = (TextView) findViewById(R.id.textView48);
TextView txt28 = (TextView) findViewById(R.id.textView51);
costone = txt27.getText().toString();
custone = txt28.getText().toString();
params.add(new BasicNameValuePair("costone", costone));
params.add(new BasicNameValuePair("custone", custone));
JSONObject json9 = jsonParser.makeHttpRequest(
url_corner_stone, "GET", params);
JSONObject json10 = jsonParser.makeHttpRequest(
url_cup_stone, "GET", params);
int success9 = json9.getInt(TAG_SUCCESS);
int success10 = json10.getInt(TAG_SUCCESS);
if (success9 == 1) {
// successfully received product details
JSONArray productObj = json9
.getJSONArray(TAG_PRODUCT); // JSON Array
// get first product object from JSON Array
final JSONObject product = productObj.getJSONObject(0);
// product with this pid found
// Edit Text
txtName9 = (TextView) findViewById(R.id.textView49);
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
txtName9.setText(product.getString(TAG_CORNERSTONE));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
} else {
// product with pid not found
}
if (success10 == 1) {
// successfully received product details
JSONArray productObj = json10
.getJSONArray(TAG_PRODUCT); // JSON Array
// get first product object from JSON Array
final JSONObject product = productObj.getJSONObject(0);
// product with this pid found
// Edit Text
txtName10 = (TextView) findViewById(R.id.textView52);
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
txtName10.setText(product.getString(TAG_CUPSTONE));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
} else {
// product with pid not found
}
}
catch(
JSONException e
)
{
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
pDialog.dismiss();
}
}

Categories