问题
I want to download a bunch of images and would like to store it as drawable in an array. So I tried declaring a drawable array.But it returns me nullPointer
exception when I access that array.
My question is, how to declare an array type as drawable ?
回答1:
an array of drawables would be declared like:
int numDrawables = 10;
Drawable[] drawableArray = new Drawable[numDrawables];
to fill the array:
for(int i = 0; i < numDrawables; i++){
// get a drawable from somewhere
Drawable drawable = new Drawable();
drawableArray[i] = drawable;
}
to access the array:
Drawable aDrawable = drawableArray[0];
This is basic java, If you are getting null pointer exceptions, you are doing something wrong.
回答2:
you can use an hashMap , and put the keys as urls for example , and to value is the drawable that you download :
HashMap<String,Drawable> myDrawables = new HashMap<String,Drawable>();
//before you download the images, you can test if your drawable is already downloaded,
// with looking for his url in the Hashmap ,
.....
myDrawables.put(urlOfYourDrawable, yourDrawable);
回答3:
If you want to store list of elements(any type) dynamically use the classes in the collection. why because Array size is static. Example:
ArrayList<Generic> list=new ArrayList<Generic>();
list.add(Generic);
来源:https://stackoverflow.com/questions/6213444/how-to-store-drawable-in-an-array