Android实现带身份验证的Camera Intent图片上传至Firebase
Hey there! Let's get your authenticated Firebase image upload working smoothly. I've looked over your code and spotted a few key gaps and outdated methods that are holding this back—let's fix them step by step:
Key Fixes & Improvements
Initialize your Storage Reference properly
You declaredmstorageRefbut never assigned it a value, which will cause aNullPointerExceptionwhen you try to upload. Add this line in youronCreatemethod:mstorageRef = FirebaseStorage.getInstance().getReference();Update the Download URL retrieval method
The oldtaskSnapshot.getDownloadUrl()is deprecated. Instead, fetch the URL from the storage reference after a successful upload.Add null safety for the captured Bitmap
If the user taps "submit" without taking a photo first,photowill be null and crash your app. Add a check at the start of thesubmitmethod.Optional: Save the image URL to Firebase Realtime Database
Since you already have a database reference, storing the download URL alongside the user's profile info makes it easy to access later.
Corrected Full Code
package com.example.android.besafe; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.provider.MediaStore; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ImageButton; import android.widget.Toast; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask; import java.io.ByteArrayOutputStream; import java.util.HashMap; import java.util.Map; public class CameraActivity extends AppCompatActivity { private ImageButton mProfileImage; Bitmap photo; private static final int CAMERA_REQ = 1; StorageReference mstorageRef; String userId; private FirebaseAuth mAuth; FirebaseUser firebaseUser; FirebaseDatabase firebaseDatabase; DatabaseReference ref; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_camera); mProfileImage = findViewById(R.id.btnselect); firebaseDatabase = FirebaseDatabase.getInstance(); ref = firebaseDatabase.getReference("ProfileInfo"); mAuth = FirebaseAuth.getInstance(); firebaseUser = mAuth.getCurrentUser(); userId = firebaseUser.getUid(); // Initialize Storage Reference (FIXED) mstorageRef = FirebaseStorage.getInstance().getReference(); mProfileImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(cameraIntent, CAMERA_REQ); } }); } public void submit(View v){ // Add null check for captured photo (FIXED) if (photo == null) { Toast.makeText(this, "Please take a photo first!", Toast.LENGTH_SHORT).show(); return; } ByteArrayOutputStream stream = new ByteArrayOutputStream(); photo.compress(Bitmap.CompressFormat.JPEG, 100, stream); byte[] b = stream.toByteArray(); StorageReference storageReference = mstorageRef.child("documentImages") .child(userId) .child("noplateImg"); storageReference.putBytes(b) .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { // Fetch download URL using updated method (FIXED) taskSnapshot.getStorage().getDownloadUrl() .addOnSuccessListener(new OnSuccessListener<Uri>() { @Override public void onSuccess(Uri downloadUri) { Toast.makeText(CameraActivity.this, "Upload successful!", Toast.LENGTH_LONG).show(); // Optional: Save URL to Realtime Database Map<String, Object> profileUpdates = new HashMap<>(); profileUpdates.put("profileImageUrl", downloadUri.toString()); ref.child(userId).updateChildren(profileUpdates) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Toast.makeText(CameraActivity.this, "Image URL saved to database!", Toast.LENGTH_SHORT).show(); } }); } }); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast.makeText(CameraActivity.this,"Upload failed: " + e.getMessage(),Toast.LENGTH_LONG).show(); } }); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // Don't forget to call super! if (requestCode == CAMERA_REQ && resultCode == RESULT_OK) { photo = (Bitmap) data.getExtras().get("data"); // Optional: Uncomment to preview the captured photo // ImageView preview = findViewById(R.id.imageview); // preview.setImageBitmap(photo); } } }
Quick Extra Notes
- Thumbnail vs Full-Resolution: The bitmap from
data.getExtras().get("data")is a low-res thumbnail. If you need full-size images, you'll need to use a File Provider to capture the image directly to a file instead. Just let me know if you want to expand on that! - Permissions: Ensure you have the
CAMERApermission (and storage permissions for older Android versions) declared in yourAndroidManifest.xml. - Auth Safety: Add a check for
firebaseUser != nullat the start ofonCreateto handle cases where the user signs out while the activity is active.
内容的提问来源于stack exchange,提问作者AHMED ABBAS

