从Firebase中获取图像,在Android Studio中展示在RecyclerView中。

huangapple go评论77阅读模式
英文:

Retriving image from firebase into recycler view in android studio

问题

以下是你提供的代码的翻译:

package com.example.blogger;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.squareup.picasso.Picasso;

public class blogupload extends AppCompatActivity {
    private RecyclerView mBlogList;
    private DatabaseReference mDataBase;
    private FirebaseAuth mAuth = FirebaseAuth.getInstance();
    FirebaseRecyclerAdapter adapter;

    @Override
    protected void onStart() {
        super.onStart();
        FirebaseRecyclerOptions<Blog> options =
                new FirebaseRecyclerOptions.Builder<Blog>()
                        .setQuery(mDataBase, Blog.class)
                        .build();

        adapter = new FirebaseRecyclerAdapter<Blog, BlogViewHolder>(options) {
            @Override
            public BlogViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                View view = LayoutInflater.from(parent.getContext())
                        .inflate(R.layout.blog_row, parent, false);

                return new BlogViewHolder(view);
            }

            @Override
            protected void onBindViewHolder(BlogViewHolder holder, int position, Blog model) {
                holder.setTitle(model.getTitle());
                holder.setDesc(model.getDesc());
                holder.setImage(model.getImage());
            }
        };
        adapter.startListening();
        mBlogList.setAdapter(adapter);
    }

    public static class BlogViewHolder extends RecyclerView.ViewHolder {
        View mView;

        public BlogViewHolder(@NonNull View itemView) {
            super(itemView);
            mView = itemView;
        }

        public void setTitle(String title) {
            TextView post_title;
            post_title = mView.findViewById(R.id.post_title);
            post_title.setText(title);
        }

        public void setDesc(String desc) {
            TextView post_desc;
            post_desc = mView.findViewById(R.id.post_desc);
            post_desc.setText(desc);
        }

        public void setImage(String image) {
            ImageView post_image;
            post_image = mView.findViewById(R.id.post_image);
            Picasso.get().load(image).into(post_image);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.action_menu, menu);
        return true;
    }

    @Override
    protected void onStop() {
        super.onStop();
        adapter.stopListening();
    }

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

        mDataBase = FirebaseDatabase.getInstance().getReference().child("blog");

        mBlogList = findViewById(R.id.blog_list);
        mBlogList.setLayoutManager(new LinearLayoutManager(this));
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.add:
                Intent intent = new Intent(getApplicationContext(), addpostactivity.class);
                startActivity(intent);
                return true;
            case R.id.logout:
                mAuth.signOut();
                Intent intent1 = new Intent(getApplicationContext(), MainActivity.class);
                startActivity(intent1);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}

图片上传活动:

package com.example.blogger;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
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 com.squareup.picasso.Picasso;

import java.util.Random;

public class addpostactivity extends AppCompatActivity {

