脚本执行两次

时间:2018-02-28 09:43:49

标签: java php android android-volley

我使用PHP作为我的消息传递Android应用程序的API,我创建了一个脚本,通过在第一次登录时将数据插入数据库来注册用户,我已经尝试了这个Link但是我的主键是唯一的,但脚本仍然执行两次并导致错误 : -

[27-Feb-2018 17:44:12 UTC] PHP Fatal error:  Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '3bc91dab47aeb989' for key 'users_device_id_uindex'' in [My Api Url]/DbFunction.php:44

这意味着表中有一个重复的条目。基本上,它在第一次执行时完美地存储了值,但是当它再次执行时它会给出上述错误

注册脚本( register.php ): -

<?php
require_once ("DbFunction.php");//Importing DbFunction Class

/*Initializing Variables*/
$response = array();
$db = new DbFunction();
$result = $device_id = $phone_number = $user_name = $email = $website = 
$profile_picture = $token = $created_at = '';

/* Checking If REQUEST_METHOD is POST*/
if($_SERVER['REQUEST_METHOD'] == 'POST') {

/*Checking is variables are set*/
  $device_id = isset($_POST['device_id']) ? $_POST['device_id']:null;
  $phone_number = isset($_POST['phone_number']) $_POST['phone_number']:null;
  $user_name = isset($_POST['user_name']) ? $_POST['user_name'] : null;
  $email = isset($_POST['email']) ? $_POST['email'] : null;
  $website = isset($_POST['website']) ? $_POST['website'] : null;
  $profile_picture = isset($_POST['profile_picture']) ? $_POST['profile_picture'] : null;
  $token = isset($_POST['token']) ? $_POST['token'] : null;
  $created_at = isset($_POST['created_at']) ? $_POST['created_at'] : null;


 /* Checking For Nulls*/
if (!isNull($device_id) || !isNull($phone_number) || !isNull($user_name) || !isNull($email) || !isNull($profile_picture) || !isNull($token) || !isNull($created_at)) {

        /* Calling The createUser functions with required parameters*/
        $result = $db->createUser($device_id, $phone_number, $user_name, $email, $website, $profile_picture, $token, $created_at);
        $response['error'] = !$result;// Setting the value of error which is inverse of $result(if result == true which means user registered successfully and there is no error so inverse of result which is false and vice versa)
        if($result)
        {
            $response['message'] = "User Registered Successfully";
        }
        else{
            $response['message'] = "Registration Error";
        }
    }
   /* Echoing The Reponse*/
    echo json_encode($response);
}
function isNull($variable)
{
    return is_null($variable);
}

函数脚本( DbFunction.php ): -

 public function createUser($device_id,$phone_number,$user_name ,$email ,$website ,$profile_dp ,$token ,$created_at )
{
        /* Calling the uploadImage funtion to upload the Image To Server which will Return Url Where Image Is Stored*/
        $profile_picture = $this->uploadImage($profile_dp, $email);

        $stmt = $this->conn->prepare("INSERT INTO users (device_id, phone_number, user_name, email, website, profile_picture, token, created_at) VALUES (:device_id, :phone_number, :user_name, :email, :website, :profile_picture, :token, :created_at)");
        $stmt->bindValue(':device_id', $device_id);
        $stmt->bindValue(':phone_number', $phone_number);
        $stmt->bindValue(':user_name', $user_name);
        $stmt->bindValue(':email', $email);
        $stmt->bindValue(':website', $website);
        $stmt->bindValue(':profile_picture', $profile_picture);
        $stmt->bindValue(':token', $token);
        $stmt->bindValue(':created_at', $created_at);
       return $stmt->execute();
}

现在从我调用请求的Android代码,我正在使用凌空。

UserInfoActivity.java : -

 @Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.btnNext:
            if (isValidInput()) {
                sendDataToServer();
                dialog.setMessage("Loading....");
                dialog.show();
            }
    }
}




