上载会导致延迟,并导致某些参数重复出现

时间:2019-06-15 13:01:14

标签: java php android android-volley laravel-5.8

我目前正在使用个人资料图片上传功能在android上进行注册活动。我成功完成了上传和注册,该保存在数据库中,并保存到我为个人资料图片设置的文件路径中,但是这会导致一些延迟,导致某些参数重复执行我认为正在执行的操作。因为我注意到它已成功上传并保存到数据库,但没有收到成功消息,而是返回了电子邮件上的错误验证:“电子邮件已存在”

RegisterController.php

 public function storeuser(Request $request){

            $valid = $this->validateRequest($request);

            if($valid){

            if(!User::all()->where('Email', '=', $valid['email'])->first()){

                $userinsert = new User();
                $userinsert->firstname = $valid['firstname'];
                $userinsert->lastname = $valid['lastname']; 
                $userinsert->email = $valid['email'];
                $userinsert->password = bcrypt($valid['password']); 
                $userinsert->mobile = $valid['mobile']; 
                $userinsert->status = 0;
                $userinsert->activationno = str_random(30); 
                $userinsert->usertypeid = 2;


                    if($userinsert->save()){ 

                        $userinsert->sendVerificationEmail(); 

                        $this->storeImage($userinsert);

                        return response()->json(['status' => "good" ,'success' => "Account Registered, Please verify email" ]); 
                    }
                    else{
                        return back()->withErrors();
                    }
            }

            else{
                return response()->json(['email' => "Email already exists"]); 
            }
        }

        else{
            return response()->withErrors(); 
        }
    }

    private function storeImage($profilepic)
    {
        $target = "profilepic";
        $target = $target ."/". rand()."_".time(). ".jpeg";

        if (request()->has('profile')) {

            $profilepic->update([
                'ProfilePicture' => $target,
            ]);           

            $add_to_public = "public/".$target;

            $img = \Storage::put($add_to_public, base64_decode(request()->profile));
            $profilepic->save();


        }
    }

这是Java的代码

SignupActivity.java

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_signup);

        requestQueue = Volley.newRequestQueue(this);

        firstname =  findViewById(R.id.firstname);
        lastname =  findViewById(R.id.lastname);
        email =  findViewById(R.id.email);
        password =  findViewById(R.id.password);
        mobile =  findViewById(R.id.mobile);
        confirmpassword =  findViewById(R.id.confirm);

        upload = findViewById(R.id.uploadImage);
        profilepic = findViewById(R.id.profilePic);

        register = findViewById(R.id.register);

        // ? uploads an Image
        upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityCompat.requestPermissions(SignupActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, CODE_GALLERY_REQUEST);
                Log.d(TAG, "Button is Clicked");
            }
        });


        // ? Continue to registration page
        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String fname = firstname.getText().toString();
                String lname =  lastname.getText().toString();
                String eml =  email.getText().toString();
                String pswrd =  password.getText().toString();
                String confirmpswrd =  confirmpassword.getText().toString();
                String mob = mobile.getText().toString();

                registerAccount(fname, lname, eml , mob, pswrd, confirmpswrd);

            }
        });
    }


    private void registerAccount(final String firstname, final String lastname, final String email, final String mobile, final String password, final String confirm_password){

        Log.d(TAG, "Register account process");
        Log.d(TAG, "Showing Passed parameters");
        Log.d(TAG, "Firstname: " + firstname);
        Log.d(TAG, "Lastname: " + lastname);
        Log.d(TAG, "Email: " + email);
        Log.d(TAG, "Mobile: " + mobile);
        Log.d(TAG, "Password: " + password);


        StringRequest registerRequest = new StringRequest(Request.Method.POST, UrlHelper.register_url, new Response.Listener<String>()
        {
            @Override
            public void onResponse(String response) {
                try {

                    JSONObject initialObj = new JSONObject(response);

                    Log.d(TAG, "getting image " + initialObj.optString("image"));
                    Log.d(TAG, "Getting Status..." + initialObj.optString("status"));

                    if (initialObj.optString("status").equals("good")){

                        Log.i(TAG, "Account registered");

                        Log.i(TAG, "img: " + initialObj.optString("profile"));

                        Toast.makeText(getApplicationContext(), initialObj.optString("success"), Toast.LENGTH_LONG).show();


                    }else{
                        Log.d(TAG, "Something went wrong or no response receive");
                        Log.d(TAG, "Response received:" + initialObj);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();

                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

                VolleyLog.d("volley", "Error: " + error.getMessage());
                error.printStackTrace();
                System.out.println("Does not work");
                Toast.makeText(getApplicationContext(), "Error!", Toast.LENGTH_LONG).show();


                NetworkResponse networkResponse = error.networkResponse;
                if (networkResponse != null && networkResponse.data != null) {
                    String jsonError = new String(networkResponse.data);

                    Log.e(TAG, "Error: " + jsonError);
                    Log.d(TAG, "Recieved an error validation");

                }


            }
        }
        )

        {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError { // ? Content type use
                Map<String, String> pars = new HashMap<String, String>();
                pars.put("Accept", "application/json");
                pars.put("Content-Type", "application/x-www-form-urlencoded");
                return pars;
            }


            @Override
            protected Map<String, String> getParams() throws AuthFailureError
            {
                Map<String, String> params = new HashMap<String, String>();
                String imageData = convertImage(bitmap);
                //Log.d(TAG, "Image Received: " + imageData);
                params.put("firstname", firstname);
                params.put("profile", imageData); // ? this will be put in as the parameter
                params.put("lastname", lastname);
                params.put("email", email);
                params.put("mobile", String.valueOf(mobile));
                params.put("password", password);
                params.put("password_confirmation", confirm_password);


                return params;
            }
        };

        requestQueue.add(registerRequest);
    }

    private String convertImage(Bitmap bitmap){

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);

        byte[] imageBytes = outputStream.toByteArray();

        String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);

        return encodedImage;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        if(requestCode == CODE_GALLERY_REQUEST){
            if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                Intent pick_profile = new Intent(Intent.ACTION_PICK);
                pick_profile.setType("image/*");
                startActivityForResult(Intent.createChooser(pick_profile, "Select a Profile Picture"), CODE_GALLERY_REQUEST);
            }
            else{
                Toast.makeText(getApplicationContext(), "Please grant permission", Toast.LENGTH_LONG).show();
            }
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if(requestCode == CODE_GALLERY_REQUEST && resultCode == RESULT_OK && data != null){
            Uri filepath = data.getData();

            try {
                InputStream inputStream = getContentResolver().openInputStream(filepath);
                bitmap = BitmapFactory.decodeStream(inputStream);
                profilepic.setImageBitmap(bitmap);

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }


        }
        super.onActivityResult(requestCode, resultCode, data);
    }

谢谢

0 个答案:

没有答案