Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/211.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 无法在android中使用JSON参数注册和登录_Php_Android_Json - Fatal编程技术网

Php 无法在android中使用JSON参数注册和登录

Php 无法在android中使用JSON参数注册和登录,php,android,json,Php,Android,Json,登录JSON响应 {"VerifiedMember":[{"user_id":"23","first_name":"karan","phone":""}],"success":1,"message":"success"} {"RegisteredMember":[{"user_id":61,"first_name":"p","phone":"9726068072"}],"success":1,"message":"Registration Successful"} 注册JSON响应 {"Ve

登录JSON响应

{"VerifiedMember":[{"user_id":"23","first_name":"karan","phone":""}],"success":1,"message":"success"}
{"RegisteredMember":[{"user_id":61,"first_name":"p","phone":"9726068072"}],"success":1,"message":"Registration Successful"}
注册JSON响应

{"VerifiedMember":[{"user_id":"23","first_name":"karan","phone":""}],"success":1,"message":"success"}
{"RegisteredMember":[{"user_id":61,"first_name":"p","phone":"9726068072"}],"success":1,"message":"Registration Successful"}
登录活动类

 public class Login extends AppCompatActivity implements View.OnClickListener{
    private static final String TAG = Login.class.getSimpleName();
    private EditText email, password;
    private Button login;
    private TextView signup;
    private ProgressDialog progressDialog;
    private UserSession session;
    private UserInfo userInfo;

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

        email        = (EditText)findViewById(R.id.email);
        password        = (EditText)findViewById(R.id.password);
        login           = (Button)findViewById(R.id.login);
        signup          = (TextView)findViewById(R.id.open_signup);
        progressDialog  = new ProgressDialog(this);
        session         = new UserSession(this);
        userInfo        = new UserInfo(this);

        if(session.isUserLoggedin()){
            startActivity(new Intent(this, MainActivity.class));
            finish();
        }

        login.setOnClickListener(this);
        signup.setOnClickListener(this);
    }

    private void login(final String email, final String password){
        // Tag used to cancel the request
        String tag_string_req = "req_login";
        progressDialog.setMessage("Logging in...");
        progressDialog.show();

        StringRequest strReq = new StringRequest(Request.Method.POST,
                Utils.LOGIN_URL, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Login Response: " + response.toString());
                progressDialog.hide();
                try {
                    JSONObject jObj = new JSONObject(response);
                    int intError = jObj.getInt("success");
                    boolean error = (intError > 0) ? true : false;


                        // Check for error node in json
                        if (!error) {
                            // Now store the user in SQLite

                            String uid = jObj.getString("user_id");
                            JSONObject user = jObj.getJSONObject("VerifiedMember");
                            String uName = user.getString("first_name");
                            String email = user.getString("phone");


                            // Inserting row in users table
                            userInfo.setEmail(email);
                            userInfo.setFirstname(uName);
                            userInfo.setUid(uid);
                            session.setLoggedin(true);
                            Intent i = new Intent(Login.this, Home.class);
                            startActivity(i);



                        } else {
                            // Error in login. Get the error message
                            String errorMsg = jObj.getString("message");
                            toast(errorMsg);


                        }
                 //   }
                }catch (JSONException e) {
                    // JSON error
                    e.printStackTrace();
                    toast("Json error: " + e.getMessage());
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Login Error: " + error.getMessage());
                toast("Unknown Error occurred");
                progressDialog.hide();
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting parameters to login url
                Map<String, String> params = new HashMap<>();
                params.put("username", email);
                params.put("password", password);

                return params;
            }

        };

        // Adding request to request queue
        AndroidLoginController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }

    private void toast(String x){
        Toast.makeText(this, x, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.login:
                String uName1 = email.getText().toString().trim();
                String pass  = password.getText().toString().trim();

                login(uName1, pass);
                break;
            case R.id.open_signup:
                startActivity(new Intent(this, SignUp.class));
                break;
        }
    }
}
public class SignUp extends AppCompatActivity {
    private String TAG = SignUp.class.getSimpleName();
    private EditText username, email, password, gender, bdate, fname, lname;
    private Button signup;
    private ProgressDialog progressDialog;
    private UserSession session;
    private UserInfo userInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_up);
        fname = (EditText) findViewById(R.id.first_name);
        lname = (EditText) findViewById(R.id.last_name);
        gender = (EditText) findViewById(R.id.gender);
        bdate = (EditText) findViewById(R.id.bdate);

      //  username = (EditText) findViewById(R.id.username);
        email = (EditText) findViewById(R.id.email_or_phone);
        password = (EditText) findViewById(R.id.password);
        signup = (Button) findViewById(R.id.signup);
        progressDialog = new ProgressDialog(this);
        session = new UserSession(this);
        userInfo = new UserInfo(this);

        signup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String fName = fname.getText().toString().trim();

                String lName = lname.getText().toString().trim();

                String gen = gender.getText().toString().trim();

                String dob = bdate.getText().toString().trim();


                String mail = email.getText().toString().trim();
                String pass = password.getText().toString().trim();



                signup(fName,lName,gen,dob, mail, pass);
            }
        });
    }

    private void signup(final String firstName,final String lastName, final String gend,  final String dobd,final String email, final String password) {
        // Tag used to cancel the request
        String tag_string_req = "req_signup";
        progressDialog.setMessage("Signing up...");
        progressDialog.show();

        StringRequest strReq = new StringRequest(Request.Method.POST,
                Utils.REGISTER_URL, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Register Response: " + response.toString());

                try {
                    JSONObject jObj = new JSONObject(response);
                    int intError = jObj.getInt("success");
                    boolean error = (intError > 0) ? true : false;

                    // Check for error node in json
                    if (!error) {
                        JSONObject user = jObj.getJSONObject("RegisteredMember");
                        String firstName = user.getString("first_name");
                        String LastName = user.getString("last_name");
                        String email = user.getString("register_nm");
                        String dobd = user.getString("bdate");
                        String gender = user.getString("gender");
                        String password = user.getString("password");

                        // Inserting row in users table
                        userInfo.setEmail(email);
                        userInfo.setFirstname(firstName);
                        userInfo.setLastname(LastName);
                        userInfo.setdob(dobd);
                        userInfo.setGender(gender);
                        userInfo.setPassword(password);

                        session.setLoggedin(true);

                        startActivity(new Intent(SignUp.this, MainActivity.class));
                    } else {
                        // Error in login. Get the error message
                        String errorMsg = jObj.getString("success");
                        toast(errorMsg);
                    }
                } catch (JSONException e) {
                    // JSON error
                    e.printStackTrace();
                    toast("Json error: " + e.getMessage());
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Login Error: " + error.getMessage());
                toast("Unknown Error occurred");
                progressDialog.hide();
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting parameters to login url
                Map<String, String> params = new HashMap<>();
                params.put("first_name", firstName);
                params.put("last_name", lastName);
                params.put("gender",gend);
                params.put("bdate",dobd);
                params.put("phone", email);
                params.put("password", password);

                return params;
            }

        };

        // Adding request to request queue
        AndroidLoginController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }

    private void toast(String x) {
        Toast.makeText(this, x, Toast.LENGTH_SHORT).show();
    }
}
public class MainActivity extends AppCompatActivity {

