简体   繁体   中英

How to Display Firebase Storage Images in GridView

I am New to Android, I am learning about gridview . I want to display a list of images from drawables into a gridview but I don't know how to display images from Firebase Storage in a gridview .

I seen Many Tutorials and and I tried lot of Stackoverflow Answers but I cannot get what i need

I created a New Folder in Firebase Storage and i upload 6 images there and I want to display all the 6 images in gridview .

Here is My Code of how I display images From drawable and I don't know how to load that url and in glide I was totally confused and messed myself

public class NewListCreate extends BottomSheetDialogFragment {


   int[] images = {R.drawable.menu, R.drawable.musicbox, R.drawable.shoppingbag, R.drawable.shoppingcart, R.drawable.wallet, R.drawable.weddingdress};
    int imageRes = images[0];

  

    public NewListCreate() {
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.new_list_create, container, false);

        ImageButton done = view.findViewById(R.id.done);
        final EditText listname = (EditText) view.findViewById(R.id.listname);
        final GridView gridView = (GridView) view.findViewById(R.id.gridview);

        final CustomAdpter customAdpter = new CustomAdpter(images, getContext());
        gridView.setAdapter(customAdpter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                customAdpter.selectedImage = i;
                customAdpter.notifyDataSetChanged();
                imageRes = images[i];


            }
        });




        done.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                String itemname = listname.getText().toString();
                if (!TextUtils.isEmpty(listname.getText().toString())) {

                    startActivity(new Intent(getContext(), CheckslateHome.class).putExtra("data", itemname).putExtra("image", imageRes));
                    dismiss();
                } else {
                    Toast.makeText(getContext(), "List Name not Empty ", Toast.LENGTH_SHORT).show();
                }

            }

        });


        return view;


    }


    public class CustomAdpter extends BaseAdapter {

        public int selectedImage = 0;
        private int[] icons;
        private Context context;
        private LayoutInflater layoutInflater;

        public CustomAdpter(int[] icons, Context context) {
            this.icons = icons;
            this.context = context;
            this.layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return icons.length;
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {

            if (view == null) {
                view = layoutInflater.inflate(R.layout.image_list, viewGroup, false);

            }
            StorageReference storageReference = FirebaseStorage.getInstance().getReference();
            ImageView imageicons = view.findViewById(R.id.image);

            if (i < icons.length) {

                imageicons.setImageResource(icons[i]);

                if (i != selectedImage) {
                    imageicons.setImageAlpha(50);
                }
                imageicons.setScaleType(ImageView.ScaleType.CENTER_CROP);
                // imageicons.setLayoutParams(new GridView.LayoutParams(150, 150));
                if (i == selectedImage) {

                    view.setBackgroundColor(Color.WHITE);
                } else {
                    view.setBackgroundColor(Color.TRANSPARENT);
                }
            }
            ;


            return view;
        }
    }
}

Here is the firebase storage information

在此处输入图像描述

I've made a small and quick demo in my app with the following code and the result is this在此处输入图像描述

For gridAdappter I have this:

public class GridAdapter extends BaseAdapter {
Context context;
private final String[] values;
private final String[] images;
View view;
LayoutInflater layoutInflater;

public GridAdapter(Context context, String[] values, String[] images) {
    this.context = context;
    this.values = values;
    this.images = images;
}

@Override
public int getCount() {
    return values.length;
}

@Override
public Object getItem(int position) {
    return null;
}

@Override
public long getItemId(int position) {
    return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if(convertView==null)
    {
        view = new View(context);
        view=layoutInflater.inflate(R.layout.single_item,null);
        ImageView imageView = view.findViewById(R.id.imageView);
        TextView textView = view.findViewById(R.id.textView);
        Glide.with(context).load(images[position]).into(imageView);
        textView.setText(values[position]);
    }
    return view;
}

}

And for the activity where I have the GridView I've done this:

  gridView = findViewById(R.id.gridView) ;

   databaseReference = FirebaseDatabase.getInstance().getReference().child("Posts");
   databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
       @Override
       public void onDataChange(@NonNull DataSnapshot snapshot) {
           for(DataSnapshot dataSnapshot:snapshot.getChildren())
           {
               if(i<19)
               {
                   Post post = dataSnapshot.getValue(Post.class);
                   images[i]=post.getpImage();
                   values[i]=post.getpTitle();
                   i++;
               }
           }
           GridAdapter gridAdapter = new GridAdapter(getApplicationContext(),values,images);
           gridView.setAdapter(gridAdapter);
       }

       @Override
       public void onCancelled(@NonNull DatabaseError error) {

       }
   });

