在Firebase数据库查询中重复的图像

时间:2018-07-07 10:52:55

标签: java android firebase-realtime-database

在我的CardStackFragment.java中,我有一个查询,该查询从Firebase实时数据库中检索5张随机图像。 这是我用来检索它们的代码:

final DatabaseReference countriesRef = mDatabase.child("paises");
    final ValueEventListener valueEventListener = new ValueEventListener()
    {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot)
        {
            countriesRef.removeEventListener(this);
            List<String> urlList = new ArrayList<>();
            List<String> nomePaisList = new ArrayList<>();
            for(DataSnapshot ds : dataSnapshot.getChildren())
            {
                String url = ds.child("Imagem").getValue(String.class); 
                String nomePais = ds.child("Nome").getValue(String.class); 
                urlList.add(url); // Adiciona as imagens à lista
                nomePaisList.add(nomePais); // Adiciona os nomes à lista
            }

            int urlCount = urlList.size();

            int randomNumber = new Random().nextInt(urlCount);

            final List<String> randomUrlList = new ArrayList<>(); 
            final List<String> randomNomePaisList = new ArrayList<>(); 


            for (int i=0; i<=Constants.TOTAL_PAISES; i++)
            {
                randomUrlList.add(urlList.get(randomNumber)); 
                randomNomePaisList.add(nomePaisList.get(randomNumber)); 

                    Picasso.with(getContext()).load(randomUrlList.get(i)).into(imgFotoPais); 
                txtPaisNome.setText(randomNomePaisList.get(i)); 
                final int temp_i = i;
 imgFotoPais.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
                        SharedPreferences.Editor editor;
                        editor = getActivity().getSharedPreferences("FotoPaisCardParaInfo", MODE_PRIVATE).edit();
                        editor.putString("fotoPaisCard", randomUrlList.get(temp_i));
                        editor.putString("nomePaisCard",randomNomePaisList.get(temp_i));
                        editor.commit();


                        Intent intentIntro = new Intent(getActivity(), CountryInfoActivity.class); // Cria o intent "intentIntro"
                        startActivity(intentIntro); // Inicia a atividade IntroActivity
                        getActivity().overridePendingTransition(R.anim.slide_up_info, R.anim.nothing);
                    }
                });

工作正常。每次重新加载时,它都会显示不同的随机图像,问题是这些图像可以重复。 例如,如果我有10张图像,它可能显示: 1、3、7、1、9 如何确保图像不会重复出现?

更新 由于没有人回答我,并且从现在起几个小时后我提出了这个问题,我将尝试通过一个简单的gif来说明正在发生的事情:

[![在此处输入图片描述] [1]] [1]

如您所见,葡萄牙正在两次演出...这在每个国家都可能发生...有人可以帮助我吗?

更新 这些是90-100行

  if(!randomUrlList.contains(urlList.get(randomNumber))) {
                    randomUrlList.add(urlList.get(randomNumber)); // Guarda um valor ao calhas de um país
                    randomNomePaisList.add(nomePaisList.get(randomNumber)); // Guarda o nome referente à imagem que foi sorteada
                }

                if(randomUrlList.get(i) != null){
                Picasso.with(getContext()).load(randomUrlList.get(i)).into(imgFotoPais); // Inserir na ImageView a imagem do respetivo país


                    txtPaisNome.setText(randomNomePaisList.get(i)); // Inserir na TextView o nome do respetivo país

这是我的 LOGCAT https://pastebin.com/REeBpAA5

这是我的适配器

类CardStackAdapter扩展FragmentStatePagerAdapter {

public CardStackAdapter(FragmentManager fm){
    super(fm);
}

@Override
public Fragment getItem(int position) { return new CardStackFragment(); }

@Override
public int getCount() { return 5; }

}

2 个答案:

答案 0 :(得分:0)

检查列表,然后再输入数据,如:

if(!urlList.contains(url)){
    urlList.add(url); // Adiciona as imagens à lista
    nomePaisList.add(nomePais); // Adiciona os nomes à lista
}

希望有帮助

答案 1 :(得分:0)

    //model class => photos
    public class Photos{

       private String Imagem;
       private Stirng Nome;

       //now make constructors
       //and getters and setters

    }

    //now in your CardStackFragment.java change the data initialization method to this

    //init arraylist outside
    private ArrayList<Photos> photosArray;

    //now that's how you have to fetch data
    DatabaseReference countriesRef = mDatabase.child("paises");
    countriesRef .addValueEventListener(new ValueEventListener() {
       @Override
       public void onDataChange(DataSnapshot dataSnapShot) {
          for(DataSnapshot ds : dataSnapshot.getChildren()){
             Photos mPhotos = ds.getValue(Photos.class);
             //check if the value already exist in the array
             if(!photosArray.contains(mPhotos)){
                 photosArray.add(mPhotos);
             }
          }
          //now let's render the data in the views
          //array of images to be used
          ArrayList<Photos> toBeUsed = new ArrayList();
          for (int i=0; i<=Constants.TOTAL_PAISES; i++){
                //now check if the image is already added to the array of to be used images
                if(!toBeUsed.contains(photosArray.get(randomNumber))){
                   toBeUsed.add(mPhotos);
                }
                Picasso.with(getContext()).load(toBeUsed.get(i).getImagem).into(imgFotoPais); 
                txtPaisNome.setText(toBeUsed.get(i).getNome);
          }
       }
       @Override
       public void onCancelled(DatabaseError databaseError) {
          //log the error
          Log.e("error in data fetching", databaseError.toString());
       }
    });



//now if you dont want to change your code
//then all you are required to check if the url has been added to randomUrlList
//so before adding the url and name do something like this

//your code

randomUrlList.add(urlList.get(randomNumber)); 
randomNomePaisList.add(nomePaisList.get(randomNumber));

//change it to

if(!randomUrlList.contains(urlList.get(randomNumber))){
   randomUrlList.add(urlList.get(randomNumber)); 
   randomNomePaisList.add(nomePaisList.get(randomNumber));
}


//thats it
//this time it's gonig to work for sure