Images not loading from URL by Picasso from Firebase Database

匆匆过客 提交于 2019-11-26 09:04:50

问题


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


回答1:


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?

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.

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.



来源:https://stackoverflow.com/questions/52670456/images-not-loading-from-url-by-picasso-from-firebase-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!