我正在为Android构建注册系统。我可以将数据添加到数据库,这很好。现在我想添加一些JSON,它将通知用户成功注册或不同的错误。即
{
"status":"success",
"message":"Successful Registration"
}
或
{
"status":"fail",
"message":"Please enter your name"
}
等
这是我的php脚本。
<?php
require "init.php";
$j = new stdClass();
$name = $_POST['name'];
$user_name = $_POST['user_name'];
$user_pass = md5(md5($_POST['user_name']).$_POST['user_pass']);
if(!$name){
json_encode(array('status' => 'fail', 'message' => 'Please enter your
name'));
}
$sql_query = "insert into user_info
values('$name','$user_name','$user_pass');";
if(mysqli_query($con,$sql_query)){
json_encode(array('status' => 'success', 'message' => 'Successfully
registered'));
}else{
json_encode(array('status' => 'fail', 'message' => 'Could not
register'));
}
?>
使用此脚本,即使我成功添加数据,也无法从我的Java代码中检测到任何JSON repsonse。
private void registerUser(final String name, final String userName,
final String password) {
// Tag used to cancel the request
String tag_string_req = "req_register";
StringRequest strReq = new StringRequest(Request.Method.POST,
"MY_LINK_GOES_HERE", new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("Response", "Register Response: " + response.toString());
Toast.makeText(getApplicationContext(), "User successfully registered. Try login now!", Toast.LENGTH_LONG).show();
// Launch login activity
Intent intent = new Intent(
Register.this,
MainActivity.class);
startActivity(intent);
finish();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("Error", "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
@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("user_name", userName);
params.put("user_pass", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
该行
Log.d("Response", "Register Response: " + response.toString());
什么也没给我。
有什么想法吗?
谢谢。
答案 0 :(得分:2)
首先,您应在问题中提及您使用的是android-volley
库,或者至少使用tag
。其次,如果您尝试解析JSON
响应,那么您应该使用JsonObjectRequest
实例来执行此操作。假设您的php
脚本发送了正确的JSON
,您可以尝试使用volley
这样简单直接的内容:
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
response = response.getJSONObject("args");
String site = response.getString("site"), network = response.getString("network");
View view = findViewById(R.id.activity_layout);
Snackbar.make(view, "Site : " + site + " Network : " + network, Snackbar.LENGTH_INDEFINITE).show();
} catch (JSONException e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getBaseContext(), "Error Listener", Toast.LENGTH_LONG).show();
}
});
Volley.newRequestQueue(this).add(jsonRequest);
这假设您的JSON
是这样的:
{
"args": {
"network": "somenetwork",
"site": "code"
},
"args2": {
...
},
"args3": "...",
"args4": "..."
}
现在,根据您发送的JSON
,您可以尝试任意组合。您还可以查看这个非常有用的tutorial。希望这可以帮助。如果您需要更多帮助,请告诉我。
答案 1 :(得分:1)
当我尝试进行注册时,我在我的应用程序中遇到了同样的问题。我想检查用户是否注册以及用户名是否可用。
所以我做的是:
PHP文件:
<?php
try {
$handler = new PDO('mysql:host=localhost;dbname=database', 'username', 'password');
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $e) {
echo $e->getMessage();
die();
}
$username = $_POST['username'];
$password=$_POST['password'];
$email = $_POST['email'];
$dateCreated = $_POST['dateCreated'];
$android_version= $_POST['android_version'];
$api_level = $_POST['api_level'];
$check = $handler->query("SELECT * FROM table WHERE username = '$username'");
$don = array();
if($check->rowCount() > 0){
$don = array('result' =>TRUE);
die();
}else{
$don = array('result' =>FALSE);
$handler->query("INSERT INTO table(id, username, password, email, dateCreated, activated, Android_Version, API_Level) VALUES('', '$username','$password','$email', '$dateCreated', 0, '$android_version', '$api_level')");
}
echo json_encode($don);
?>
机器人:
私有类MyInsertDataTask扩展了AsyncTask {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(YourActivity.this);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setIndeterminate(true);
pDialog.setMessage(getString(R.string.dialog_rate_data_submit));
pDialog.setCancelable(false);
pDialog.setInverseBackgroundForced(true);
pDialog.show();
}
@Override
protected Boolean doInBackground(String... params) {
nameValuePairs = new ArrayList<>();
nameValuePairs.add(new BasicNameValuePair("username", uName));
nameValuePairs.add(new BasicNameValuePair("password", pass));
nameValuePairs.add(new BasicNameValuePair("email", email));
nameValuePairs.add(new BasicNameValuePair("dateCreated", date));
nameValuePairs.add(new BasicNameValuePair("android_version", release));
nameValuePairs.add(new BasicNameValuePair("api_level", String.valueOf(sdkVersion)));
try
{
httpClient = new DefaultHttpClient();
httpPost = new HttpPost(AppConstant.REGISTER_URL);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpClient.execute(httpPost);
httpEntity = response.getEntity();
is = httpEntity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder result = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
result.append(line);
}
Log.e("Responce", result.toString());
if (result != null) {
data = new JSONObject(result.toString());
usernameExists = data.getBoolean("result");
}
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
}
return usernameExists;
}
@Override
protected void onPostExecute(Boolean aVoid) {
super.onPostExecute(aVoid);
pDialog.dismiss();
if (aVoid){
Snackbar.with(YourActivity.this).type(SnackbarType.MULTI_LINE).text(getString(R.string.username_exists_message)).color(Color.parseColor(AppConstant.ENABLED_BUTTON_COLOR)).show(getActivity());
}else {
Toast.makeText(YourActivity.this, getString(R.string.created_successfully), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(YourActivity.this, MainActivity.class);
startActivity(intent);
YourActivity.this.finish();
}
}
}
结果是,如果存在用户名,则会弹出一条消息,说明用户名已存在,否则用户注册
结果:
答案 2 :(得分:0)
我修好了!这是一个php问题。这是我的解决方案。
<?php
require "init.php";
header('Content-type: application/json');
$name = $_POST['name'];
$user_name = $_POST['user_name'];
$user_pass = md5(md5($_POST['user_name']).$_POST['user_pass']);
$sql_query = "select * from user_info WHERE user_name
='".mysqli_real_escape_string($con, $user_name)."'";
$result = mysqli_query($con, $sql_query);
$results = mysqli_num_rows($result);
if ($results){
$don = array('result' =>"fail","message"=>"Username exists. User
a different one");
}else{
$sql_query = "insert into user_info
values('$name','$user_name','$user_pass');";
if(mysqli_query($con,$sql_query)){
$don = array('result' =>"success","message"=>"Successfully
registered!Well done");
}
}
echo json_encode($don);
?>