    private Button logout;
    private TextView tvUsername, tvEmail;
    private UserInfo userInfo;
    private UserSession userSession;

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

        userInfo        = new UserInfo(this);
        userSession     = new UserSession(this);
        logout          = (Button)findViewById(R.id.logout);
        tvUsername      = (TextView)findViewById(R.id.key_username);
        tvEmail         = (TextView)findViewById(R.id.key_email);

        if(!userSession.isUserLoggedin()){
            startActivity(new Intent(this, Login.class));
            finish();
        }

        String username = userInfo.getKeyFirstname();
        String email    = userInfo.getKeyEmail();

        tvUsername.setText(username);
        tvEmail.setText(email);

        logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                userSession.setLoggedin(false);
                userInfo.clearUserInfo();
                startActivity(new Intent(MainActivity.this, Login.class));
                finish();
            }
        });


    }

}
主要活动类

 public class Login extends AppCompatActivity implements View.OnClickListener{
    private static final String TAG = Login.class.getSimpleName();
    private EditText email, password;
    private Button login;
    private TextView signup;
    private ProgressDialog progressDialog;
    private UserSession session;
    private UserInfo userInfo;

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

        email        = (EditText)findViewById(R.id.email);
        password        = (EditText)findViewById(R.id.password);
        login           = (Button)findViewById(R.id.login);
        signup          = (TextView)findViewById(R.id.open_signup);
        progressDialog  = new ProgressDialog(this);
        session         = new UserSession(this);
        userInfo        = new UserInfo(this);

        if(session.isUserLoggedin()){
            startActivity(new Intent(this, MainActivity.class));
            finish();
        }

        login.setOnClickListener(this);
        signup.setOnClickListener(this);
    }

    private void login(final String email, final String password){
        // Tag used to cancel the request
        String tag_string_req = "req_login";
        progressDialog.setMessage("Logging in...");
        progressDialog.show();

        StringRequest strReq = new StringRequest(Request.Method.POST,
                Utils.LOGIN_URL, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Login Response: " + response.toString());
                progressDialog.hide();
                try {
                    JSONObject jObj = new JSONObject(response);
                    int intError = jObj.getInt("success");
                    boolean error = (intError > 0) ? true : false;


                        // Check for error node in json
                        if (!error) {
                            // Now store the user in SQLite

                            String uid = jObj.getString("user_id");
                            JSONObject user = jObj.getJSONObject("VerifiedMember");
                            String uName = user.getString("first_name");
                            String email = user.getString("phone");


                            // Inserting row in users table
                            userInfo.setEmail(email);
                            userInfo.setFirstname(uName);
                            userInfo.setUid(uid);
                            session.setLoggedin(true);
                            Intent i = new Intent(Login.this, Home.class);
                            startActivity(i);



                        } else {
                            // Error in login. Get the error message
                            String errorMsg = jObj.getString("message");
                            toast(errorMsg);


                        }
                 //   }
                }catch (JSONException e) {
                    // JSON error
                    e.printStackTrace();
                    toast("Json error: " + e.getMessage());
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Login Error: " + error.getMessage());
                toast("Unknown Error occurred");
                progressDialog.hide();
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting parameters to login url
                Map<String, String> params = new HashMap<>();
                params.put("username", email);
                params.put("password", password);

                return params;
            }

        };

        // Adding request to request queue
        AndroidLoginController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }

    private void toast(String x){
        Toast.makeText(this, x, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.login:
                String uName1 = email.getText().toString().trim();
                String pass  = password.getText().toString().trim();

                login(uName1, pass);
                break;
            case R.id.open_signup:
                startActivity(new Intent(this, SignUp.class));
                break;
        }
    }
}
public class SignUp extends AppCompatActivity {
    private String TAG = SignUp.class.getSimpleName();
    private EditText username, email, password, gender, bdate, fname, lname;
    private Button signup;
    private ProgressDialog progressDialog;
    private UserSession session;
    private UserInfo userInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_up);
        fname = (EditText) findViewById(R.id.first_name);
        lname = (EditText) findViewById(R.id.last_name);
        gender = (EditText) findViewById(R.id.gender);
        bdate = (EditText) findViewById(R.id.bdate);

      //  username = (EditText) findViewById(R.id.username);
        email = (EditText) findViewById(R.id.email_or_phone);
        password = (EditText) findViewById(R.id.password);
        signup = (Button) findViewById(R.id.signup);
        progressDialog = new ProgressDialog(this);
        session = new UserSession(this);
        userInfo = new UserInfo(this);

        signup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String fName = fname.getText().toString().trim();

                String lName = lname.getText().toString().trim();

                String gen = gender.getText().toString().trim();

                String dob = bdate.getText().toString().trim();


                String mail = email.getText().toString().trim();
                String pass = password.getText().toString().trim();



                signup(fName,lName,gen,dob, mail, pass);
            }
        });
    }

    private void signup(final String firstName,final String lastName, final String gend,  final String dobd,final String email, final String password) {
        // Tag used to cancel the request
        String tag_string_req = "req_signup";
        progressDialog.setMessage("Signing up...");
        progressDialog.show();

        StringRequest strReq = new StringRequest(Request.Method.POST,
                Utils.REGISTER_URL, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Register Response: " + response.toString());

                try {
                    JSONObject jObj = new JSONObject(response);
                    int intError = jObj.getInt("success");
                    boolean error = (intError > 0) ? true : false;

                    // Check for error node in json
                    if (!error) {
                        JSONObject user = jObj.getJSONObject("RegisteredMember");
                        String firstName = user.getString("first_name");
                        String LastName = user.getString("last_name");
                        String email = user.getString("register_nm");
                        String dobd = user.getString("bdate");
                        String gender = user.getString("gender");
                        String password = user.getString("password");

                        // Inserting row in users table
                        userInfo.setEmail(email);
                        userInfo.setFirstname(firstName);
                        userInfo.setLastname(LastName);
                        userInfo.setdob(dobd);
                        userInfo.setGender(gender);
                        userInfo.setPassword(password);

                        session.setLoggedin(true);

                        startActivity(new Intent(SignUp.this, MainActivity.class));
                    } else {
                        // Error in login. Get the error message
                        String errorMsg = jObj.getString("success");
                        toast(errorMsg);
                    }
                } catch (JSONException e) {
                    // JSON error
                    e.printStackTrace();
                    toast("Json error: " + e.getMessage());
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Login Error: " + error.getMessage());
                toast("Unknown Error occurred");
                progressDialog.hide();
            }
        }) {

            @Override
            protected Map<String, String> getParams() {
                // Posting parameters to login url
                Map<String, String> params = new HashMap<>();
                params.put("first_name", firstName);
                params.put("last_name", lastName);
                params.put("gender",gend);
                params.put("bdate",dobd);
                params.put("phone", email);
                params.put("password", password);

                return params;
            }

        };

        // Adding request to request queue
        AndroidLoginController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }

    private void toast(String x) {
        Toast.makeText(this, x, Toast.LENGTH_SHORT).show();
    }
}
public class MainActivity extends AppCompatActivity {

