排球响应返回空值

时间:2017-10-08 10:22:51

标签: php android android-volley

我正在尝试创建一个简单的注册页面,将用户名,电子邮件和密码传递给php端。 我用RESTclient(postman)检查了我的PHP代码,它工作正常。但是当我尝试使用volley从android传递params时,onResponse中的响应返回null值。 这是代码:

Php:

DbOperations.php

<?php
class DbOperations{     
    private $con;
    require_once dirname(__FILE__).'/DbConnect.php';
    $db = new DbConnect();
    $this->con = $db->connect();
}   
function createUser($username,$pass,$email){
    $password = md5($pass);
    $stmt = $this->con->prepare("INSERT INTO `android`.`users` (`id`, `username`, `password`, `email`) VALUES (NULL, ?, ?, ?);");
    $stmt->bind_param("sss",$username,$password,$email);            
    if($stmt->execute()){
        return true;
        }else{
            return false;
        }
    }   
}

registerUser.php

<?php

    if      
    (isset($_POST['username']) and
        isset($_POST['password']) and 
        isset($_POST['email'])
        ){
            $db = new DbOperations();       
            if($db->createUser(
                $_POST['username'],
                $_POST['password'],
                $_POST['email']
            )){
                $response['error'] = "false"; $response['message'] = "user register success";
            }else{
                $response['error'] = "true";
                $response['message'] = "user register failed";
            }
    }else{
        $response['error'] = true;
        $response['message'] = "Required fields are missing";
    }
}else{
    $response['error'] = true;
    $response['message'] = "invalid post request";
}
echo json_encode($response);

机器人:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

private EditText etUsername,etEmail,etPassword;
private Button bt;
private ProgressDialog progressDialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    etEmail=(EditText)findViewById(R.id.et_email);
    etUsername=(EditText)findViewById(R.id.et_username);
    etPassword=(EditText)findViewById(R.id.et_pasword);

    bt=(Button)findViewById(R.id.bt);

    progressDialog =new ProgressDialog(this);

    bt.setOnClickListener(this);

}


private void registerUser(){
        final String email=etEmail.getText().toString().trim();
        final String username=etUsername.getText().toString().trim();
        final String password=etPassword.getText().toString().trim();

    progressDialog.setMessage("Registering..");
    progressDialog.show();
    StringRequest stringRequest = new StringRequest(Request.Method.POST,
            Constants.URL_REGISTER,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    progressDialog.dismiss();

                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        Toast.makeText(getApplicationContext(),jsonObject.getString("message"),Toast.LENGTH_LONG).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    progressDialog.hide();
                    Toast.makeText(getApplicationContext(),error.getMessage(),Toast.LENGTH_LONG).show();
                }
            }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String,String> params=new HashMap<>();
            params.put("username",username);
            params.put("email",email);
            params.put("password",password);

            return params;
        }
    };

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);

}

@Override
public void onClick(View v) {
    if (v==bt)
        registerUser();
}

}

2 个答案:

答案 0 :(得分:0)

 try {
                    JSONObject jsonObject = new JSONObject(response);
                    Toast.makeText(getApplicationContext(),jsonObject.getString("message"),Toast.LENGTH_LONG).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

首先你应该检查一下反应。 你能分享一下php的代码吗? 在注册用户名等注册文件后,你应该在那里打印一些回复,这样你就可以在volley中得到那个回应

$ sql =“INSERT INTO table_name(username,password,email)VALUES('$ username','$ password','$ email')”;

    if(mysqli_query($con,$sql)){

        echo 'successfully registered';

}

更改此代码后检查响应,然后您将成功注册,以便在java比较响应中然后吐司

答案 1 :(得分:0)

不确定您是否已经这样做,只需尝试以下

尝试首先定义一个空数组,如下所示:

$response = array(); <--add this line,create an empty array 1st..then only can echo out

 if      
    (isset($_POST['username']) and
        isset($_POST['password']) and 
        isset($_POST['email'])
        ){
            $db = new DbOperations();       
            if($db->createUser(
                $_POST['username'],
                $_POST['password'],
                $_POST['email']
            )){
                $response['error'] = "false"; $response['message'] = "user register success";
            }else{
                $response['error'] = "true";
                $response['message'] = "user register failed";
            }
    }else{
        $response['error'] = true;
        $response['message'] = "Required fields are missing";
    }
}else{
    $response['error'] = true;
    $response['message'] = "invalid post request";
}
echo json_encode($response);