How to create an array of objects using Loop in Android

I am trying to create an array of objects with a for loop in Android. The array contains a string taken from the database and the image (for convenience, I saved the image in the same place).

I started with the following (which works):

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 in a for loop so that when the number of rows in the database changes, the number of objects created increases without the need to change the code every time.

I tried several different implementations, and the closest I got the following (the variable bis the number of rows in the database, and dbString[i]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 mistake I bought is that the line ItemData[i]contains the expression expected in line 3.

ItemData , .

, , .

+4
1

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

, .

+2

All Articles