无法从Firebase数据库通过Picasso从URL加载图像 [英] Images not loading from URL by Picasso from Firebase Database
问题描述
模型类
public class Category
{
private String Name;
private String Image;
public Category(String name, String image) {
Name = name;
Image = image;
}
public Category() {
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getImage() {
return Image;
}
public void setImage(String image) {
Image = image;
}
}
活动类
public class Home extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
FirebaseDatabase database;
DatabaseReference reference;
FirebaseStorage storage;
StorageReference storageReference;
//Add new menu
MaterialEditText edtTxtName;
Button selectImage;
Button uploadImage;
//Adding new category
Category newCategory;
Uri savedImageUri;
private final int PICK_IMAGE_REQUEST=71;
MaterialEditText edtTxtNewCategoryName;
FloatingActionButton fab;
FirebaseRecyclerAdapter<Category,MenuViewHolder> recyclerAdapter;
TextView userName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
edtTxtNewCategoryName=findViewById(R.id.edt_txt_new_item_name);
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitle("Menu Mangement");
setSupportActionBar(toolbar);
fab =findViewById(R.id.fab);
//Firebase init
database=FirebaseDatabase.getInstance();
reference=database.getReference("Category");
storage=FirebaseStorage.getInstance();
storageReference=storage.getReference();
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showDailog();
}
});
DrawerLayout drawer =findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//Setting header name
/* View view=navigationView.getHeaderView(0);
userName = view.findViewById(R.id.username);
userName.setText(Common.currentUser.getName());*/
//View init
recyclerView=findViewById(R.id.recycler_menu);
layoutManager=new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
loadMenu();
}
private void selectImage() {
Intent intent=new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,PICK_IMAGE_REQUEST);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if(requestCode==PICK_IMAGE_REQUEST && resultCode==Activity.RESULT_OK
&& data!=null && data.getData()!=null)
{
savedImageUri=data.getData();//getting uri
selectImage.setText("Image Selected !");
}
}
private void uploadImage() {
final ProgressDialog progressDialog=new ProgressDialog(this);
progressDialog.setMessage("Uploading Image");
progressDialog.show();
String image= UUID.randomUUID().toString();
final StorageReference imageFolder=storageReference.child("images/"+image);
imageFolder.putFile(savedImageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(Home.this, "Uploaded", Toast.LENGTH_SHORT).show();
imageFolder.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>()
{
@Override
public void onSuccess(Uri uri)
{
newCategory=new Category(edtTxtName.getText().toString(),uri.toString());
Toast.makeText(Home.this, ""+uri.toString(), Toast.LENGTH_SHORT).show();
}
});
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(Home.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
@Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress=(100.0 * taskSnapshot.getBytesTransferred()
/ taskSnapshot.getTotalByteCount());
progressDialog.setMessage("Uploaded "+progress+" %");
}
});
}
private void showDailog() {
final AlertDialog.Builder alertDailog=new AlertDialog.Builder(this);
alertDailog.setTitle("Add new Category");
alertDailog.setMessage("Please fill all the fields");
LayoutInflater inflater=this.getLayoutInflater();
View view=inflater.inflate(R.layout.add_new_menu_layout,null);
edtTxtName=view.findViewById(R.id.edt_txt_new_item_name);
alertDailog.setView(view);
alertDailog.setIcon(R.drawable.ic_shopping_cart_black_24dp);
alertDailog.setPositiveButton("Add", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(newCategory!=null){
reference.push().setValue(newCategory);
}
}
});
alertDailog.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDailog.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDailog.show();
}
private void loadMenu()
{
recyclerAdapter=new FirebaseRecyclerAdapter<Category, MenuViewHolder>(
Category.class,R.layout.menu_layout,
MenuViewHolder.class,reference) {
@Override
protected void populateViewHolder(MenuViewHolder viewHolder, final Category model, int position)
{
viewHolder.menuName.setText(model.getName());
Picasso.get().load(model.getImage()).into(viewHolder.imageView);
viewHolder.setItemClickListner(new ItemClickListner() {
@Override
public void onClick(View view, int position, boolean isLongClick) {
//Getting menuId
Intent intent=new Intent(Home.this,FoodList.class);
intent.putExtra("CategoryId",recyclerAdapter.getRef(position).getKey());
startActivity(intent);
}
});
}
};
recyclerAdapter.notifyDataSetChanged();//notifiy us if data has been changed.
recyclerView.setAdapter(recyclerAdapter);
}
在活动类中,实现了firebase适配器.通过firebase数据库的刷新,仅以id为"-LO061DOhjG2hVZlqY79"的图像正在加载,但诸如"01","02"之类的id不在加载
In activity class,firebase adapter is implemented.by refrence of firebase database ,images are loading with only id "-LO061DOhjG2hVZlqY79" but with id's like '01' '02' are not loading
适配器加载图像的速度非常慢 此代码的输出
非常感谢您的帮助
推荐答案
代码中的问题在于,Category
类中的字段名称与数据库中的属性名称不同.您在Category
类中有一个名为Name
的字段,但是在数据库中,我将其视为name
,这是不正确的.名称必须匹配.当您使用名为getName()
的吸气剂时,Firebase会查找名为 name
而不是Name
的字段.看到小写的n
字母与大写字母N
?
The problem in your code lies in the fact that the name of the fields in your Category
class are different than the name of the properties in your database. You have in your Category
class a field named Name
but in your database I see it as name
and this is not correct. The names must match. When you are using a getter named getName()
, Firebase is looking for a field named name
and not Name
. See the lowercase n
letter vs. capital letter N
?
有两种方法可以解决此问题.第一个方法是根据 Java命名约定重命名字段来更改模型类.一个>.因此,您的模型类应如下所示:
There are two ways in which you can solve this problem. The first one would be to change your model class by renaming the fields according to the Java Naming Conventions. So you model class should look like this:
public class Category {
private String name, image;
public Category() {}
public Category(String name, String image) {
this.name = name;
this.image = image;
}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getImage() { return image; }
public void setImage(String image) { this.image = image; }
}
现在只需删除当前数据,然后使用正确的名称再次添加即可.仅当您处于测试阶段时,此解决方案才有效.
Now just remove the current data and add it again using the correct names. This solution will work only if you are in testing phase.
还有第二种方法,即使用annotations
.因为我看到您正在使用私有字段和公共获取程序,所以应该使用
There is also the second approach, which is to use annotations
. Because I see that you are using private fields and public getters, you should use the PropertyName annotation only in front of the getter. So your Category
class should look like this:
public class Category {
private String Name, Image;
public Category(String name, String image) {
Name = name;
Image = image;
}
public Category() { }
@PropertyName("name")
public String getName() { return Name; }
public void setName(String name) { Name = name; }
@PropertyName("image")
public String getImage() { return Image; }
public void setImage(String image) { Image = image; }
}
也不要忘记开始聆听更改.
Don't also forget to start listening for changes.
这篇关于无法从Firebase数据库通过Picasso从URL加载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!