    private static final int MAX_LENGTH = 23;
    ProgressBar mProgress;
    ImageView selectimage;
    TextView posttitle, postdesc;
    Button submitbtn;
    private Uri uri;
    private static final int GALLERY_INTENT = 2;
    private StorageReference mStorage;
    private DatabaseReference mDataBase;
    private FirebaseAuth mAuth;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == GALLERY_INTENT && resultCode == RESULT_OK) {
            uri = data.getData();
            Picasso.get().load(uri).into(selectimage);
        }
    }

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

        selectimage = findViewById(R.id.selectimage);
        posttitle = findViewById(R.id.posttitle);
        postdesc = findViewById(R.id.postdesc);
        submitbtn = findViewById(R.id.submitbtn);

        mProgress = new ProgressBar(this);

        mDataBase = FirebaseDatabase.getInstance().getReference().child("blog");

        submitbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startposting();
            }
        });

        selectimage.setVisibility(View.VISIBLE);
        mStorage = FirebaseStorage.getInstance().getReference();

        selectimage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent, GALLERY_INTENT);
            }
        });
    }

    public static String random() {
        Random generator = new Random();
        StringBuilder randomStringBuilder = new StringBuilder();
        int randomLength = generator.nextInt(MAX_LENGTH);
        char tempChar;
        for (int i = 0; i < randomLength; i++) {
            tempChar = (char) (generator.nextInt(96) + 32);
            randomStringBuilder.append(tempChar);
        }
        return randomStringBuilder.toString();
    }

    private void startposting() {
        mProgress.setProgress(0);
        mProgress.setVisibility(View.VISIBLE);

        String title_value = posttitle.getText().toString().trim();
        String desc_value = postdesc.getText().toString().trim();
        if (!TextUtils.isEmpty(title_value) && !TextUtils.isEmpty(desc_value) && uri != null) {
            StorageReference filepath = mStorage.child("blog_image").child(random());

            filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    Toast.makeText(getApplicationContext(), "Uploaded", Toast.LENGTH_SHORT).show();
                }
            });
        }

        DatabaseReference newPost = mDataBase.push();
        newPost.child("title").setValue(title_value);
        newPost.child("desc").setValue(desc_value);
        newPost.child("image").setValue(uri.toString());

        Intent intent = new Intent(getApplicationContext(), blogupload.class);
        startActivity(intent);
    }
}
英文:

I'm trying to retrive image from firebase Database (the image is in storage ) .
I'm unable to convert it into url to pass it to picasso to load it in a recycler view . It works if uploaded and retrieved from same device but the image isn't shown on other devices . Any help would be of almost use .
I am trying to store and retrieve image by using Firebase. It is okay when storing an image, but I can't show it in an ImageView. It doesn't give an error so I can't understand where is the mistake.
i gave the required permissions.

Thank you in advnace.
Mainactivity.java

package com.example.blogger;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.squareup.picasso.Picasso;
public class blogupload extends AppCompatActivity {
private RecyclerView mBlogList;
private DatabaseReference mDataBase;
private FirebaseAuth mAuth=FirebaseAuth.getInstance();
FirebaseRecyclerAdapter adapter;
@Override
protected void onStart() {
super.onStart();
FirebaseRecyclerOptions&lt;Blog&gt; options =
new FirebaseRecyclerOptions.Builder&lt;Blog&gt;()
.setQuery(mDataBase,Blog.class)
.build();
adapter = new FirebaseRecyclerAdapter&lt;Blog, BlogViewHolder&gt;(options) {
@Override
public BlogViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.blog_row, parent, false);
return new BlogViewHolder(view);
}
@Override
protected void onBindViewHolder(BlogViewHolder holder, int position, Blog model) {
holder.setTitle(model.getTitle());
holder.setDesc(model.getDesc());
holder.setImage(model.getImage());
}
};
adapter.startListening();
mBlogList.setAdapter(adapter);
}
public static class BlogViewHolder extends RecyclerView.ViewHolder {
View mView;
public BlogViewHolder(@NonNull View itemView) {
super(itemView);
mView=itemView;
}
public void setTitle(String title)
{
TextView post_title ;
post_title=(TextView) mView.findViewById(R.id.post_title);
post_title.setText(title);
}
public void setDesc(String desc)
{
TextView post_desc ;
post_desc=(TextView) mView.findViewById(R.id.post_desc);
post_desc.setText(desc);
}
public void setImage(String image)
{
ImageView post_image;
post_image=(ImageView) mView.findViewById(R.id.post_image);
Picasso.get().load(image).into(post_image);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.action_menu,menu);
return true;
}
@Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_blogupload);
mDataBase= FirebaseDatabase.getInstance().getReference().child(&quot;blog&quot;);
mBlogList=(RecyclerView) findViewById(R.id.blog_list);
mBlogList.setLayoutManager(new LinearLayoutManager(this));
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.add:
Intent intent = new Intent(getApplicationContext(), addpostactivity.class);
startActivity(intent);
return true;
case R.id.logout:
mAuth.signOut();
Intent intent1 =new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent1);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}

