Michael Allen
Michael Allen

Reputation: 65

How to Create Object Array with For Loop in Android

I'm trying to create an array of objects with a for loop in Android. The array contains a string taken from a database and an image (for the ease of this I have kept the image to the same one throughout).

I started with the following (which does work):

ItemData[] itemsData = {
                new ItemData(dbString[0], R.mipmap.ic_launcher),
                new ItemData(dbString[1], R.mipmap.ic_launcher),
                new ItemData(dbString[2], R.mipmap.ic_launcher),
                new ItemData(dbString[3], R.mipmap.ic_launcher),
                new ItemData(dbString[4], R.mipmap.ic_launcher)
        };

I want to create the above within a for loop so that when the number of rows in the database changes then the number of objects created will increase without having to amend the code every time.

I have tried several different implementations and the closest I have got is the following (variable b is the number of rows in the database and dbString[i] is the "Name" field in the row):

ItemData[] itemsData = new ItemData[0];
for(int i = 0;i < b;i++) {
    ItemData[i] = new ItemData[]{
        new  ItemData(dbString[i], R.mipmap.ic_launcher)
    };
}

However this still does not work. The only error being bought up is that there is an expression expected at ItemData[i] on line 3 above.

ItemData is being passed to an adapter to then produce a recyclerview of cards.

I am fairly new to programming in general and have researched this issue but am coming up short with an answer that works.

Upvotes: 4

Views: 1585

Answers (1)

Nagaraju V
Nagaraju V

Reputation: 2757

Once try like this

ItemData[] itemsData = new ItemData[b];
for(int i = 0;i < b;i++) {
itemsData[i] = new  ItemData(dbString[i], R.mipmap.ic_launcher);
}

Hope this will helps you.

Upvotes: 2

Related Questions