How to store drawable in an array - android

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 ?

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.

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);

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);

Related

How to change an ImageView with a filename

I have a string with the name of the file that I want (R.drawable.square) to put in the imageview.
String shape = "square"
I am trying to use the method below to show the image
imageView.setImageResource()
Hardcoding the filename in works but I want to be able to pass different filenames in.
image.setImageResource(R.drawable.square)
tl;dr
can't get from String:"square" to int:R.drawable.square
Please see Android, reference things in R.drawable. using variables?
//to retrieve image in res/drawable and set image in ImageView
String imageName = "picture"
int resID = getResources().getIdentifier(imageName, "drawable", "package.name");
ImageView image;
image.setImageResource(resID );
I achieved the effect by putting the images in the assets directory
I think it's better to use you Strings as key and your resource ids as value in a Map Object.
Map<String, Integer> resources = new HashMap<>();
resources.put("square", R.drawable.square);
// resources.put("...", R.drawable....);
imageView.setImageResource(resources.get("square"));

How to work with two different types of array in single adapter of grid view

Let me explain my question , I have a grid view which has to show images from resource folder i.e drawables and from device. So I have made int array for resources images and arraylist for my custom data type for images in device
Now what it looks like, the array of images from resources
public static Integer[] mThumbIds = {R.drawable.myImage_1, R.drawable.myImage, R.drawable.myImage,
R.drawable.myImage};
And array list of my custom data type.
static List<MyDetails> myData = new ArrayList<MyDetails>(myDb.GetAllData());
so in short as we know that images in the resources are deal as integers while images in my custom array list has a path of string , this is path which tells where the image is , on my device , so my picasso library gets the image from there
Now My problem is , I know how to show images from one single array ,
and how to set the respective adapter , but in this case I want to
show the images coming from my arraylist and also the images from my
resource folder.
Do you have any idea , how to achieve this ?
List all = new Arraylist(mThumbIds);
all.addAll(MyDetails);
getView(int i){
Object object = m.get(i);
if(object instanceof Integer){
//form resource;
int resid = (int)object;
}else if(object instanceof MyDetails){
//from db;
MyDetails mydetail = (MyDetails)object;
}
}

Access a image dynamically from res folder android

I have a image in res folder like this
I want to access this one dynamically like this
holder.Viewcover.setImageDrawable(Drawable.createFromPath("R.id." + CoverimgUrl.get(position)));
CoverimgUrl is a list which have two image name one is book_cover & and another is blank_image this array is generated dynamically so how can I set this image from that list
In One word how to access a image dynamically which is in drawable folder and I need get that image name from an array list ?
Resources res = getResources();
String mDrawableName = "image_name";
int resourceId = res.getIdentifier(mDrawableName , "drawable", getPackageName());
Drawable drawable = res.getDrawable(resourceId);
icon.setImageDrawable(drawable );
First Make CoverimgUrl list of integer
List<Integer> CoverimgUrl =new ArrayList<Integer>();
CoverimgUrl.add(R.drawable.book_cover);
CoverimgUrl.add(R.drawable.blank_image);
Then
holder.Viewcover.setImageResource(CoverimgUrl.get(position));
createFromPath expects a path to the file, not it's ID.
You can use the following:
int id = getResources().getIdentifier(CoverimgUrl.get(position), "id", getPackageName());
holder.Viewcover.setImageDrawable(getResources().getDrawable(id));
getIdentifier() gets the ID from the string. When you use the "R" class, it contains static integers for ids. So R.id.some_name is actually an integer, which is the id of the some_name resource.
once you get this integer with getIdentifier, you can use getResources().getDrawable() to get the drawable with the given ID.
Let me know if this works.

Android - Getting a list of drawable resource

