How to store drawable in an array

穿精又带淫゛_ 提交于 2019-12-11 08:35:43

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!