    private Button logout;
    private TextView tvUsername, tvEmail;
    private UserInfo userInfo;
    private UserSession userSession;

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

        userInfo        = new UserInfo(this);
        userSession     = new UserSession(this);
        logout          = (Button)findViewById(R.id.logout);
        tvUsername      = (TextView)findViewById(R.id.key_username);
        tvEmail         = (TextView)findViewById(R.id.key_email);

        if(!userSession.isUserLoggedin()){
            startActivity(new Intent(this, Login.class));
            finish();
        }

        String username = userInfo.getKeyFirstname();
        String email    = userInfo.getKeyEmail();

        tvUsername.setText(username);
        tvEmail.setText(email);

        logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                userSession.setLoggedin(false);
                userInfo.clearUserInfo();
                startActivity(new Intent(MainActivity.this, Login.class));
                finish();
            }
        });


    }

}
用户会话类

public class UserSession {
    private static final String TAG = UserSession.class.getSimpleName();
    private static final String PREF_NAME = "login";
    private static final String KEY_IS_LOGGED_IN = "isloggedin";
    SharedPreferences prefs;
    SharedPreferences.Editor editor;
    Context ctx;

    public UserSession(Context ctx) {
        this.ctx = ctx;
        prefs = ctx.getSharedPreferences(PREF_NAME, ctx.MODE_PRIVATE);
        editor = prefs.edit();
    }

