[英]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.好吧,我认为 onActivityResult 方法的 requestCode 存在错误。 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 )您在
onActivityResult
中弄乱了请求代码和结果代码,在第一行您正在比较请求和结果,这些永远不会是==
(或者如果IMAGE_PICK_GALLERY_CODE
设置为-1
就像RESULT_OK
一样,则永远都是)
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一些相机/图库应用程序可能会返回错误的结果代码,仍然返回数据/图像,因此检查
requestCode
和data
Intent
中的正确有效负载应该足够了
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
根据我的经验,在您从使用
startActivityForResult
打开的活动返回活动后,总是会调用onActivityResult
I believe you mixed between requestCode
and resultCode
.我相信您在
requestCode
和resultCode
之间混为一谈。 It's the request code that should be either IMAGE_PICK_GALLERY_CODE
or IMAGE_PICK_CAMERA_CODE
.请求代码应该是
IMAGE_PICK_GALLERY_CODE
或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.另外,我建议在 function 启动后立即添加日志并打印所有 arguments 以便于调试。
Enjoy:)享受:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.