Android Studio中图片无法上传至App及Firebase问题求助
Hi Azizah, let's break down the issues in your code and fix them step by step:
1. Critical Bug in onActivityResult
Your first check in onActivityResult is reversed — you're comparing requestCode to RESULT_OK instead of resultCode. This means none of your image handling logic runs after selecting a photo. Plus, you weren't updating the ImageView with the selected image, so you couldn't see the preview. Fix it like this:
@Override public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); // Move this to the top first if (resultCode == RESULT_OK) { // Correct comparison here if(requestCode == IMAGE_PICK_GALLERY_CODE){ image_uri = data.getData(); // Update the corresponding ImageView immediately updatePreviewImageView(image_uri); uploadprofile(image_uri); } if (requestCode == IMAGE_PICK_CAMERA_CODE){ // Update preview for camera-captured image too updatePreviewImageView(image_uri); uploadprofile(image_uri); } } } // Helper method to update the right ImageView private void updatePreviewImageView(Uri uri) { if(profilorcover.equals("image")){ ava.setImageURI(uri); } else if(profilorcover.equals("cover")){ cover2.setImageURI(uri); } }
2. Firebase Storage Initialization Error
Your storageReference line is missing the class reference, which will break uploads entirely:
// Wrong: storageReference = getInstance().getReference(); // Correct: storageReference = FirebaseStorage.getInstance().getReference();
3. Firebase Database & Storage Rules Fix
For uploads and profile updates to work, your Firebase rules need to grant authenticated users access to their own data.
Database Rules (Secure for Production)
{ "rules": { "Users": { "$uid": { ".read": "$uid === auth.uid", ".write": "$uid === auth.uid" } } } }
Storage Rules (Secure for Production)
{ "rules": { "Users_Profile_Cover_Imgs": { ".read": "auth != null", ".write": "auth != null && resource.name.contains(auth.uid)" } } }
Note: For testing only, you can temporarily use open rules (.read": true, ".write": true), but never leave this enabled in a live app.
4. Additional Checks
- Confirm you've added the Firebase Storage dependency to your app-level
build.gradle:implementation 'com.google.firebase:firebase-storage:20.0.1' // Use the latest version available - Add a null check for
userinonCreateViewto avoid crashes if the user isn't authenticated:if(user == null){ // Handle unauthenticated state, e.g., redirect to login return view; }
Apply these fixes, and your image preview and upload functionality should start working as expected. Let me know if you hit any other snags!
内容的提问来源于stack exchange,提问作者Azizah

