来自 Firebase 数据库的 Picasso 未从 URL 加载图像 [英] Images not loading from URL by Picasso from Firebase Database

查看:20
本文介绍了来自 Firebase 数据库的 Picasso 未从 URL 加载图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Firebase 图像

<块引用>

模型类

 公共类类别{私人字符串名称;私人字符串图像;公共类别(字符串名称,字符串图像){姓名 = 姓名;图像 = 图像;}公共类别(){}公共字符串 getName() {返回名称;}公共无效集名称(字符串名称){姓名 = 姓名;}公共字符串 getImage() {返回图像;}public void setImage(String image) {图像 = 图像;}}

<块引用>

活动类

 公共类 Home 扩展 AppCompatActivity实现 NavigationView.OnNavigationItemSelectedListener {RecyclerView recyclerView;RecyclerView.LayoutManager layoutManager;FirebaseDatabase 数据库;数据库参考参考;FirebaseStorage 存储;存储参考存储参考;//添加新菜单MaterialEditText edtTxtName;按钮选择图像;按钮上传图片;//添加新类别类别新类别;Uri savedImageUri;私有最终 int PICK_IMAGE_REQUEST=71;MaterialEditText edtTxtNewCategoryName;FloatingActionButton fab;FirebaseRecyclerAdapter回收器适配器;文本视图用户名;@覆盖protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_home);edtTxtNewCategoryName=findViewById(R.id.edt_txt_new_item_name);工具栏工具栏 = findViewById(R.id.toolbar);toolbar.setTitle("菜单管理");setSupportActionBar(工具栏);fab =findViewById(R.id.fab);//Firebase 初始化数据库=FirebaseDatabase.getInstance();参考=database.getReference("类别");存储=FirebaseStorage.getInstance();storageReference=storage.getReference();fab.setOnClickListener(new View.OnClickListener() {@覆盖公共无效onClick(查看视图){showDailog();}});DrawerLayout drawer =findViewById(R.id.drawer_layout);ActionBarDrawerToggle 切换 = 新的 ActionBarDrawerToggle(这个,抽屉,工具栏,R.string.navigation_drawer_open,R.string.navigation_drawer_close);drawer.addDrawerListener(toggle);切换.syncState();NavigationView 导航视图 = findViewById(R.id.nav_view);navigationView.setNavigationItemSelectedListener(this);//设置标题名称/* 查看视图=navigationView.getHeaderView(0);userName = view.findViewById(R.id.username);userName.setText(Common.currentUser.getName());*///查看初始化recyclerView=findViewById(R.id.recycler_menu);layoutManager=new LinearLayoutManager(this);recyclerView.setLayoutManager(layoutManager);加载菜单();}私有无效选择图像(){意图意图=新意图();intent.setType("图像/*");意图.setAction(Intent.ACTION_GET_CONTENT);startActivityForResult(意图,PICK_IMAGE_REQUEST);}@覆盖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();//获取uriselectImage.setText("选中图片!");}}私有无效uploadImage(){final ProgressDialog progressDialog=new ProgressDialog(this);progressDialog.setMessage("上传图片");progressDialog.show();字符串图像= UUID.randomUUID().toString();final StorageReference imageFolder=storageReference.child("images/"+image);imageFolder.putFile(savedImageUri).addOnSuccessListener(new OnSuccessListener() {@覆盖public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {progressDialog.dismiss();Toast.makeText(Home.this, 上传", Toast.LENGTH_SHORT).show();imageFolder.getDownloadUrl().addOnSuccessListener(new OnSuccessListener(){@覆盖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() {@覆盖public void onFailure(@NonNull Exception e) {progressDialog.dismiss();Toast.makeText(Home.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();}}).addOnProgressListener(new OnProgressListener() {@覆盖public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {双进度=(100.0 * taskSnapshot.getBytesTransferred()/taskSnapshot.getTotalByteCount());progressDialog.setMessage("上传"+progress+" %");}});}私有无效 showDailog() {final AlertDialog.Builder alertDailog=new AlertDialog.Builder(this);alertDailog.setTitle("添加新类别");alertDailog.setMessage("请填写所有字段");LayoutInflater inflater=this.getLayoutInflater();查看 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() {@覆盖public void onClick(DialogInterface dialog, int which) {如果(新类别!=空){reference.push().setValue(newCategory);}}});alertDailog.setNegativeButton("No", new DialogInterface.OnClickListener() {@覆盖public void onClick(DialogInterface dialog, int which) {dialog.dismiss();}});alertDailog.setNeutralButton("Cancel", new DialogInterface.OnClickListener() {@覆盖public void onClick(DialogInterface dialog, int which) {dialog.dismiss();}});alertDailog.show();}私有无效 loadMenu(){recyclerAdapter=new FirebaseRecyclerAdapter(Category.class,R.layout.menu_layout,MenuViewHolder.class,reference) {@覆盖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() {@覆盖public void onClick(View view, int position, boolean isLongClick) {//获取菜单ID意图意图=新意图(Home.this,FoodList.class);intent.putExtra("CategoryId",recyclerAdapter.getRef(position).getKey());开始活动(意图);}});}};recyclerAdapter.notifyDataSetChanged();//如果数据发生变化,通知我们.recyclerView.setAdapter(recyclerAdapter);}

在活动类中,firebase 适配器是实现的.通过 firebase 数据库的引用,图像正在加载,只有 id "-LO061DOhjG2hVZlqY79" 但像 '01' '02' 这样的 id 没有加载

适配器加载图片的速度很慢此代码的输出

非常感谢您的帮助

解决方案

因为您使用的是私有字段和公共 getter 和 setter,所以 Category 类中的字段名称无关紧要.如果您想在类中使用与数据库中不同的名称,您可以使用名为 PropertyName 在 getter 前面.

<块引用>

图像正在加载唯一的 ID-LO061DOhjG2hVZlqY79"但是像'01''02'这样的id没有加载

正如我在您的屏幕截图中所见,第一个元素的图像"01"以手指食品"为名在 UI 中正确显示.因此,如果孩子有一个看起来像这样的密钥,0102-LO061DOhjG2hVZlqY79 都应该显示数据.事实上,它显示的是下一个项目的名称,西式汤".显示,因此问题很可能出在您的 URL 上.因此,请确保该 URL 确实存在并且包含有效的图像.

Firebase image

Model class

 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;
    }
}

Activity class

 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);
        }

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

Adapter is loading images very slow Output of this code

Help will highly appreciated

解决方案

Because you are using private fields and public getters and setters, the name of your fields in your Category class, doesn't matter. If you want to use different names in your class than in the database, you might use an annotation called PropertyName in front of the getter.

images are loading with the only id "-LO061DOhjG2hVZlqY79" but with id's like '01' '02' are not loading

As I see in your screenshot, the image of the first element "01" with the name "Finger Foods" is displayed correctly in the UI. So it doesn't matter if the children have a key that looks like this 01, 02, or -LO061DOhjG2hVZlqY79 the data should be displayed. As a matter of fact, it is displayed, the name of the next item, "Western Soups" is displayed, so most likely the problem is with your URL. So please make sure that the URL actually exists and has it contains a valid image.

这篇关于来自 Firebase 数据库的 Picasso 未从 URL 加载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