简体   繁体   English

如何在GridView中显示Firebase存储镜像

[英]How to Display Firebase Storage Images in GridView

I am New to Android, I am learning about gridview .我是 Android 的新手,我正在学习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 .我想将可绘制对象中的图像列表显示到gridview ,但我不知道如何在 gridview 中显示来自gridview存储的图像。

I seen Many Tutorials and and I tried lot of Stackoverflow Answers but I cannot get what i need我看了很多教程,并且尝试了很多 Stackoverflow 答案,但我无法得到我需要的

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 .我在 Firebase 存储中创建了一个新文件夹,我在那里上传了 6 张图像,我想显示gridview中的所有 6 张图像。

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这是我如何显示可绘制图像的代码,我不知道如何加载 url 并且在滑行中我完全困惑并弄乱了自己

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这里是firebase的存储信息

在此处输入图像描述

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:对于 gridAdappter 我有这个:

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的活动,我这样做了:

  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.我有一个对我的 Firebase 数据库的引用,以获取我存储在 Firebase 存储中的图片的 URL,我使用 class Post来获取信息,因为它对我来说更容易和更快。

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.您需要获取图像的 URL 并将它们添加到字符串数组图像中,如果您没有设置存储图片 URL 的数据库,请查看文档以了解如何从存储中获取 URL。

Here is how you could get the URL for one of your pictures from firebase storage以下是如何从 firebase 存储中为您的一张照片获取 URL

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.我创建了一个FirebaseUtils class,从中我可以从中选择 static firebase 方法(没有双关语意)。
In order to achieve what you want, just create a loop then call the downloadPic method below为了实现你想要的,只需创建一个循环然后调用下面的 downloadPic 方法

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

ivPic is the image view ivPic是图像视图
picToDisplay is the pic downloaded from storage picToDisplay是从存储中下载的图片
storageFolder is the folder on firebase eg: Photos/ storageFolder是 firebase 上的文件夹 eg: Photos/
picToDownload is the name of the pic within the storageFolder picToDownloadstorageFolder中图片的名称
noOfPhotos is the number of photos you have, obviously you can set up a query and load them into an ArrayList for convenience noOfPhotos是您拥有的照片数量,显然您可以设置查询并将它们加载到ArrayList中以方便使用

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

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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