我正在尝试更改在我的应用程序上注册的用户的个人资料图片.最初,它现在可以工作了.现在它不工作了.一旦我点击"相机"或"图像"这两个选项,它就会在ProfileFragments中返回给我,而无法选择图像.我如何解决?如果你需要更多代码,请告诉我
public class ProfileFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_profile, container, false);
if (!Places.isInitialized()) {
Places.initialize(requireContext(), getResources().getString(R.string.maps_api_key));
}
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
// Get current user's id
reference = FirebaseDatabase.getInstance().getReference("Users").child(firebaseUser.getUid());
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
if (user != null) {
username.setText(user.getUsername());
if ("default".equals(user.getImageURL())) {
image_profile.setImageResource(R.mipmap.ic_launcher);
} else {
// If the fragment is added to its activity and user has a image profile load it
if (isAdded()) {
Glide.with(requireContext()).load(user.getImageURL()).into(image_profile);
}
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
private void showImageImportDialog() {
// Options to display
String options[] = {"Camera", "Gallery"};
AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
builder.setTitle("Pick Image").setItems(options, (dialog, which) -> {
// Handle clicks
}).show();
}
private void pickGallery() {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, IMAGE_PICK_GALLERY_CODE);
}
private void pickCamera() {
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.Images.Media.TITLE, "GroupImage");
contentValues.put(MediaStore.Images.Media.DESCRIPTION, "GroupImageDescription");
imageUri = requireContext().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);
}
// Get file extension
private String getFileExtension(Uri uri) {
ContentResolver contentResolver = requireContext().getContentResolver();
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(uri));
}
private void uploadImage() throws IOException {
// Show a progress dialog with a message
progressDialog = new ProgressDialog(requireContext());
progressDialog.setTitle("Please wait");
progressDialog.setMessage("Uploading Image...");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
// If imageUri has been initialized
if (imageUri != null) {
// Set storage reference
storageReference = FirebaseStorage.getInstance().getReference("ProfileImages").child(System.currentTimeMillis()+ "." + getFileExtension(imageUri));
// Compress the image
Bitmap bmp = MediaStore.Images.Media.getBitmap(requireContext().getContentResolver(), imageUri);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 15, baos);
byte[] data = baos.toByteArray();
// Upload the image to data base
uploadTask = storageReference.putBytes(data);
//uploadTask = fileReference.putFile(imageUri);
uploadTask.continueWithTask((Continuation<UploadTask.TaskSnapshot, Task<Uri>>) task -> {
if (!task.isSuccessful()) {
throw task.getException();
}
// Return the image url
return storageReference.getDownloadUrl();
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
@Override
public void onComplete(@NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
String mUri = downloadUri.toString();
// Put image url to users reference
reference = FirebaseDatabase.getInstance().getReference("Users").child(firebaseUser.getUid());
HashMap<String, Object> map = new HashMap<>();
map.put("imageURL", mUri);
reference.updateChildren(map);
// Close the progress dialog
}
else {
Toast.makeText(requireContext(), "Failed!", Toast.LENGTH_SHORT).show();
}
progressDialog.dismiss();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(requireContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
});
}
else {
Toast.makeText(requireContext(), "No Image Selected", Toast.LENGTH_SHORT).show();
}
}
// Receive the result from a previous call to startActivityForResult
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if requestCode is 1 and result code is -1 and there is some data (image selected)
if (resultCode == Activity.RESULT_OK){
if (requestCode == IMAGE_PICK_GALLERY_CODE && data != null && data.getData() != null) {
// Set imageUri with the given URI data
imageUri = data.getData();
// If you already uploading show a toast message
if (uploadTask != null && uploadTask.isInProgress()) {
Toast.makeText(requireContext(), "Uploading in progress", Toast.LENGTH_SHORT).show();
}
// Else call uploadImage
else {
try {
uploadImage();
//Toast.makeText(requireContext(), "Working", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
}
else if (requestCode == IMAGE_PICK_CAMERA_CODE) {
if (uploadTask != null && uploadTask.isInProgress()) {
Toast.makeText(requireContext(), "Uploading in progress", Toast.LENGTH_SHORT).show();
}
else {
try {
uploadImage();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}