簡體   English   中英

Android Volley從登錄php獲取響應,但未進入下一個活動

[英]Android Volley getting response from login php but not going to next activity

Android登錄問題。 PHP完美地以JSON格式返回了響應。 但是android活動不會轉到下一個活動。 有時顯示網絡連接錯誤,有時即使密碼正確也顯示密碼不匹配錯誤

這是我的密碼

的login.php

  <?php

include("Connection.php");

if(isset($_POST["email"]) && isset($_POST["password"]))
{

   $email=$_POST["email"];

   $password=$_POST["password"];

   $result = mysqli_query($conn, "select * from user_master where email='$email' && password='$password'");

    if(mysqli_num_rows($result) > 0)
    {   
        $isLogin["success"] = 1;

    }           
    else
    {   
        $isLogin["success"] = 0;
    }
    echo json_encode($isLogin);
}


?>

LoginRequest.java

    package com.talentakeaways.ttpms;

import com.android.volley.AuthFailureError;

import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;



import java.util.HashMap;
import java.util.Map;

/**
 * Created by chand on 15-03-2018.
 */

public class LoginRequest extends StringRequest {


    private static final String LOGIN_URL = "http://192.168.1.9:80/Ttpms/login.php";
    private Map<String, String> parameters;
    LoginRequest(String username, String password, Response.Listener<String> listener, Response.ErrorListener errorListener) {
        super(Method.POST, LOGIN_URL, listener, errorListener);
        parameters = new HashMap<>();
        parameters.put("email", username);
        parameters.put("password", password);
    }
    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        return parameters;
    }
}

Ttpm_Login.java

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ttpm_login);
        setTitle("Login"); //set title of the activity
        initialize();
        final RequestQueue requestQueue = Volley.newRequestQueue(Ttpm_Login.this);
        //onClickListener method for button
        bt_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //assigning String variables to the text in edit texts
                userName = tenantname.getText().toString();
                password = passWord.getText().toString();
                //Validating the String values
                if (validateUsername(userName) && validatePassword(password)) {

                    //Start ProgressDialog
                    final ProgressDialog progressDialog = new ProgressDialog(Ttpm_Login.this);
                    progressDialog.setTitle("Please Wait");
                    progressDialog.setMessage("Logging You In");
                    progressDialog.setCancelable(false);
                    progressDialog.show();


                    //LoginRequest from class LoginRequest
                    LoginRequest loginRequest = new LoginRequest(userName, password, new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            Log.i("Login Response", response);
                            progressDialog.dismiss();
                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                //If Success then start Dashboard Activity
                                if (jsonObject.getString("success").equals(1)) {
                                    Intent loginSuccess = new Intent(getApplicationContext(), Ttpm_Dashboard.class);
                                    startActivity(loginSuccess);
                                    finish();
                                }

                                //else Invalid
                                else {
                                    if (jsonObject.getString("success").equals(0))
                                        Toast.makeText(getApplicationContext(), "User Not Found", Toast.LENGTH_SHORT).show();
//                                    else {
//                                        Toast.makeText(getApplicationContext(), "Passwords Don't Match", Toast.LENGTH_SHORT).show();
//                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                                Log.getStackTraceString(e);
                                Toast.makeText(Ttpm_Login.this, "Bad Response from the Server", Toast.LENGTH_SHORT).show();
                            }
                        }

                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            progressDialog.dismiss();
                            if (error instanceof ServerError) {
                                Toast.makeText(Ttpm_Login.this, "Server Error", Toast.LENGTH_SHORT).show();
                            } else if (error instanceof TimeoutError) {
                                Toast.makeText(Ttpm_Login.this, "Connection Timed Out", Toast.LENGTH_SHORT).show();
                            } else if (error instanceof NetworkError) {
                                Toast.makeText(Ttpm_Login.this, "Bad Network Connection", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                    requestQueue.add(loginRequest);
                }
            }
        });
    }

請先幫助謝謝。

您正在將JSON結果與錯誤的數字進行比較

嘗試這個

   if (jsonObject.getString("success").equals("1"))  {
      // Proceed to Login
   }  else { 
          if (jsonObject.getString("success").equals("0")) {
   }

服務器返回{ "success" : "1" }

PHP文件中的if..else條件上方將此塊寫為

$isLogin["success"] = 0; //This will give access outside of If condition.
if(mysqli_num_rows($result) > 0)
{   
    $isLogin["success"] = 1;

}           

echo json_encode($isLogin);

就像@Lucifer發布的那樣,服務器返回{"success":"1"} ,在您Activity的代碼中將您的as寫為

JSONObject jsonObject = new JSONObject(response);
if(jsonObject.getString("success").equals("1"))
{
     //Success
}
else{
    //Invalid Login
}

請嘗試以下代碼,這對您有很大幫助:

    String url = Global.BASE_URL + Global.LOGIN_API;
    cancel_login_api=url;
    StringRequest jsonObjReq = new StringRequest(Request.Method.POST,
            url,
            new Response.Listener<String>() {
                /** Api response action*/
                @Override
                public void onResponse(String response) {
                      Log.e("AB",response);
                     /** receiving response from api here*/
                    try {
                        JSONObject obj = new JSONObject(response);
                        if (API.success(obj))
                        {

                            Utils.storeUserPreferences(LoginActivity.this, Global.USER, API.getData(obj));
                            Toast.makeText(LoginActivity.this, API.rMessage(obj), Toast.LENGTH_SHORT).show();
                            Intent skip = new Intent(LoginActivity.this, HomeActivity.class);
                            startActivity(skip);
                        } else
                        {
                            Toast.makeText(LoginActivity.this, ""+API.rMessage(obj), Toast.LENGTH_SHORT).show();
                        }
                    }   catch (Exception e) {
                        e.printStackTrace();
                        Log.e("AA",response);
                    }

                    /** Alert dialog box is dismiss*/
                    pd.dismiss();
                }
            }, new Response.ErrorListener() {
        /** method when no response from internet*/
        @Override
        public void onErrorResponse(VolleyError error) {
            /** Error Log */
            VolleyLog.d(TAG, "Error: " + error.getMessage());
            Log.e("AA",""+error.getMessage());

            /** Alert dialog box is dismiss*/
            pd.dismiss();
        }
      }) {

        /*
        ** Sending parameters to server
        * @params user_login
        * @params user_login_password
        */

        @Override
        protected Map<String, String> getParams() {

          /** Pass the parameters to according to the API.*/
            Map<String, String> params = new HashMap<String, String>();
            params.put("user_login", edt_email.getText().toString().trim());
            params.put("user_login_password", edt_password.getText().toString().trim());
            return params;
        }
    };
    /** Adding request to request queue*/
    AppController.getInstance().addToRequestQueue(jsonObjReq, cancel_login_api);
}

嘗試這個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM