我在Android中有一个注册页面,用户输入他/她的姓名,电子邮件,电话和密码。当我从应用程序注册任何新用户时,即使用户不存在,我得到的响应始终为E/Json response: {"success":false,"msg":"User already Exists"}
。但是当我通过Postman查询相同的查询时,我得到了正确的响应,如
{
"success": true,
"msg": "Confirmation Link to activate your account has been sent to your email address",
"data": {
"studentId": 8
}
}
如果我通过邮递员注册新用户我得到了正确的回复,但是从应用程序中它始终显示"用户已经存在"。
这是我的注册活动:
public class RegisterActivity extends AppCompatActivity implements ServerRequests.Registereponse {
private EditText password, phone, email;
public static EditText name;
ServerRequests serverRequests;
JSONParser jsonParser;
private Button registerButton;
TextView alreadyMember;
Editor editor;
UserSession session;
SharedPreferences sharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
jsonParser = new JSONParser();
serverRequests = new ServerRequests(getApplicationContext());
serverRequests.setRegistereponse(this);
alreadyMember = (TextView) findViewById(R.id.alreadyMember);
name = (EditText) findViewById(R.id.FName);
phone = (EditText) findViewById(R.id.PhoneNum);
email = (EditText) findViewById(R.id.mail);
password = (EditText) findViewById(R.id.password);
registerButton = (Button) findViewById(R.id.email_sign_in_button);
sharedPreferences = getApplicationContext().getSharedPreferences("Reg", 0);
editor = sharedPreferences.edit();
registerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
CharSequence temp_emailID = email.getText().toString();
if (name.getText().toString().length() == 0) {
name.setError("Please enter your name");
name.requestFocus();
} else if (phone.getText().toString().length() == 0) {
phone.setError("Please enter your phone number");
phone.requestFocus();
} else if (!isValidEmail(temp_emailID)) {
email.setError("Please enter valid email");
email.requestFocus();
} else if (password.getText().toString().length() == 0) {
password.setError("Please enter password");
password.requestFocus();
} else {
try {
String Name = name.getText().toString();
String Email = email.getText().toString();
String Password = password.getText().toString();
String Phone = phone.getText().toString();
JSONObject obj = jsonParser.makeRegisterJson(Name, Email, Password, Long.parseLong(Phone));
Log.e("final Json", obj.toString());
serverRequests.register(obj);
editor.putString("name", Name);
editor.putString("email", Email);
editor.putString("password", Password);
editor.putString("phone", Phone);
editor.commit();
// Toast.makeText(RegisterActivity.this, "Registered Successfully!", Toast.LENGTH_LONG).show();
} catch (Exception e) {
}
}
// startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
}
});
alreadyMember.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
finish();
}
});
}
@Override
public void onRegsiterReposne(JSONObject object) {
Toast.makeText(RegisterActivity.this, "hiii" + object.toString(), Toast.LENGTH_SHORT).show();
}
public final static boolean isValidEmail(CharSequence target) {
if (TextUtils.isEmpty(target)) {
return false;
} else {
return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}
}
}
这是我的服务器请求类:
public void setRegistereponse(Registereponse registereponse) {
this.registereponse = registereponse;
}
private Registereponse registereponse;
public interface Registereponse {
void onRegsiterReposne(JSONObject object);
}
public void register(JSONObject jsonObject) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Services.REGISTER_URL, jsonObject,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
Log.e("Json response", "" + response);
boolean b = response.getBoolean("success");
if (registereponse != null) {
registereponse.onRegsiterReposne(response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("Error ", "" + error);
}
}
);
queue.add(jsonObjectRequest);
}
这是我的JSON Parser类:
public class JSONParser {
//----------For Register
public JSONObject makeRegisterJson(String name, String email, String password, long phone) throws JSONException {
JSONObject object = new JSONObject();
object.put("name", name);
object.put("email", email);
object.put("password", password);
object.put("phone", phone);
// if its in array------
/*JSONObject finalObject=new JSONObject();
finalObject.put("request",object);
return finalObject;*/
return object;
}
服务器端: 我已经使用codeigniter框架在Php中进行了编码:
这是我的控制器方法:
public function register_post()
{
$data['name'] = $this->post('name');
$data['email'] = $this->post('email');
$data['phone'] = $this->post('phone');
$data['password'] = $this->post('password');
if (isset($data['name']) && !empty($data['name']) && isset($data['email']) && !empty($data['email']) && isset($data['phone']) && !empty($data['phone']) && isset($data['password']) && !empty($data['password']))
{
$model_response=$this->api_model->register_user($data);
if($model_response == "E101"){
$data_result['success'] = false;
$data_result['msg'] = "User already Exists";
}
if($model_response == "E103" || $model_response == "E102"){
$data_result['success'] = false;
$data_result['msg'] = "Record Not Inserted";
}
else
{
$name = $data['name'];
$emailid = $data['email'];
$link = "<a href=''>Verification Link</a>";
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Debugoutput = 'html';
$mail->Host = "dash.dash.in";
$mail->Port = 25;
$mail->SMTPAuth = true;
$mail->isHTML(true);
$mail->Username = "dash@dash.in";
$mail->Password = "******";
$mail->setFrom('dash@dash.in','Training App');
$mail->addAddress($emailid, 'Registration');
$mail->Subject = 'Registration - Training App';
$mail->Body = "<p>Hi $name,<br/><br/>You are successfully registered with us.<br/><br/> Please Click below link to activate your account<br/> Link - $link<br/><br/>If you have any queries or encounter any problems in logging in, please contact us on :<br>dash@dash.com <br/><br/> Thank you.</p>";
if($mail->send()){
$data_result['success'] = true;
$data_result['msg'] = "Confirmation Link to activate your account has been sent to your email address";
$data_result['data'] = array('studentId' => $model_response);
}else{
$data_result['success'] = false;
$data_result["msg"] = "Failed to send mail.";
}
}
}
else{
$data_result['success'] = false;
$data_result['msg'] = "Please Check Your Request";
}
$this->response($data_result);
}
这是我的型号代码:
public function register_user($data)
{
$email = $data['email'];
$this->db->select('username as email');
$this->db->where('username',$email);
$query = $this->db->get('tbl_login');
if($query->row() > 0)
{
return "E101";
}else{
$data_l = array(
'username' => $data['email'],
'role' => 2,
'password' => md5($data['password'])
);
$this->db->insert('tbl_login', $data_l);
if ($this->db->affected_rows() == 1) {
$loginId = $this->db->insert_id();
$data_s = array(
'name' => $data['name'],
'email' => $data['email'],
'phone' => $data['phone'],
'loginId' => $loginId
);
$this->db->insert('student', $data_s);
if ($this->db->affected_rows() == 1) {
$studentId = $this->db->insert_id();
return $studentId;
} else {
return "E102";
}
}else {
return "E103";
}
}
}
我不知道我哪里出错了。
答案 0 :(得分:4)
请查看下面的代码,我添加了一行queue.getCache()。clear();这将有效。
public void setRegistereponse(Registereponse registereponse) {
this.registereponse = registereponse;
}
private Registereponse registereponse;
public interface Registereponse {
void onRegsiterReposne(JSONObject object);
}
public void register(JSONObject jsonObject) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Services.REGISTER_URL, jsonObject,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
Log.e("Json response", "" + response);
boolean b = response.getBoolean("success");
if (registereponse != null) {
registereponse.onRegsiterReposne(response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("Error ", "" + error);
}
}
);
queue.getCache().clear();
queue.add(jsonObjectRequest);
}
答案 1 :(得分:2)
我找到了另一个解决方案。它适用于我使用Async任务,但仍然不明白为什么我使用Volley时会出现错误。