private void sendDataToServer() {
    StringRequest strreq = new StringRequest(Request.Method.POST,
            Config.URL_REGISTER,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String Response) {
                    dialog.dismiss();
                    Log.d(TAG, Response);
                    Boolean error = null;
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(Response);
                        error = jsonObject.getBoolean("error");
                        if(!error)
                        {
                            Toast.makeText(UserInfoActivity.this,"User Registered Successfully",Toast.LENGTH_LONG).show();
                        }
                        else {
                            Toast.makeText(UserInfoActivity.this, "Something Went Wrong While Registering", Toast.LENGTH_LONG).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        Toast.makeText(UserInfoActivity.this, "Something Went Wrong While Registering", Toast.LENGTH_LONG).show();
                    }

                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError e) {
            VolleyLog.e(TAG, e);
            e.printStackTrace();
            Toast.makeText(UserInfoActivity.this, "Something Went Wrong While Registering", Toast.LENGTH_LONG).show();
            dialog.dismiss();
        }
    }) {
        @SuppressLint("HardwareIds")
        @Override
        public Map<String, String> getParams() {
            DateTime dateTime = new DateTime();
            SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0);
            Map<String, String> params = new HashMap<>();
            params.put("phone_number", FirebaseAuth.getInstance().getCurrentUser().getPhoneNumber());
            params.put("user_name", etName.getText().toString());
            params.put("email", etEmail.getText().toString());
            if (!TextUtils.isEmpty(etWebsite.getText().toString())) {
                params.put("website", etWebsite.getText().toString());
            }
            params.put("token", pref.getString("token", null));
            params.put("device_id",  Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID));
            params.put("created_at", dateTime.toString());
            params.put("profile_picture", image_to_server);
            return params;
        }
    };
    AppSingleton.getInstance(UserInfoActivity.this).addToRequestQueue(strreq);
}

AppSingleton.java : -

public class AppSingleton {
private static AppSingleton mInstance;
private RequestQueue mRequestQueue;
private static Context mContext;

private AppSingleton(Context context){
    // Specify the application context
    mContext = context;
    // Get the request queue
    mRequestQueue = getRequestQueue();
}

public static synchronized AppSingleton getInstance(Context context){
    // If Instance is null then initialize new Instance
    if(mInstance == null){
        mInstance = new AppSingleton(context);
    }
    // Return MySingleton new Instance
    return mInstance;
}

public RequestQueue getRequestQueue(){
    // If RequestQueue is null the initialize new RequestQueue
    if(mRequestQueue == null){
        mRequestQueue = Volley.newRequestQueue(mContext.getApplicationContext());
    }

    // Return RequestQueue
    return mRequestQueue;
}

public<T> void addToRequestQueue(Request<T> request){
    // Add the specified request to the request queue
    getRequestQueue().add(request);
}

}

在请求之后,我得到一个null的错误响应: -

02-28 14:58:20.690 14606-14606/com.dev.pigeon E/Volley: [1] 3.onErrorResponse: USERINFOACTIVITYTAG

更新 看完日志之后,我看到了这个: -

02-28 17:21:36.448 21212-21815/com.dev.pigeon D/Volley: [22348] BasicNetwork.logSlowRequests: HTTP response for request=<[ ] http://[My Api Url]/register.php 0xec86a58c NORMAL 1> [lifetime=8562], [size=1208], [rc=500], [retryCount=1]

02-28 17:21:36.449 21212-21815/com.dev.pigeon E/Volley: [22348] BasicNetwork.performRequest: Unexpected response code 500 for http://[My APi Url]/register.php

02-28 17:21:36.463 21212-21212/com.dev.pigeon E/Volley: [1] 3.onErrorResponse: USERINFOACTIVITYTAG

以上错误表示排球正在重试请求,我不知道为什么?

请从这个错误发生的地方得到帮助,我正在研究Volley这种奇怪的行为很长一段时间但没有得到任何解决方案。

P.S。抱歉我的英文不好和写得不好的代码!!

0 个答案:

没有答案