简体   繁体   中英

onActivityResult not passing requestCode

in my app I made a code that when I choose an image from gallery or camera the image should be sent on chat, but when I do that the app returns on chat activity without the image sent. Bellow is the code I made:

sendMedia.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //check if storage permission exists
                if (!checkStoragePermission()) {
                    requestStoragePermission();
                }else {
                    pickFromGallery();
                }
            }
        });

        takePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //check if camera permission exists
                if (!checkCameraPermission()) {
                    requestCameraPermission();
                }else {
                    pickFromCamera();
                }
            }
        });

private void pickFromGallery() {
        //pick from gallery
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, IMAGE_PICK_GALLERY_CODE);
    }

    private void pickFromCamera() {
        //open camera and pick image
        ContentValues contentValues = new ContentValues();
        contentValues.put(MediaStore.Images.Media.TITLE, "Temp Pick");
        contentValues.put(MediaStore.Images.Media.DESCRIPTION, "Temp Descr");
        imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, IMAGE_PICK_CAMERA_CODE);
    }

private void sendImageMessage(Uri imageUri) throws IOException {
        ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Sending Image.");
        progressDialog.show();

        String timeStamp = ""+System.currentTimeMillis();

        String filePath = "ChatImages/"+"post_"+timeStamp;

        Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
        byte[] data = byteArrayOutputStream.toByteArray();
        StorageReference reference = FirebaseStorage.getInstance().getReference().child(filePath);
        reference.putBytes(data)
                .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        progressDialog.dismiss();
                        Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
                        while (!uriTask.isSuccessful());
                        String downloadUri = uriTask.getResult().toString();

                        if (uriTask.isSuccessful()) {
                            DatabaseReference reference1 = FirebaseDatabase.getInstance().getReference();

                            HashMap<String, Object> hashMap = new HashMap<>();
                            hashMap.put("sender", firebaseUser.getUid());
                            hashMap.put("receiver", userId);
                            hashMap.put("message", downloadUri);
                            hashMap.put("timestamp", timeStamp);
                            hashMap.put("type", "image");
                            hashMap.put("isseen", false);

                            reference1.child("chats").push().setValue(hashMap);

                            DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("users").child(firebaseUser.getUid());
                            databaseReference.addValueEventListener(new ValueEventListener() {
                                @Override
                                public void onDataChange(@NonNull DataSnapshot snapshot) {
                                    Users users = snapshot.getValue(Users.class);

                                    if (notify) {
                                    }
                                    notify = false;
                                }

                                @Override
                                public void onCancelled(@NonNull DatabaseError error) {

                                }
                            });
                        }
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Toast.makeText(MessageActivity.this, "Failed to send image.", Toast.LENGTH_SHORT).show();
                    }
                });
    }

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

        switch (requestCode) {
            case CAMERA_REQUEST_CODE: {
                if (grantResults.length>0) {
                    boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                    boolean storageAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                    if (cameraAccepted && storageAccepted) {
                        pickFromCamera();
                    }else {
                        Toast.makeText(this, "Camera and storage permissions should be accepted.", Toast.LENGTH_SHORT).show();
                    }
                }else {
                }
            }
            break;
            case STORAGE_REQUEST_CODE: {
                if (grantResults.length>0) {
                    boolean storageAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                    if (storageAccepted) {
                        pickFromGallery();
                    }else {
                        Toast.makeText(this, "Storage permissions should be accepted.", Toast.LENGTH_SHORT).show();
                    }
                }
            }
            break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_OK) {
            if (resultCode == IMAGE_PICK_GALLERY_CODE) {
                imageUri = data.getData();
                try {
                    sendImageMessage(imageUri);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }else if (requestCode == IMAGE_PICK_CAMERA_CODE) {
                try {
                    sendImageMessage(imageUri);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

Well, I think there is a bug on requestCode of the onActivityResult method. Is there another way to do that?

you have messed request code and result code in onActivityResult , in first line you are comparing request and result, these won't never be == (or will always be if IMAGE_PICK_GALLERY_CODE is set to -1 like RESULT_OK is )

    if (requestCode == RESULT_OK) {
        if (resultCode == IMAGE_PICK_GALLERY_CODE) {

some camera/gallery apps may return wrong result code, still returning also data/images, so checking requestCode and proper payload in data Intent should be sufficient

    if (requestCode == IMAGE_PICK_GALLERY_CODE && data!= null) {
        imageUri = data.getData();
        if (imageUri != null)
            ...rest of code
    else if (requestCode == IMAGE_PICK_CAMERA_CODE) {
        ...

From my experience, onActivityResult is always called after you get back to your activity from the activity you opened using startActivityForResult

I believe you mixed between requestCode and resultCode . It's the request code that should be either IMAGE_PICK_GALLERY_CODE or IMAGE_PICK_CAMERA_CODE .

You should first check the request code and only then the result code (maybe there are custom results for a specific request).

Also, I'd recommend adding logs right after the function starts and print all of the arguments for easy debugging.

Enjoy:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM