问题是我无法刷新我的gridView
,当我在 Firestore 中进行更改时,我的 gridView 不会清除,只是从 Firestore 添加新值(图像)。我尝试了很多可以在“stackoverflow”上找到的方法,但没有成功。也许问题ImageAdapter
出在我的称呼addSnapshotListener
上,我真的不知道。现在我只想在数据更改时刷新我的gridView Firestore
,但在最好的情况下,我希望当我从中获取新值时Firestore
,它只更新gridView的图像所在的部分,而不是整个gridView
.
public class MainActivity extends AppCompatActivity {
private FirebaseFirestore db;
private ArrayList<Items> arrayList;
private ImageAdapter imageAdapter;
private GridView gridView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridView = findViewById(R.id.gridViewList);
db = FirebaseFirestore.getInstance();
arrayList = new ArrayList<>();
//arrayList.clear();
getUrls();
imageAdapter = new ImageAdapter(MainActivity.this, arrayList);
gridView.setAdapter(imageAdapter);
}
private void getUrls(){
gridView.setAdapter(null);
db.collection("images").addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(QuerySnapshot value, FirebaseFirestoreException e) {
if (e != null){
Toast.makeText(getApplicationContext(), "No images returned", Toast.LENGTH_SHORT).show();
return;
}
for (DocumentSnapshot document : value){
refresh();
if (document.get("imageUrl") != null){
arrayList.add(new Items(document.get("imageUrl").toString()));
refresh();
}
}
}
});
}
public void refresh() {
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
imageAdapter.notifyDataSetChanged();
gridView.invalidate();
}
});
}
public class ImageAdapter extends BaseAdapter {
private ImageView imageView;
private Context context;
private LayoutInflater inflater;
private ArrayList<Items> list;
public ImageAdapter(Context context, ArrayList<Items> list){
this.context = context;
this.list = list;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null){
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.image_layout, parent, false);
imageView = convertView.findViewById(R.id.singleImageView);
}
/** https://futurestud.io/tutorials/glide-caching-basics */
Glide.with(context).load(list.get(position).getImageUrl()).apply(RequestOptions.skipMemoryCacheOf(true).centerCrop()).into(imageView);
return convertView;
}