Question

I've followed this tutorial to get a gridview that displays images using a custom adapter: http://www.mkyong.com/android/android-gridview-example/

I've adapted the code to show the images when an nfc card is presented to the phone, however if I present the card multiple times, the images in the gridview are just replaced. I wanted it so that when the phone reads the nfc card again, it adds the images to the gridview, instead of just replacing them.

How can I achieve this?

                //If the NFC card contains the word "pic"           
            if(thePayloadText.equals("pic")){

                gridView = (GridView) findViewById(R.id.gridView1);

                gridView.setAdapter(new ImageAdapter(this, MOBILE_OS));
        }

            //If the NFC card contains the word "test"
            if(thePayloadText.equals("test")){

                gridView = (GridView) findViewById(R.id.gridView1);
                gridView.setAdapter(new ImageAdapter(this, PHOTOS));

            }
Était-ce utile?

La solution

The problem is setAdapter will clear all the previous items. So you need to avoid setAdapter when you add new items.

Instead you need to add the new item into the existing adapter.

If your custom adapter is ArrayAdapter, You can simply add like this

imageAdapter.add(yourObject); // imageAdapter is the instance you created first time when you setAdapter.

add() method with call notifyDataSetChanged to notify the `GridView' to refresh the UI.

If your custom adapter is BaseAdapter, then have a add() method in the Custom Adapter class and call it to add new items.

public void add(String[] newImages){
    // add the items to the previous array
    this.mobileValues.addAll(Arrays.asList(newItems));
    // notify the data changed
    notifyDataSetChanged();
}

Hope it helps you.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top