17

How to count Total Number of List Items in a ListView ?

I am writing a Church Application in which i am populating list using images stored into SD Card, but now i want to count total number of list items.

     // to upload whole list
     for(int position = 0; position < lstView.getAdapter().getCount(); position++)
                 {
                     flags.put(position, true);   
                 }

                 ((BaseAdapter) lstView.getAdapter()).notifyDataSetChanged();        
            }
        });

        /*** Get Images from SDCard ***/
        listSDCardImages = fetchSDCardImages();

        // ListView and imageAdapter
        lstView = (ListView) findViewById(R.id.listSDCardImages);
        lstView.setAdapter(new ListSDCardImagesAdapter(this));

        Toast.makeText(getApplicationContext(), "Total number of Items are:" + String.valueOf(position), Toast.LENGTH_LONG).show();
        }

Everytime i am getting 0

Sophie
  • 2,384
  • 10
  • 39
  • 71

1 Answers1

43

Total list view count is

 lstView.getAdapter().getCount() ,

So use

Toast.makeText(getApplicationContext(), "Total number of Items are:" + lstView.getAdapter().getCount() , Toast.LENGTH_LONG).show();
Shayan Pourvatan
  • 11,622
  • 4
  • 39
  • 62
EminenT
  • 4,111
  • 2
  • 31
  • 50
  • thanks solved i did stupid mistake, may i know how to assign this value to String variable (to show in a TextView), and i will accept your answer after 5mins as per SO rule – Sophie May 17 '14 at 06:30
  • Yes, why not String count = ""+lstView.getAdapter().getCount(); textView.setText(count); – EminenT May 17 '14 at 06:31
  • In ListView i am using two different images in many list items using red circle and many list items using blue, so what i have to do if i want to count list items contains red circle and list items those contains blue circle, check this : http://pastebin.com/ENWcQSmM – Sophie May 17 '14 at 07:53
  • pastebin.com is not opening, please use other site – EminenT May 17 '14 at 07:56
  • I am using getView with holder: if(strExist) { holder.statusImageView.setImageResource(R.drawable.red); } else { holder.statusImageView.setImageResource(R.drawable.blue); } – Sophie May 17 '14 at 08:57
  • The correct way to parse numbers to String is String.valueOf(lstView.getAdapter().getCount()); – jpros May 17 '14 at 09:27
  • one simple of doing is : public int countRed = 0; public int countBlue = 0; @Override public View getView(int position, View convertView, ViewGroup parent) { // inflate view if(strExist) { holder.statusImageView.setImageResource(R.drawable.red); countRed++; } else { holder.statusImageView.setImageResource(R.drawable.blue); } countBlue++; } – EminenT May 18 '14 at 04:33