In android you can access a resource with syntax like R..
what I want to do is to reach a set of images has naming convention.
for example I have 4 files in drawable with the names :
draw_1_.jpg
how can I get the list of drawable images to List ..
This is because, I want to make a slide show.
thx
I don't believe you can trust the resource compiler to give your images sequential integer values. In the past I've always created a static array to store these.
private static int[] imgs = { R.id.draw_1, R.id.draw_2, R.id.draw_3, R.id.draw_4 };
With this you can then have a section of code like:
int curSlide = 0;
view.setBackgroundResource(imgs[curSlide]);
Although it is an old question, I just had a similar problem recently. I liked solution of jeffd, but storing a list of images ids in code is not the best idea. So, I created an xml file with the list, which I put in res/xml directory.
<?xml version="1.0" encoding="utf-8"?>
<list>
<image id="#drawable/draw_1"/>
<image id="#drawable/draw_2"/>
<image id="#drawable/draw_3"/>
<image id="#drawable/draw_4"/>
</list>
Images are stored in drawable directory and are named draw_1.jpg, draw_2.jpg, etc.
Using this sort of xml has an advantage that availability of resources is checked at compile time, so if you have a typo, it won't compile.
Retrieving the list in code is simply parsing the xml, yet it's a bit verbose. XmlPullParser has method getAttributeResourceValue that allows getting resource id without dealing with any strings.
List<Integer> list = new ArrayList<>();
try {
while (parser.next() != XmlPullParser.END_DOCUMENT) {
if (parser.getEventType() == XmlPullParser.START_TAG &&
parser.getName().equals("image")) {
int imageId = -1;
for (int i = 0; i < parser.getAttributeCount(); ++i) {
if (parser.getAttributeName(i).equals("id")) {
list.add(parser.getAttributeResourceValue(i, -1));
}
}
}
}
}
catch (XmlPullParserException | IOException e) {
e.printStackTrace();
}
Another simpler solution would be using arrays as resources. I haven't tried this out, but you can see an example here: http://www.geeks.gallery/how-to-list-images-from-array-xml-in-android/ This is how to structure your xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<array name="list">
<item>#drawable/draw_1</item>
<item>#drawable/draw_2</item>
<item>#drawable/draw_3</item>
</array>
</resources>
To access the array you can use this code:
TypedArray list = getResources().obtainTypedArray(R.array.list);
for (int i = 0; i < list.length(); ++i) {
int id = list.getResourceId(i, -1);
}
well, if you know the suffix of the images, you can request the identifier for a drawable by getResources().getIdentifier(...) and then using the identifier get the drawable. So if you know how many images you have, then you can create a loop and store each of the drawables in a list. Just take into account that such a lookup is relatively expensive.
You Should identify all the Image as a Drawable .. and then you can use them as you can !

trying to use ArrayList to hold image resources

In my app, I have a bunch of images in my drawable folder which I select at random and display using imageView. I've been told about ArrayList's which can add/remove objects from the list...in order to prevent image repeats, some sample code I used below:
// create an array list
ArrayList imageHolder = new ArrayList();
int remaining = 10;
public void initArrayList(){
// add elements to the array list
imageHolder.add((int)R.drawable.child0);
imageHolder.add((int)R.drawable.child1);
imageHolder.add((int)R.drawable.child2);
imageHolder.add((int)R.drawable.child3);
imageHolder.add((int)R.drawable.child4);
imageHolder.add((int)R.drawable.child5);
imageHolder.add((int)R.drawable.child6);
imageHolder.add((int)R.drawable.child7);
imageHolder.add((int)R.drawable.child8);
imageHolder.add((int)R.drawable.child9);
}
//get random number within the current range
int randInt = new Random().nextInt((remaining-1));
//update the imageView config
ImageView image = (ImageView) findViewById(R.id.shuffleImageView);
image.setImageResource(imageHolder.get(randInt));
Eclipse reports that image.setImageResource cannot use an object argument, which is what is provided by arrayList. The actual argument should be int. Any clue how to get around this??
Thanks in advance!
Use List<Integer> imageHolder = new ArrayList<Integer>();
ArrayList contains Objects, always, never primitive types. When you set ints into it, they are autoboxed to Integer objects, when you get them back, you get Integer objects as well. A short fix will be:
image.setImageResource((int)imageHolder.get(randInt));
Be careful though, unboxing a null pointer will cause a NullPointerException, So make sure your randInt is in the range of the arraylist.
EDIT:
I totally missed that, but You initialize your ArrayList like that:
ArrayList imageHolder = new ArrayList();
Which creates ArrayList of Objects. instead, initialize the ArrayList like the following to create ArrayList of integers:
List<Integer> imageHolder = new ArrayList<Integer>();

Categories

Resources