У меня есть страница регистрации в 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 } }
Если я зарегистрируюсь у новых пользователей через Postman, я получаю правильный ответ, но из приложения он всегда показывает «Пользователь уже существует».
Вот моя активность в реестре:
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; }
Сторона сервера: я сделал кодирование в Php с использованием рамки codeigniter:
Это мой метод контроллера:
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"; } } }
Я не знаю, где я ошибаюсь.
Посмотрите ниже своего кода, просто я добавил одну строку 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); }
Я нашел другое решение для этого. Он работал для меня с использованием задачи Async, но до сих пор не понял, почему возникла ошибка, когда я использую Volley.