    public void setLoggedin(boolean isLoggedin){
        editor.putBoolean(KEY_IS_LOGGED_IN, isLoggedin);
        editor.apply();
    }

    public boolean isUserLoggedin(){return prefs.getBoolean(KEY_IS_LOGGED_IN, false);}
}
注册PHP代码

<?php
require '../db_connect.php';
require "../classes/class.phpmailer.php";

if(isset($_POST['first_name']) && !empty($_POST['first_name']) && isset($_POST['last_name']) && !empty($_POST['last_name']) && isset($_POST['password']) && !empty($_POST['password']) && isset($_POST['bdate']) && !empty($_POST['bdate']) && isset($_POST['gender']) && !empty($_POST['gender'])){

$first_name=$_POST['first_name'];
$last_name=$_POST['last_name'];
//$email=$_POST['email'];
//$phone=$_POST['phone'];
$password=$_POST['password'];
$birthdate=$_POST['bdate'];
$gender=$_POST['gender'];

if(is_numeric($register_name))
{
    $email="";
    $phone=$register_name;
    if(!preg_match("/^([0-9][0-9]{9})$/",$phone)) { 
        $response["success"] = 0;
        $response["message"] = "invalid phone validation";

        // echoing JSON response
        echo json_encode($response);
        exit;
    }
    $reg_type=1;
    $email_hash="";
}
else{
    $email=$register_name;
    if(!preg_match("/^([_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,5}))|(\d+$)$/",$email)) { 
       $response["success"] = 0;
        $response["message"] = "invalid email validation";

        // echoing JSON response
        echo json_encode($response);
        exit;
    }
    $phone="";
    $reg_type=2;
    $email_hash = md5(rand(0,1000));
}
if(!preg_match("/^[a-zA-Z']+$/",$first_name)) { 
    $response["success"] = 0;
    $response["message"] = "invalid firstname validation";

    // echoing JSON response
    echo json_encode($response);
    exit;
}
if(!preg_match("/^[a-zA-Z']+$/",$last_name)) { 
    $response["success"] = 0;
    $response["message"] = "invalid lastname validation";

    // echoing JSON response
    echo json_encode($response);
    exit;
}
if(strlen($password) < 6){
    $response["success"] = 0;
    $response["message"] = "invalid password validation";

    // echoing JSON response
    echo json_encode($response);
    exit;
}
if(!($gender=='male' || $gender=='female')){
    $response["success"] = 0;
    $response["message"] = "invalid gender validation";

    // echoing JSON response
    echo json_encode($response);
    exit;   
}
if(strtotime($birthdate) > strtotime(date('d-m-Y'))){
    $response["success"] = 0;
    $response["message"] = "invalid bdate validation";

    // echoing JSON response
    echo json_encode($response);
    exit;
}
function sendOtp($otp, $phone){
        //This is the sms text that will be sent via sms 
        $sms_content = "Your verification code is $otp";

        //Encoding the text in url format
        $sms_text = urlencode($sms_content);

        $arrContextOptions=array(
        "ssl"=>array(
                "verify_peer"=>false,
                "verify_peer_name"=>false,
                ),
                );

        $api_url = 'https://www.txtguru.in/imobile/api.php?username=candidispin&password=candid@123&source=CANDID&dmobile=91'.$phone.'&message='.$sms_text;

        //Envoking the API url and getting the response 
        $response = file_get_contents($api_url);

        //Returning the response 
        //return $response;
        //header("location:confirmation.php");
    }

    function generateSalt($max = 64) {
        $characterList = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%&*?";
        $i = 0;
        $salt = "";
        while ($i < $max) {
            $salt .= $characterList{mt_rand(0, (strlen($characterList) - 1))};
            $i++;
        }
        return $salt;
    }

    $user_salt = generateSalt(); // Generates a salt from the function above
    $combo = $user_salt . $password; // Appending user password to the salt 
    $hashed_pwd = hash('sha512',$combo); // Using SHA512 to hash the salt+password combo string

    date_default_timezone_set('Asia/Kolkata');
    $date = date('Y-m-d H:i:s');
    //echo $date;
    $otp = rand(100000, 999999);
    $ip_address = $_SERVER['REMOTE_ADDR'];  

    $sql="insert into user_registration(email,phone,hashed_password,salt,first_name,last_name,birthdate,gender,created_at,register_type,email_hash,is_active,ip_address) values('".$email."','".$phone."','".$hashed_pwd."','".$user_salt."','".$first_name."','".$last_name."','".$birthdate."','".$gender."','".$date."','".$reg_type."','".$email_hash."',1,'".$ip_address."')";
    //echo $sql;

    if(mysqli_query($con,$sql)){
    $response["RegisteredMember"] = array();    
    $user_id=mysqli_insert_id($con);
    $RegisteredMember['user_id'] = $user_id;

    $sql = "SELECT * FROM user_registration WHERE id =".$user_id;
    $result = mysqli_fetch_array(mysqli_query($con,$sql));
    $RegisteredMember['first_name'] = $result['first_name'];
    $RegisteredMember['phone'] = $result['phone'];
    array_push($response["RegisteredMember"], $RegisteredMember);

    if($reg_type==1){
    $expiration_time=date('Y-m-d H:i:s', strtotime('+1 hours'));
    //echo $expiration_time;

    $sql1="INSERT INTO user_otps (user_id, otp, expiration_time) values ('$user_id','$otp','$expiration_time')";

    if(mysqli_query($con,$sql1)){
    echo sendOtp($otp,$phone);

    }
    }
    else{
        $result1 = mysqli_query($con,"select * from user_authentication");

                if (mysqli_num_rows($result1) > 0) {
                    // output data of each row

                        $row1 = mysqli_fetch_array($result1);
                        $company = $row1["Company"];
                        $webemail = $row1["WebEmail"];
                        $username = $row1["Username"];
                        $password = $row1["Password"];
                        $host = $row1["Host"];
                        $port = $row1["Port"];

                        $mail   = new PHPMailer; // call the class 
                        $mail->IsSMTP();  
                        $mail->Host = $host; //Hostname of the mail server
                        $mail->Port = $port; //Port of the SMTP like to be 25, 80, 465 or 587
                        $mail->SMTPAuth = true; //Whether to use SMTP authentication
                        $mail->SMTPSecure = 'tls';
                        $mail->Username = $username; //Username for SMTP authentication any valid email created in your domain
                        $mail->Password = $password; //Password for SMTP authentication
                        //$mail->AddReplyTo($email, $name); //reply-to address
                        $mail->SetFrom($webemail, $company); //From address of the mail
                        // put your while loop here like below,
                        $mail->Subject = "Verification Email"; //Subject od your mail
                        $mail->AddAddress($webemail, $company); //To address who will receive this email
                        $mail->AddAddress($email, ""); //To address who will receive this email
                        $url='http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
                        $s_url=$url.'/verify.php?email='.$register_name.'&hash='.$email_hash;
                        $sub =  "Thanks for signing up!<br>Your account has been created<br>Please click this link to verify your account:<br><a href=".$s_url.">Verification Link</a>";
                        $mail->MsgHTML($sub); //Put your body of the message you can place html code here
                        //$mail->AddAttachment("images/asif18-logo.png"); //Attach a file here if any or comment this line, 
                        $send = $mail->Send(); //Send the mails
                        if($send)
                        {
                            $response["success"] = 1;
                            $response["message"] = "Mail sent";

                            // echoing JSON response
                            echo json_encode($response);
                        }
                        else
                        {
                            $response["success"] = 0;
                            $response["message"] = "Mail not sent";

                            // echoing JSON response
                            echo json_encode($response);
                        }

                }
                else
                {
                            $response["success"] = 0;
                            $response["message"] = "Mail not sent";

                            // echoing JSON response
                            echo json_encode($response);
                }


    }
    $response["success"] = 1;
    $response["message"] = "Registration Successful";

    // echoing JSON response
    echo json_encode($response);
    }
    mysqli_close($con);
}
else{
    $response["success"] = 0;
    $response["message"] = "Parameters are not set";

    echo json_encode($response);
}