I have a reference to my Firebase Database to get the URLs for the pictures that I have stored on Firebase Storage and I use a class Post to get the information because it was easier and quicker for me.

You need to get the URL of your images and add them to the string array images and if you don't have set up a database with the URLs of your pictures stored then check this documentation to see how to get the URLs from your storage.

Here is how you could get the URL for one of your pictures from firebase storage

storageReference.child("icons/menu").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
        @Override
        public void onSuccess(Uri uri) {
            images[0] = String.valueOf(uri);
            values[0] = "menu"
          //Here you can also add thiss
         /*GridAdapter gridAdapter = new 
                      GridAdapter(getApplicationContext(),values,images);
       gridView.setAdapter(gridAdapter);*/

        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {

        }
    });

I have created a FirebaseUtils class, from within it I have a range of static firebase methods I can pick (no pun intended) from.
In order to achieve what you want, just create a loop then call the downloadPic method below

    for( int index = 0; index < noOfPhotos; index++ )
        FirebaseUtils.downloadPic( ivPic[index], "Photos/", image[index] );

ivPic is the image view
picToDisplay is the pic downloaded from storage
storageFolder is the folder on firebase eg: Photos/
picToDownload is the name of the pic within the storageFolder
noOfPhotos is the number of photos you have, obviously you can set up a query and load them into an ArrayList for convenience

    //////////////////////////////////////////////////////////////////////////////////

    private static void loadPicIntoGlide( @NonNull ImageView ivPic, 
                                          @NonNull String picToDisplay )
    {
        if( picToDisplay.isEmpty() )
        {
            Glide.with( ivPic.getContext() )
                    .load( R.mipmap.ic_default_pic )
                    .into( ivPic );
        }
        else
        {
            Glide.with( ivPic.getContext() )
                    .load( picToDisplay )
                    .into( ivPic );
        }
    }

    ///////////////////////////////////////////////////////////////////////////////////


    public static void downloadPic( @NonNull ImageView ivPicView,
                                    @NonNull String storageFolder,
                                    @NonNull String picToDownload )
    {
        StorageReference storageRef = FirebaseStorage.getInstance().getReference();
        Uri uri = Uri.fromFile( new File( picToDownload ) );
        StorageReference storageReference = storageRef.child( 
               storageFolder + picToDownload );

        storageReference.getDownloadUrl().addOnSuccessListener( 
                                                new OnSuccessListener<Uri>()
        {
            @Override
            public void onSuccess( Uri uri )
            {
                String actPic = uri.toString();
                loadPicIntoGlide( ivPicView, actPic );
            }
        } )
        .addOnFailureListener( new OnFailureListener()
        {
            @Override
            public void onFailure( @NonNull Exception e )
            {
                loadPicIntoGlide( ivPicView, "" );
            }
        } );
    }
public class CustomAdpter extends BaseAdapter {

FirebaseStorage firebaseStorage = FirebaseStorage.getInstance();    

private Context context;

public CustomAdapter(Context c) {
    context = c;
}

public int getCount() {
    return thumbId.length;
}

public Object getItem(int position) {
    return null;
}

public long getItemId(int position) {
    return 0;
}

// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
    ImageView imageView;
    if (convertView == null) {
        // if it's not recycled, initialize some attributes
        imageView = new ImageView(context);
        imageView.setLayoutParams(new GridView.LayoutParams(200, 200));
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setPadding(8, 8, 8, 8);
    } else {
        imageView = (ImageView) convertView;
    }

    imageView.setImageResource(thumbId [position]);




    return imageView;
}

// references to our images
public Integer[] thumbId = {

        R.drawable.sample_2, R.drawable.sample_3,
        R.drawable.sample_4, R.drawable.sample_5,
        R.drawable.sample_6, R.drawable.sample_7,
        R.drawable.sample_0, R.drawable.sample_1,
        R.drawable.sample_2, R.drawable.sample_3,
        R.drawable.sample_4, R.drawable.sample_5,
        R.drawable.sample_6, R.drawable.sample_7,
        R.drawable.sample_0, R.drawable.sample_1,
        R.drawable.sample_2, R.drawable.sample_3,
        R.drawable.sample_4, R.drawable.sample_5,
        R.drawable.sample_6, R.drawable.sample_7
};

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM