简体   繁体   English

如何使用 Java 从 Android 中的 Firebase 存储获取图像 URL?

[英]How to get image URL from Firebase Storage in Android using Java?

I made an application that makes a list of people that contains (name, age, description, and photo), but the problem that I searched too much but I don't find the solution.我制作了一个应用程序,其中包含(姓名,年龄,描述和照片)的人员列表,但是我搜索了太多但找不到解决方案的问题。 This is codes for AddPerson :这是AddPerson代码:

public class AddPersonextends AppCompatActivity {
    private TextInputEditText mFirstName, mLastName, mAge, mDescription;
    private String firstNameString, lastNameString, ageString, descriptionString;
    private Uri imageUri = null;
    CardView mInsertImage;
    ImageView mImageView;
    private static final int IMAGE_PICK_CODE = 1000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_person);

        mFirstName = findViewById(R.id.first_name_input);
        mLastName = findViewById(R.id.last_name_input);
        AboutMissingSpinner = findViewById(R.id.spinner_about_missing);
        mAge = findViewById(R.id.age_input);
        mDescription = findViewById(R.id.description_input);

        mInsertImage = findViewById(R.id.insert_image);
        mImageView = findViewById(R.id.imageView);


        mInsertImage.setOnClickListener(v -> pickImageFromGallery());
    }

    private void pickImageFromGallery() {
        Intent i = new Intent();
        i.setType("image/*");
        i.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(i, IMAGE_PICK_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode == RESULT_OK && requestCode == IMAGE_PICK_CODE) {
            assert data != null;
            imageUri = data.getData();
            mImageView.setImageURI(data.getData());
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void insertPerson() {
        firstNameString = Objects.requireNonNull(mFirstName.getText()).toString().trim();
        lastNameString = Objects.requireNonNull(mLastName.getText()).toString().trim();
        ageString = Objects.requireNonNull(mAge.getText()).toString().trim();
        descriptionString = Objects.requireNonNull(mDescription.getText()).toString().trim();

        if (TextUtils.isEmpty(lastNameString)) {
            lastNameString = "";
        }

        if (TextUtils.isEmpty(firstNameString) && TextUtils.isEmpty(lastNameString)
                && TextUtils.isEmpty(ageString) && TextUtils.isEmpty(descriptionString)) {
            return;
        }

        uploadImage();
    }

    private void uploadImage() {
        long timestamp = System.currentTimeMillis();
        String filePathAndName = "images/" + timestamp;

        StorageReference storageReference = FirebaseStorage.getInstance().getReference(filePathAndName);
        storageReference.putFile(imageUri)
                .addOnSuccessListener(taskSnapshot -> {
                    Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
                    while (!uriTask.isSuccessful());
                    String uploadedImageUri = "" + uriTask.getResult();
                    sendList(uploadedImageUri, timestamp);
                }).addOnFailureListener(e -> {

                });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.menu_add_person, menu);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_save) {
            insertPerson();
            finish();
            return true;
        } else if (item.getItemId() == android.R.id.home) {
            if (TextUtils.isEmpty(firstNameString) && TextUtils.isEmpty(lastNameString)
                    && TextUtils.isEmpty(ageString) && TextUtils.isEmpty(descriptionString)) {
            }

            showUnsavedChangesDialog();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void sendList(String uploadedImageUri, long timestamp) {
        DatabaseReference reference = FirebaseDatabase.getInstance().getReference("List");
        HashMap<String, Object> hashMap = new HashMap<>();

        hashMap.put("firstName", firstNameString);
        hashMap.put("lastName", lastNameString);
        hashMap.put("age", ageString);
        hashMap.put("description", descriptionString);
        hashMap.put("url", uploadedImageUri);
        hashMap.put("timestamp", timestamp);

        reference.push().setValue(hashMap);
    }
}

As also @FrankvanPuffelen mentioned in his comment, the problem is indeed at the following lines of code:正如@FrankvanPuffelen 在他的评论中提到的那样,问题确实出在以下代码行中:

while (!uriTask.isSuccessful());

When you add a ;当你添加一个; (semicolon) at the end of the line it means that the while statement has nobody. (分号)在行尾表示 while 语句没有人。 It's true that you can create a body and move the corresponding lines of code inside it, but it will not behave as an if statement.的确,您可以创建一个主体并在其中移动相应的代码行,但它不会像 if 语句那样运行。 So to solve this, you should use the following lines of code:因此,要解决此问题,您应该使用以下代码行:

StorageReference storageReference = FirebaseStorage.getInstance().getReference(filePathAndName);
UploadTask uploadTask = storageReference.putFile(imageUri);

Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
    @Override
    public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
        if (!task.isSuccessful()) {
            throw task.getException();
        }

        // Continue with the task to get the download URL
        return ref.getDownloadUrl();
    }
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
    @Override
    public void onComplete(@NonNull Task<Uri> task) {
        if (task.isSuccessful()) {
            Uri uploadedImageUri = task.getResult().toString();
            long timestamp = System.currentTimeMillis();
            sendList(uploadedImageUri, timestamp);
        } else {
            Log.d("TAG", task.getException().getMessage()); //Don't ignore potential errors!
        }
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 Firestore 中的图像 url 从 firebase 存储中获取图像 - How to get image from firebase storage with the image url that is in firestore How can I get full URL (like below) from direct Firebase Storage for Android JAVA OR Kotlin - How can I get full URL (like below) from direct Firebase Storage for Android JAVA OR Kotlin Android Firebase 存储:如何在下载之前从 firebase 存储文件 url 获取文件大小? - Android Firebase Storage: How to get file size from firebase storage file url before downloading it? 如何从 java 中的 firebase 存储中获取照片的链接,而不是 android - How to get the link of the photo from firebase storage in java, not android 在 firebase 存储上获取 URL 图像 - Get URL of image on firebase storage 如何从 Firebase Storage getDownloadURL 获取 URL - How to get URL from Firebase Storage getDownloadURL 如何从 Firebase Storage 获取下载网址? - How to get the download url from Firebase Storage? 从 Firebase 存储下载图像到 imageview 上 android 工作室 Z93F725A07423FE2189F448B336 - Downloading image from Firebase storage into imageview on android studio java 如何将图像下载URL从FireBase存储发送到SQLServer数据库? - How to send image download URL from FireBase Storage to SQLServer Database? 如何从Firebase Storage检索图像的下载URL? - How to retrieve the download URL of an image from Firebase Storage?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM