Search code examples
javaandroidgridviewandroid-resourcesresource-id

Android : Custom object can't preserve resource ID


App shows images in a Gridview. In the adapter of GridView, I generate # of images reqd randomly from the resources available. A new Integer[] imageIDs is created & those resource IDs are saved in this new array. I also want to store this resourceID in an ArrayList of custom object ImageSourceObject that extends ImageView. I set the imageView using imgObj.setImageResource(imageIDs[i]). Now when I retrieve this object in onTouch() or getView() methods I expect to get the same resource of the imageView set, whereas I get -1.

I think that when I am setting the ImageView of ImageSourceObject thru setImageResource(), then when I try to retrieve the getId() of ImageSourceObject I should get the id of the ImageView set.

Code :

    private void createObjectsArray() {
    int totalObjs = 15;
    Integer[] mThumbIds = {
            R.drawable.droid_1, R.drawable.droid_3,
            R.drawable.droid_2, R.drawable.ic_launcher
    };
    // Create new [] for imageIDs to store the resource ID as generated    
    imageIds = new Integer[totalObjs];
    // Create ArrayList of ImageSourceObject to set image & other proeprties 
    this.imgObjsArr = new ArrayList<ImageSourceObject>();

    Random random = new Random();
    int index;
    // Set Targets 
    for (int i=0; i < totalObjs; i++) {
        index = this.generateRandomNumber(0, (mThumbIds.length - 1), random);
        imageIds[i] = mThumbIds[index];
        ImageSourceObject iso = new ImageSourceObject(mContext);
        iso.setImageResource(imageIds[i]);
        imgObjsArr.add(iso);

        Log.d("GA", "ThumbIDS ID : " + mThumbIds[index] + " ImageIDs  : " + imageIds[i] + " ISO IMG ID : " + iso.getId());
    }
}

Log of this code :

02-19 12:21:38.780: D/GA(1613): ThumbIDS ID : 2130837557 ImageIDs  : 2130837557 ISO IMG ID : -1

You can see the IDs of mThumbIDs & imageIDs values are the same. But for iso object after setting the image also it is -1 ??

Code of ImageSourceObject is quiet simple :

public class ImageSourceObject extends ImageView {

private boolean touched;
private boolean targetObj;

public ImageSourceObject(Context context) {
    super(context);
    setTouched(false);
    setTargetObj(false); 
}

 .... Rest Getter & Setter methods

Can you help me know why is the resource ID not being set in ImageSourceObject ? Doesn't setting image thru setImageResource of ImageView save it with it's all resources ???

Any help is highly appreciated.

Thanks


Solution

  • The id you gave is for the Image you populate to your ImageSourceObject (the Drawable), it is not of the ImageSourceObject itself. if you want to set the id to be this number, you should do:

            iso.setImageResource(imageIds[i]);
            iso.setId(imageIds[i]);