image upload activity

package com.example.blogger;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
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 com.squareup.picasso.Picasso;
import java.util.Random;
public class addpostactivity extends AppCompatActivity
{
private static final int MAX_LENGTH = 23 ;
ProgressBar mProgress;
ImageView selectimage;
TextView posttitle,postdesc;
Button submitbtn;
private Uri uri;
private static final int GALLERY_INTENT=2;
private StorageReference mStorage;
private DatabaseReference mDataBase;
private FirebaseAuth mAuth;
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==GALLERY_INTENT&amp;&amp;resultCode==RESULT_OK)
{
uri=data.getData();
Picasso.get().load(uri).into(selectimage);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addpostactivity);
selectimage=(ImageView) findViewById(R.id.selectimage);
posttitle=(TextView) findViewById(R.id.posttitle);
postdesc=(TextView) findViewById(R.id.postdesc);
submitbtn=(Button) findViewById(R.id.submitbtn);
mProgress= new ProgressBar(this);
mDataBase= FirebaseDatabase.getInstance().getReference().child(&quot;blog&quot;);
submitbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startposting();
}
});
selectimage.setVisibility(View.VISIBLE);
mStorage= FirebaseStorage.getInstance().getReference();
selectimage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent =new Intent(Intent.ACTION_PICK);
intent.setType(&quot;image/w&quot;);
startActivityForResult(intent,GALLERY_INTENT);
}
});
}
public static String random() {
Random generator = new Random();
StringBuilder randomStringBuilder = new StringBuilder();
int randomLength = generator.nextInt(MAX_LENGTH);
char tempChar;
for (int i = 0; i &lt; randomLength; i++){
tempChar = (char) (generator.nextInt(96) + 32);
randomStringBuilder.append(tempChar);
}
return randomStringBuilder.toString();
}
private void startposting() 
{
mProgress.setProgress(0);
mProgress.setVisibility(View.VISIBLE);
String title_value=posttitle.getText().toString().trim();
String desc_value=postdesc.getText().toString().trim();
if(!TextUtils.isEmpty(title_value)  &amp;&amp;  !TextUtils.isEmpty(desc_value)  &amp;&amp;  uri!=null)
{
StorageReference filepath=mStorage.child(&quot;blog_image&quot;).child(random());
//adding a picture to storage
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener&lt;UploadTask.TaskSnapshot&gt;() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(getApplicationContext(),&quot;Uploaded&quot;,Toast.LENGTH_SHORT).show();
}
});
}
DatabaseReference newPost=mDataBase.push();
//newPost.child(&quot;uid&quot;).setValue(mAuth.getCurrentUser().getUid());
newPost.child(&quot;title&quot;).setValue(title_value);
newPost.child(&quot;desc&quot;).setValue(desc_value);
newPost.child(&quot;image&quot;).setValue(uri.toString());
Intent intent = new Intent(getApplicationContext(), blogupload.class);
startActivity(intent);
}
}

答案1

得分: 1

就我所看,问题出在你代码的这部分:

if(!TextUtils.isEmpty(title_value) && !TextUtils.isEmpty(desc_value) && uri!=null)
{
    StorageReference filepath=mStorage.child("blog_image").child(random());
    //向存储中添加图片

    filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
            Toast.makeText(getApplicationContext(),"已上传",Toast.LENGTH_SHORT).show();
        }
    });
}

DatabaseReference newPost=mDataBase.push();
//newPost.child("uid").setValue(mAuth.getCurrentUser().getUid());
newPost.child("title").setValue(title_value);
newPost.child("desc").setValue(desc_value);
newPost.child("image").setValue(uri.toString());

你传递给 filepath.putFile(uri)uri 是指向 Android 设备上本地路径的,你要上传到存储中的。然后你将这个 本地 路径写入了 newPost.child("image").setValue(uri.toString()) 中。但由于该路径只在 Android 设备上有效,在另一个设备上是无法工作的。

