Android GridView is not populated oncreate in activity


Ask by : Gabriela Radu November 06, 2012 20:31

Trying to get the data behind a specific position item from my created and populated gridView. Below listener method setOnItemClickListener() works well,but what i need is to get info on rendering the screen(gridview) not only on item click.

This is a snipped from my activity:

    ImageAdapter adapter = new ImageAdapter(LaunchActivity.this,
                myArray, elements);
        gridview.setAdapter(adapter);

        gridview.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v,
                    int position, long id) {

                ImageView iv = (ImageView) v.findViewById(R.id.icon_image);
                iv.setImageDrawable(getResources()
                        .getDrawable(R.drawable.drank));
                String name = elements[position].toString();
                System.out.println("===POSITION: " + position);
                if (dbHelper.getElementByPosition(position) == null) {
                    System.out.println("can insert");
                    dbHelper.addElement(new Beer(name, 1, position));
                } else {
                    System.out.println("already exists");
                }
            }
        });

        if (!elements.isEmpty()) {
            for (Element cn : elements) {
            Element item = (Element) gridview.getItemAtPosition(cn.getPosition());



                System.out.println(cn.getPosition() + ", ITEM: " + item);


}
        }

It keeps on returning null...:

[2012-11-04 01:33:46 - Emulator] I/System.out( 1771): 7, ITEM: null
[2012-11-04 01:33:46 - Emulator] I/System.out( 1771): 3, ITEM: null
[2012-11-04 01:33:46 - Emulator] I/System.out( 1771): 11, ITEM: null
[2012-11-04 01:33:47 - Emulator] I/System.out( 1771): 14, ITEM: null
[2012-11-04 01:33:47 - Emulator] I/System.out( 1771): 12, ITEM: null

I don't understand why i am getting this wrong... Maybe someone can spot my mistake or just an idea would be great. Thank you!

View original question

Answer by : SnicolasNovember 03, 2012 23:46

Your grid is not filled up yet by the adapter during onCreate. You have several possibilities. One of them is to use a delayed runnable in onStart for instance

 new Handler().runDelayed( Runnable, long ).

And inside this runnable, your grid will be filled.

Or better, register a datasetobserver on your adapter and you will know when your grid is filled.

View original answer