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 !
Related
Hello I have added some images in drawable folder and after that I have refer that in strings.xml
Now I want to get dynamically the images so how I can do that, I found this code but for this code I need to give the id of image manually
this is strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="images">
<item>#drawable/one</item>
<item>#drawable/two</item>
<item>#drawable/three</item>
<item>#drawable/four</item>
<item>#drawable/five</item>
</string-array>
</resources>
and this is the java code
TypedArray images = getResources().obtainTypedArray(R.array.images);
images .getResourceId(i, -1)
mImgView1.setImageResource(imgs.getResourceId(i, -1));
imgs.recycle();
String names[] = getResources().getStringArray(R.array.fi);
for (String string : names) {
}
or
for(int i=0; i<names.length ;i++){
}
Like this you can access all the elements in the array
i have some consecutive elements id declared inside R.java files. Now i need to fill each one by using a for cycle, so i need to increment for each iteration value of id. I've write this:
int current_id = R.id.button00;
for (int i = 0; i < values.length; i++) {
TextView to_fill = (TextView) (getActivity().findViewById(current_id));
to_fill.setText(String.valueOf(values[i]));
current_id++;
}
but in this way current_id doesn't increment correctly.
How can i do?
There is no guarantee that the generated IDs in R will be sequential, or that they will be generated in any particular order.
I recommend putting your IDs in an array resource like so:
<array name="button_id_array">
<item>#id/button00</item>
<item>#id/button01</item>
<item>#id/button02</item>
</array>
Then you can access it in code like so:
int[] ids = getResources().getIntArray(R.array.test);
I am using Arraylist of strings:
ArrayList entries = new ArrayList(Arrays.asList(""));
and giving values dynamically. It may contain the names of Directories or Files.
I need to show entries in ListView such that, first all directories are shown in sort order then files in sort order.
Is this possible? if yes, any hint? Appreciate the help.. I am using
Collections.sort(entries);
to sort my entries.
Use the 2 parameter version with a custom comparator. Compare it such that:
boolean firstFileIsDirectory = file1.isDirectory();
boolean secondFileIsDirectory = file2.isDirectory();
if(firstFileIsDirectory && !secondFileIsDirectory){
return -1;
}
if(!firstFileIsDirectory && secondFileIsDirectory){
return 1;
}
return String.compare(filename1, filename2);
I have done it. Logic used: separate the entries into two ArrayList. One having directories other files. Sort these two ArrayLists separately. Finally add these two to "entries". Here is the code:
private void sortEntries(String path){
ArrayList<String> entriesDir = new ArrayList<String>(Arrays.asList(""));
ArrayList<String> entriesFile = new ArrayList<String>(Arrays.asList(""));
entriesDir.removeAll(entriesDir);
entriesFile.removeAll(entriesFile);
int fileCounter=0, dirCounter=0;
path = path.equals("/") ? "" : path;
for(int i=1;i<=entries.size();i++){
if((new File(path+"/"+entries.get(i-1))).isFile()) entriesFile.add(fileCounter++, entries.get(i-1));
else entriesDir.add(dirCounter++, entries.get(i-1));
}
Collections.sort(entriesDir,String.CASE_INSENSITIVE_ORDER);
Collections.sort(entriesFile,String.CASE_INSENSITIVE_ORDER);
entries.removeAll(entries);
entries.addAll(entriesDir);
entries.addAll(entriesFile);
}
I created an application that uses the TTS engine to send feedback to the user. With the aim to improve the performance, I used the synthesizeToFile and addSpeech methods, but strings of text to be synthesized are inside the strings.xml file, so I have to invoke these methods for each string that is spoken by the TTS engine.
Since the TTS engine uses only strings whose name begins with tts_, is it possible to easily iterate over all strings that begin with tts_ within the strings.xml file?
You can get all the strings in strings.xml via reflection, and filter out only the ones you need, like so:
for (Field field : R.string.class.getDeclaredFields())
{
if (Modifier.isStatic(field.getModifiers()) && !Modifier.isPrivate(field.getModifiers()) && field.getType().equals(int.class))
{
try
{
if (field.getName().startsWith("tts_"))
{
int id = field.getInt(null);
// do something here...
}
} catch (IllegalArgumentException e)
{
// ignore
} catch (IllegalAccessException e)
{
// ignore
}
}
}
You can give them all (while defining) the resource name as "prefix"+(1..n). And in the code use,
int resid=<constant>;
for(i=1;resid!=0;i++){
resid = this.getResources().getIdentifier("prefix"+i, "strings", this.getPackageName());
}
You could put these TTS strings into a TypedArray.
you can use this code:
String[] strings = getResources().getAssets().list("string");
for (int i = 0; i < strings.length; i++) {
Log.d("aaa ", strings[i]);
}
to iterate through other resources like fonts,... just replace string with folder name.
In all my projects, i just observed that the value of strings in R.java starts with 0x7f050000 and it counts upwards, like 0x7f050001, 0x7f050002, 0x7f050003,....
You could just ++ them :D
Hope it helps :)
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);