?>

根据注册响应JSON,“RegisteredMember”是一个数组而不是对象,这是错误的

接下来,很明显,您得到了一个错误{“success”:0,“message”:“未设置参数”},并且JSON没有“RegisteredMember”,因此出现了异常

因此,您可以检查json中是否存在该值

    if(your_json_object.has("RegisteredMember")){
        //Get the JSONArray, take a loop and get individual objects
    }
然后继续

编辑

据我所知,最初您有JSONException,但在响应中没有得到“RegisteredMember”数组。因此,基于此,您可以遵循以下代码

JSONObject jsonObject = new JSONObject(response);

            int success = jsonObject.getInt("success");
            String message = jsonObject.getString("message");

            if(jsonObject.has("RegisteredMember")){
                JSONArray jsonArray = jsonObject.getJSONArray("RegisteredMember");
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject regMemberObject = jsonArray.getJSONObject(i);
                    String phone = regMemberObject.getString("phone");
                    String firstName = regMemberObject.getString("first_name");
                    int userID = regMemberObject.getInt("user_id");
                }   
            }
            //Similar with the login Json as it too has same format
JSONObject JSONObject=新的JSONObject(响应);
int success=jsonObject.getInt(“success”);
String message=jsonObject.getString(“消息”);
if(jsonObject.has(“RegisteredMember”)){
JSONArray JSONArray=jsonObject.getJSONArray(“RegisteredMember”);
for(int i=0;i

我没有检查你的密码。我只是给出一个通用的解决方案。您将拥有响应Json的特定格式&将以相同的方式解析Json。如果出现一些错误,服务器可能不会向您发送相同格式的json,因此您可能会收到一个异常。因此,验证并解析json.has(String)首先进行验证,以便以后不会出现异常。

对代码进行以下更改

并按如下方式解析您的响应:

try {
            JSONObject jObj = new JSONObject(response);
            int intError = jObj.getInt("success");
            Boolean error = (intError < 0) ? true : false;

            if (!error){
                // user successfully logged in
                // Create login session
                session.setLogin(true);
                JSONArray verifiedMember = jObj.optJSONArray("VerifiedMember");
                for (int i =0;i<verifiedMember.length();i++){
                    JSONObject rootObj = verifiedMember.getJSONObject(i);
                    String userId = rootObj.getString("user_id");
                    String first_name = rootObj.getString("first_name");
                    String email = rootObj.getString("phone");
                    // Inserting row in users table
                    db.addUser(first__name, email);
                }
                        // Launch main activity
                        Intent intent = new Intent(LoginActivity.this,
                                MainActivity.class);
                        startActivity(intent);
                        finish();
            }


        } catch (JSONException e) {
            e.printStackTrace();
        }
试试看{
JSONObject jObj=新的JSONObject(响应);
int interor=jObj.getInt(“成功”);
布尔错误=(intError<0)?真:假;
如果(!错误){
//用户已成功登录
//创建登录会话
session.setLogin(true);
JSONArray-verifiedMember=jObj.optJSONArray(“verifiedMember”);

对于(int i=0;i
参数未设置
您似乎没有为API发送适当的参数。共享您的php代码您的android端代码看起来不错php代码添加有问题请检查并告诉我我犯了什么错误@sumitI更新了您的注册php代码我在第一次查看中看到了什么错误现在可以在我的c中编辑吗ode bcz我是这方面的新手,所以请帮助我@Subhechhu KhanalHere我已经更新了所有代码和问题,所以请帮助我解决这个问题@Subhechhu Khanalyes我很乐意帮助你。你能再发布一次例外情况吗?@Karanisranislogin回复:{“VerifiedMember”:[{“user_id:”64,“first_name:”samle”,“pho”‌​ne:“}]”,“成功”:1‌​,“消息”:“成功”‌​} @Subhechhu Khanalyeah我得到了登录响应和注册响应,当请求失败时,你有一个异常,你得到了失败的json响应。发布这篇文章,我也将帮助解析我的代码pls@sumit中的allcan u edit我没有得到确切的pls请求uh帮助me@KaranIsrani在移动到新活动之前,使用此选项隐藏进度对话框共享您获得的响应,并使用更新的代码登录响应:{“VerifiedMember”:[{“user_id”:“64”,“first_name”:“samle”,“phone”:“}],“success”:1,“message”:“success”}@sumit获得此响应bt不进入下一个活动您的响应不是有效的json您必须获得一些json异常