firebase 数据库和存储为图像返回 null

Posted

技术标签:

【中文标题】firebase 数据库和存储为图像返回 null【英文标题】:firebase database and storage returning null for image 【发布时间】:2021-05-19 12:27:34 【问题描述】:

我遇到了问题,请帮忙。我正在从 firebase 数据库返回数据,包括来自 firebase 存储的图像 URL,但图像 URL 似乎返回 null。我一直在尝试多种方法,但似乎没有任何效果。

这是模型类:

public class upload 

    private String mName;
    private String mFormula;
    private String mPrice;
    private String mImageUrl;

    public upload()
    

    

    public upload(String mName, String mFormula, String mPrice, String mImageUrl) 
        if (mName.trim().equals("")) 
            mName = "No Name";
        
        this.mName = mName;
        this.mFormula = mFormula;
        this.mPrice = mPrice;
        this.mImageUrl = mImageUrl;
    

    public String getmName() 
        return mName;
    

    public void setmName(String mName) 
        this.mName = mName;
    

    public String getmFormula() 
        return mFormula;
    

    public void setmFormula(String mFormula) 
        this.mFormula = mFormula;
    

    public String getmPrice() 
        return mPrice;
    

    public void setmPrice(String mPrice) 
        this.mPrice = mPrice;
    

    public String getmImageUrl() 
        return mImageUrl;
    

    public void setmImageUrl(String mImageUrl) 
        this.mImageUrl = mImageUrl;
    


这是带有recyclerview的片段



public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) 
        dashboardViewModel =
                ViewModelProviders.of(this).get(DashboardViewModel.class);
        View root = inflater.inflate(R.layout.fragment_dashboard, container, false);



        mStorageRef = FirebaseStorage.getInstance().getReference("meds");
        mDatabaseRef = FirebaseDatabase.getInstance().getReference("meds");

        fab = root.findViewById(R.id.floatingActionButton);
        fab.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 

                callBottomSheet();
            
        );

        mRecyclerView = root.findViewById(R.id.recyclerview);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

       // mProgressCircle = root.findViewById(R.id.progress_circle);
        mUploads = new ArrayList<>();

        mDatabaseRef.addValueEventListener(new ValueEventListener() 
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) 
                for (DataSnapshot postSnapshot : snapshot.getChildren()) 
                    upload upload = postSnapshot.getValue(upload.class);
                    mUploads.add(upload);
                
                mAdapter = new imageAdapter(getActivity(), mUploads);
                mRecyclerView.setAdapter(mAdapter);
//                mProgressCircle.setVisibility(View.INVISIBLE);
            

            @Override
            public void onCancelled(@NonNull DatabaseError error) 
                Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_SHORT).show();

            
        );

        return root;
    
  private void uploadFile() 
        if (mImageUri != null) 
            StorageReference fileReference = mStorageRef.child(System.currentTimeMillis()
                    + "." + getFileExtension(mImageUri));
            mUploadTask = fileReference.putFile(mImageUri)
                    .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() 
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) 
                            Handler handler = new Handler();
                            handler.postDelayed(new Runnable() 
                                @Override
                                public void run() 
                                    mProgressBar.setProgress(0);
                                
                            , 500);
                            Toast.makeText(getActivity(), "Upload successful", Toast.LENGTH_LONG).show();
                            /*upload upload = new upload(name.getText().toString().trim(),
                                    formula.getText().toString().trim(),
                                    price.getText().toString().trim(),
                                    taskSnapshot.getMetadata().getReference().getDownloadUrl().toString());
                            String uploadId = mDatabaseRef.push().getKey();
                            mDatabaseRef.child(uploadId).setValue(upload);*/
                            Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
                            while (!urlTask.isSuccessful());
                            Uri downloadUrl = urlTask.getResult();

                            //Log.d(TAG, "onSuccess: firebase download url: " + downloadUrl.toString()); //use if testing...don't need this line.
                            upload upload = new upload(name.getText().toString().trim(),
                                    formula.getText().toString().trim(),
                                    price.getText().toString().trim(),
                                    downloadUrl.toString());

                            String uploadId = mDatabaseRef.push().getKey();
                            mDatabaseRef.child(uploadId).setValue(upload);
                        
                    )
                    .addOnFailureListener(new OnFailureListener() 
                        @Override
                        public void onFailure(@NonNull Exception e) 
                            Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
                        
                    )
                    .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() 
                        @Override
                        public void onProgress(@NonNull UploadTask.TaskSnapshot snapshot) 
                            double progress = (100.0 * snapshot.getBytesTransferred() / snapshot.getTotalByteCount());
                            mProgressBar.setProgress((int) progress);
                        
                    );
         else 
            Toast.makeText(getActivity(), "No file selected", Toast.LENGTH_SHORT).show();
        
    

最后这是适配器



 public void onBindViewHolder(@NonNull ImageViewHolder holder, int position) 
        upload uploadCurrent = mUploads.get(position);
        holder.Name.setText(uploadCurrent.getmName());
        Picasso.get()
                .load(uploadCurrent.getmImageUrl())
                .fit()
                .centerCrop()
                .into(holder.imageView);

//        Glide.with(mContext).load(uploadCurrent.getmImageUrl()).into(holder.imageView);

    

public class ImageViewHolder extends RecyclerView.ViewHolder 
        public TextView Name, Formula, Price;
        public ImageView imageView;
        public ImageViewHolder(View itemView) 
            super(itemView);
            Name = itemView.findViewById(R.id.item_name);
            Formula = itemView.findViewById(R.id.item_formula);
            Price = itemView.findViewById(R.id.item_price);
            imageView = itemView.findViewById(R.id.image_view);
        
    

这是数据库结构 database structure

【问题讨论】:

请编辑您的问题并将您的数据库结构添加为 JSON 文件或至少是屏幕截图。 我添加了截图 【参考方案1】:

更改 taskSnapshot.getStorage().getDownloadUrl();到 taskSnapshot.getMetadata()).getReference()).getDownloadUrl()。这将返回下载 uri。将 uri 字符串上传到您的数据库。 典型的 Firebase 存储下载 URL 类似于 https://firebasestorage.googleapis.com/v0/b/projectname.appspot.com/o/storage_info?alt=media&token=tokenid。不是您数据库中的那个。

【讨论】:

以上是关于firebase 数据库和存储为图像返回 null的主要内容,如果未能解决你的问题,请参考以下文章

如何在实时数据库firebase android中存储下载图像url

如何将多个图像上传到 Firebase 存储并返回多个下载 URL

Firebase 快照返回 null

如何将多个图像上传到Firebase存储并返回多个downloadURL

Firebase 数据库返回 null

Firebase存储规则资源变量返回null