我正在Android应用程序中实现基本注册系统,该应用程序通过wampserver和PHP API连接到SQL DATABASE ...每次执行注册过程时,用户都会保存在数据库中,但是当我尝试获取进程的JSON响应,它将注册的用户信息存储在与我的应用程序关联的SQLite数据库中...我得到的错误声明:string无法转换为json对象。
这是android端,我调用PHP代码来执行注册并接收json响应。
private void registerUser(final String name, final String email,
final String password, final String latitude,
final String longitude, final String userType) {
// 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) {
hideDialog();
try {
Log.i("tagconvertstr", "[" + response.toString()
+ "]");
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 latitude = user.getString("latitude");
String longitude = user.getString("longitude");
String userType = user.getString("userType");
String service = user.getString("service");
String rate = user.getString("rate");
String rated_clients = user
.getString("rated_clients");
String servicesTag = user
.getString("servicesTag");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUser(name, email, latitude, longitude,
userType, service, rate, rated_clients,
servicesTag, uid, created_at);
Toast.makeText(
getApplicationContext(),
"User successfully registered. Try login now!",
Toast.LENGTH_LONG).show();
// Launch login activity
checkLogin(email, password);
} else {
Log.d("heeeeeeeeeeeeeeeey", "error here");
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("error_msg");
toast.makeDialog("Error in registering "
+ errorMsg + "kk",
getApplicationContext());
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
loginLayout.setVisibility(View.GONE);
registerLayout.setVisibility(View.GONE);
noConnectionLayout.setVisibility(View.VISIBLE);
tag = "register";
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);
params.put("latitude", latitude);
params.put("longitude", longitude);
params.put("userType", userType);
return params;
}
};
strReq.setRetryPolicy(new DefaultRetryPolicy(0,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
我在该行收到错误:JSONObject jObj = new JSONObject(response);
这是注册过程的PHP代码:
<?php
ini_set ( 'display_errors', 'On' );
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'] ) && isset ( $_POST ['latitude'] ) && isset ( $_POST ['longitude'] ) && isset ( $_POST ['userType'] )) {
// receiving the post params
$name = $_POST ['name'];
$email = $_POST ['email'];
$password = $_POST ['password'];
$latitude = $_POST ['latitude'];
$longitude = $_POST ['longitude'];
$userType = $_POST ['userType'];
// 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, $latitude, $longitude, $userType );
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"] ["latitude"] = $user ["latitude"];
$response ["user"] ["longitude"] = $user ["longitude"];
$response ["user"] ["userType"] = $user ["userType"];
$response ["user"] ["service"] = $user ["service"];
$response ["user"] ["rate"] = $user ["rate"];
$response ["user"] ["rated_clients"] = $user ["rated_clients"];
$response ["user"] ["servicesTag"] = $user ["servicesTag"];
$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 );
}
?>
这是isUserExicted和storeUser函数:
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;
}
}
public function storeUser($name, $email, $password, $latitude, $longitude, $userType) {
$uuid = uniqid ( '', true );
$hash = $this->hashSSHA ( $password );
$encrypted_password = $hash ["encrypted"]; // encrypted password
$salt = $hash ["salt"]; // salt
$service = "none";
$rate = "none";
$rated_clients = "none";
$servicesTag = "none";
$stmt = $this->conn->prepare ( "INSERT INTO users(unique_id, name, email, encrypted_password, latitude, longitude, userType, salt, service, rate, rated_clients, servicesTag, created_at) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())" );
$stmt->bind_param ( "ssssssssssss", $uuid, $name, $email, $encrypted_password, $latitude, $longitude, $userType, $salt, $service, $rate, $rated_clients, $servicesTag );
$result = $stmt->execute ();
$stmt->close ();
var_dump ( $result );
// 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 ();
var_dump ( $user );
echo '</pre>';
return $user;
} else {
return null;
}
}
这是响应值:
注意:保证在storeUser方法中绑定到查询的列将在数据库中创建。
答案 0 :(得分:0)
您从服务器获得的json无效,您可以通过在以下网站上运行来检查json的有效性:
http://www.jsoneditoronline.org/
问题可能是由于某些服务器错误造成的,或者您在生成的json之前回显了其他一些输出,这些是在乞讨时的html标记。我建议关闭错误,请点击此处了解更多信息:Turn Off Display Error PHP.ini
你可以使用.htaccess文件,例如:
Options -Indexes
# suppress PHP errors from displaying in the browser
php_flag display_startup_errors off
php_flag display_errors off
php_flag html_errors off
# log PHP errors to a file
php_flag log_errors on
php_value error_reporting 32767
php_value error_log "./error_log.txt"
您的php通常应采用以下简化形式:
<?php
header('Content-type: application/json');
$json = file_get_contents('php://input'); // input json
// ...
$js_result = json_encode(array("error" => "unknown_action")); // result
echo $js_result;