I have a lot of SVG images, currently transformed into XML code, stored into the drawable/
directory. I am using the following code to retrieve them all and randomly display one of them:
Field[] ID_Fields = R.drawable.class.getFields();
int[] resArray = new int[ID_Fields.length];
for (int i = 0; i < ID_Fields.length; i++)
{
try
{
resArray[i] = ID_Fields[i].getInt(null);
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
}
Random r = new Random();
int i1 = r.nextInt(ID_Fields.length - 1);
Log.i("TAG", "Selected index: " + i1);
Drawable drawable = ContextCompat.getDrawable(context, resArray[i1]);
imageView.setImageDrawable(drawable);
This works fine - even if all drawables are loaded, so a mechanism to separate my custom images must be implemented - and the chosen image is correctly displayed into the imageView
.
I would like to change my structure and put my XMLs into the assets/flags/
folder. However, when I use the following code, the returned drawable is always null
:
AssetManager am = getApplicationContext().getAssets();
String[] files = new String[0];
try
{
files = am.list("flags");
}
catch (IOException e)
{
e.printStackTrace();
}
ArrayList<Drawable> drawables = new ArrayList<>();
for (String file : files)
{
Drawable d = null;
try
{
d = Drawable.createFromStream(am.open("flags/" + file), null);
}
catch (IOException e)
{
Log.i("EX2", "Second exception: " + file + " not found");
e.printStackTrace();
}
drawables.add(d);
if (d == null)
Log.i("FLAG", "Null drawable");
}
Random r = new Random();
int i1 = r.nextInt(drawables.size() - 1);
Log.i("TAG", "Selected index: " + i1);
Drawable drawable = drawables.get(i1);
imageView.setImageDrawable(drawable);
Why does this happen?