你需要获取已上传文件的下载 URL,并将其写入数据库。根据上传文件的文档,大致如下:

StorageReference filepath=mStorage.child("blog_image").child(random());
filepath.putFile(uri).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();
        }
        return filepath.getDownloadUrl();
    }
}).addOnSuccessListener(new OnSuccessListener<Uri>() {
    @Override
    public void onSuccess(Uri uri) {
        DatabaseReference newPost=mDataBase.push();
        newPost.child("title").setValue(title_value);
        newPost.child("desc").setValue(desc_value);
        newPost.child("image").setValue(uri.toString());
    }
});

需要注意的差异:

  • 写入数据库的代码现在位于 onSuccess 监听器内部,因为这在图片上传到存储后才被调用。
  • 我们现在调用了 getDownloadUrl 来确定下载 URL,这是一个指向云存储文件的 URL,任何人都可以使用它来访问文件数据。
  • 由于 getDownloadUrl 也是一个异步调用,我们使用了 continueWith 调用来链接异步任务。我们也可以将完成监听器嵌套,但这是文档中的做法。
英文:

As far as I can see, the problem is in this part of your code:

if(!TextUtils.isEmpty(title_value)  &amp;&amp;  !TextUtils.isEmpty(desc_value)  &amp;&amp;  uri!=null)
{
StorageReference filepath=mStorage.child(&quot;blog_image&quot;).child(random());
//adding a picture to storage
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener&lt;UploadTask.TaskSnapshot&gt;() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(getApplicationContext(),&quot;Uploaded&quot;,Toast.LENGTH_SHORT).show();
}
});
}
DatabaseReference newPost=mDataBase.push();
//newPost.child(&quot;uid&quot;).setValue(mAuth.getCurrentUser().getUid());
newPost.child(&quot;title&quot;).setValue(title_value);
newPost.child(&quot;desc&quot;).setValue(desc_value);
newPost.child(&quot;image&quot;).setValue(uri.toString());

The uri that you're passing to filepath.putFile(uri) is the path to a local locally on the Android device, that you are uploading to Storage. Then you write that local path to the database in newPost.child(&quot;image&quot;).setValue(uri.toString()). But since the path is local to the Android device, it won't work on another device.

You need to instead get the download URL of the uploaded file, and write that to the database. Based on the documentation on uploading a file, that'd be something like:


StorageReference filepath=mStorage.child(&quot;blog_image&quot;).child(random());
filepath.putFile(uri).continueWithTask(new Continuation&lt;UploadTask.TaskSnapshot, Task&lt;Uri&gt;&gt;() {
addOnSuccessListener(new OnSuccessListener&lt;UploadTask.TaskSnapshot&gt;() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(getApplicationContext(),&quot;Uploaded&quot;,Toast.LENGTH_SHORT).show();
return filepath.getDownloadUrl();
}
}).addOnSuccessListener(new OnSuccessListener&lt;Uri&gt;() {
@Override
public void OnSuccessListener(@NonNull Uri uri) {
DatabaseReference newPost=mDataBase.push();
newPost.child(&quot;title&quot;).setValue(title_value);
newPost.child(&quot;desc&quot;).setValue(desc_value);
newPost.child(&quot;image&quot;).setValue(uri.toString());
}
});

Differences to note:

  • The code that writes to the database is inside the onSuccess listener, since that gets called once the image has been uploaded to Storage.
  • We now have a call to getDownloadUrl to determine the download URL, which is a URL to the file in Cloud Storage that anyone can use to access its data.
  • Since getDownloadUrl is also an asynchronous call, we have a continueWith call to chain the asynchronous tasks. We could also have nested the completion listener, but this is what the documentation did.

huangapple
  • 本文由 发表于 2020年7月24日 19:22:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/63072553.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定