How to write an array which stores the images from

2019-08-08 15:10发布

问题:

Can i know what did i do wrong? i just wanna get my images from drawable folder and pass it to my adapter to display on my gridView.. But i dont know how to add inside the array.. The error message is at the line

arrImages[i] = this.getResources().getIdentifier(wd.getName(), "drawable", this.getPackageName());

Anybody wants to help me :( I wanna load it dynamically according to the names in my database.. the database name (wd.getName()) is the same as my file name.png

Declare at the top :

    int arrImages [] = {};

Inside onCreate :

    int i = 0;
    for (Words wd : words)
    {

        String log = "Id: " + wd.getId() + " ,Name: " + wd.getName();
        // Writing Contacts to log
        Log.d("wordList : ", log);

        arrImages[i] = this.getResources().getIdentifier(wd.getName(), "drawable", this.getPackageName());

        i++;
    }

回答1:

// references to our images

private Integer[] mThumbIds = {
        R.drawable.sample_2, R.drawable.sample_3,
        R.drawable.sample_4, R.drawable.sample_5,
        R.drawable.sample_6, R.drawable.sample_7,
        R.drawable.sample_0, R.drawable.sample_1,
        R.drawable.sample_2, R.drawable.sample_3,
        R.drawable.sample_4, R.drawable.sample_5,
        R.drawable.sample_6, R.drawable.sample_7
};

Here is the array of your images in drawable folder. Now use this array in the array adapter of grid view. This is the easy method. For more understanding please visit this link

http://www.compiletimeerror.com/2013/02/display-images-in-gridview.html#.VekddOSqrCY



回答2:

I've done it using dynamic way.

Implementing new array list :

ArrayList<Integer> arrImages = new ArrayList<>();

Then I can store all my images dynamically inside.

This is the looping from my database, adding the resource id from drawable folder to my array :

for (Words wd : words)
    {
        String log = "Id: " + wd.getId() + " ,Name: " + wd.getName() ;
        // Writing Contacts to log
        Log.d("wordList : ", log);

        arrImages.add( this.getResources().getIdentifier(wd.getName(), "drawable", this.getPackageName()));

    }