How to use a String as a resource ID [closed] - android

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
*Update - solved**
What I was looking for was how to get the Resource ID. It's difficult to formulate a question when you don't know what you don't know, but the two guys that answered it within a matter of minutes seemed to understand. Thanks, guys.
Here is the code I was finally able to use without having to load all 32 bitmaps while using a String to identify which specific one I was after.
StartCalc session = new StartCalc(context);
int findDate = session.findDate();
for (int i = 0; i < daysTil.length; i++) {
String numbers = "numbers" + i;
int resId = getResources().getIdentifier(numbers, "drawable", getPackageName());
if (i == findDate) {
ivNumbers.setImageBitmap(BitmapFactory.decodeResource(getResources(), resId));
}
}
*Original question**
I'm trying to use a for loop to fill an array of Bitmaps, from 0 to 32, but I can't figure out how to use the String "numbers" (identified on line 3) to populate the address required by the BitmapFactory (referenced on line 5). Here's the code of me filling the array two ways. The long way has issues taking up too much memory, and since I only need one of these images based on the date, I'm hoping there's a way to do this.
private void setNumbers() {
for (int i = 0; i < 33; i++) {
String numbers = "R.drawable.numbers" + i;
Log.e(TAG, numbers);
daysTil[i] = BitmapFactory.decodeResource(getResources(), numbers);
}
daysTil[0] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers0);
daysTil[1] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers1);
daysTil[2] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers2);
daysTil[3] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers3);
daysTil[4] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers4);
daysTil[5] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers5);
daysTil[6] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers6);
daysTil[7] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers7);
daysTil[8] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers8);
daysTil[9] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers9);
daysTil[10] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers10);
daysTil[11] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers11);
daysTil[12] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers12);
daysTil[13] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers13);
daysTil[14] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers14);
daysTil[15] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers15);
daysTil[16] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers16);
daysTil[17] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers17);
daysTil[18] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers18);
daysTil[19] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers19);
daysTil[20] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers20);
daysTil[21] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers21);
daysTil[22] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers22);
daysTil[23] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers23);
daysTil[24] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers24);
daysTil[25] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers25);
daysTil[26] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers26);
daysTil[27] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers27);
daysTil[28] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers28);
daysTil[29] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers29);
daysTil[30] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers30);
daysTil[31] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers31);
daysTil[32] = BitmapFactory.decodeResource(getResources(), R.drawable.numbers32);
}

You should use this method to find the resource id of the drawable:
String numbers = "numbers" + i;
int resId = getResources().getIdentifier(numbers, "drawable", getPackageName());
Reference: getIdentifier

The Resources class has this method:
public int getIdentifier (String name, String defType, String defPackage)
So the complete statement could look somewhat like this:
for (int i = 0; i < 33; i++) {
String numbers = "R.drawable.numbers" + i;
Log.e(TAG, numbers);
Resources resources = <context>.getResources();
daysTil[i] = BitmapFactory.decodeResource(getResources(),
resources.getIdentifier ("numbers" +i, "drawable",
<context>.getPackageName());
}
(note: this code is untested - it's just for demonstration)

Related

How to create a Dynamic decodeResource?

I want to create a dynamic decodeResource to use very images in the object.
This is my code:
for(int i=42; i<55; i++) {
bitmap = BitmapFactory.decodeResource(context.getResources(),
Integer.parseInt("R.drawable.a"+i));
}
I want to get the files
R.drawable.a43 to a54
Its possible to create a loop for decodeResource?
To retrieve the resource ID for 'R.drawable.a##' dynamically we can use Resources.getIdentifier as follows:
final String pkg = context.getPackageName();
final Resources resources = context.getResources();
...
int num = ...; /* between 43 and 54 */
final int id = resources.getIdentifier("a" + num, "drawable", pkg);
You can store these in a List using a loop much like the one you have now, only with slightly modified bounds:
final String pkg = context.getPackageName();
final Resources resources = context.getResources();
final List<Bitmap> bitmaps = new ArrayList<Bitmap>();
for (int i = 43; i <= 54; ++i) {
/* decode bitmap with id R.drawable.a{i} */
final Bitmap bitmap = BitmapFactory.decodeResource(resources,
resources.getIdentifier("a" + i, "drawable", pkg));
bitmaps.add(bitmap);
}
/* now bitmaps contains the Bitmaps */

Images getting as too noise when applying filters in Android

I am developing an application which includes filters and crop too. Here I am using cropping library. Here I used 8*8 luts like sample lut. Here I want to CROP the filtered image(8*8 lut)
Here is the logic to crop the image.
Bitmap cropbitmap = ivCropimageView.getCroppedImage();
Using this bitmap I generate a thumbnail bitmap like below.
Bitmap thumbImage = ThumbnailUtils.extractThumbnail(cropbitmap, 190, 250);
When I am trying to generate thumbnails for all filters then the thumbnails are displaying as too noise like this.
This result is when I implemented the answer from renderscript.
So if anyone has ab idea please help me..
I'm working on a LUT applier library which eases the use of LUT images in Android. Now it also guesses the color axes of the LUT:
https://github.com/dntks/easyLUT/wiki
It uses the algorythm I mentioned in the other post
u can go through this, hope it will help you to get the right process.
photo is the main bitmap here.
mLut3D is the array of LUT images stored in drawable
RenderScript mRs;
Bitmap mLutBitmap, mBitmap;
ScriptIntrinsic3DLUT mScriptlut;
Bitmap mOutputBitmap;
Allocation mAllocIn;
Allocation mAllocOut;
Allocation mAllocCube;
int mFilter = 0;
mRs = RenderScript.create(yourActivity.this);
public Bitmap filterapply() {
int redDim, greenDim, blueDim;
int w, h;
int[] lut;
if (mScriptlut == null) {
mScriptlut = ScriptIntrinsic3DLUT.create(mRs, Element.U8_4(mRs));
}
if (mBitmap == null) {
mBitmap = photo;
}
mOutputBitmap = Bitmap.createBitmap(mBitmap.getWidth(),
mBitmap.getHeight(), mBitmap.getConfig());
mAllocIn = Allocation.createFromBitmap(mRs, mBitmap);
mAllocOut = Allocation.createFromBitmap(mRs, mOutputBitmap);
// }
mLutBitmap = BitmapFactory.decodeResource(getResources(),
mLut3D[mFilter]);
w = mLutBitmap.getWidth();
h = mLutBitmap.getHeight();
redDim = w / h;
greenDim = redDim;
blueDim = redDim;
int[] pixels = new int[w * h];
lut = new int[w * h];
mLutBitmap.getPixels(pixels, 0, w, 0, 0, w, h);
int i = 0;
for (int r = 0; r < redDim; r++) {
for (int g = 0; g < greenDim; g++) {
int p = r + g * w;
for (int b = 0; b < blueDim; b++) {
lut[i++] = pixels[p + b * h];
}
}
}
Type.Builder tb = new Type.Builder(mRs, Element.U8_4(mRs));
tb.setX(redDim).setY(greenDim).setZ(blueDim);
Type t = tb.create();
mAllocCube = Allocation.createTyped(mRs, t);
mAllocCube.copyFromUnchecked(lut);
mScriptlut.setLUT(mAllocCube);
mScriptlut.forEach(mAllocIn, mAllocOut);
mAllocOut.copyTo(mOutputBitmap);
return mOutputBitmap;
}
you increase the mFilter value to get different filter effect with different LUT images, you have, check it out.
you can go through the this link on github for more help, i got the answer from here:-
https://github.com/RenderScript/RsLutDemo
hope it will help

how to simplify an img array that uses many drawable ressources

I have an array which contains several drawables needed by my main java code I use this to call them when needed:
mImagesArray = new int[]{R.drawable.img_0, R.drawable.img_1, R.drawable.img_2,...,R.drawable.img_m}
this direct implementation method works but imagine if i have an array containing +100 images, I would call each drawable value from img_1 to the final img_100 which is pretty frustrating.
What I need is a function which use an increment int i value that is defined by (for i=0;i<m;i++) so this function would look much simpler than the previous one that I used.. something like mImagesArray = new int[]{R.drawable.img_i} maybe ?
I hope you understood my question, basically I want an all-set function which requires only mImagesArray's number of elements..
edit ** mImagesArray is used in:
private void drawImage(Canvas canvas) {
//Get the image and resize it
Bitmap image = BitmapFactory.decodeResource(getResources(),
mImagesArray_ar[mImagesArrayIndex]);
//Draw background
// customWallpaperHelper.setBackground(canvas);
//Scale the canvas
PointF mScale = customWallpaperHelper.getCanvasScale(mImageScale, image.getWidth(), image.getHeight());
canvas.scale(mScale.x, mScale.y);
//Draw the image on screen
Point mPos = customWallpaperHelper.getImagePos(mScale, image.getWidth(), image.getHeight());
canvas.drawBitmap(image, mPos.x, mPos.y, null);
}
THANKS.
Add this method to your code:
protected final static int getResourceID
(final String resName, final String resType, final Context ctx)
{
final int ResourceID =
ctx.getResources().getIdentifier(resName, resType,
ctx.getApplicationInfo().packageName);
if (ResourceID == 0)
{
throw new IllegalArgumentException
(
"No resource string found with name " + resName
);
}
else
{
return ResourceID;
}
}
And use it like this:
int myID =
getResourceID("your_resource_name", "drawable", getApplicationContext());
Note: no path nor extension, in case of images.
You can even not use the mImagesArray array: just use int myID = getResourceID("img_" + i, "drawable", getApplicationContext());, where i is an integer (the same integer you would use as your array index).
Like this:
Bitmap image =
BitmapFactory.decodeResource(getResources(),
getResourceID("img_" + mImagesArrayIndex, "drawable", getApplicationContext()));
I would rather suggest you to just create a string array with all the drawable names and then extract the drawable from the names.
I mean to say similar to this:-
String[] drawables=new String[100]
for(int i=0;i<100;i++)
drawables[i]="img"+i;
Then finally when you want it you get by name like this:-
int drawableResourceId = this.getResources().getIdentifier(drawables[i], "drawable", this.getPackageName());
Had the same problem.
int x,i=0;
While(i<100){
ImageView view = new ImageView(this);
name="img_"+i;
x=getResources().getIdentifier(name, "drawable, getPackageName());
view.setImageResurse(x);
mainActivity.addView(view);
i++;
}

[cocos2dx android]Rendering CCSprite using raw data from Bitmap

I am trying to fetch an image from a URL into a Bitmap and then using the raw data from the Bitmap am trying to create a CCSprite. The issue here is that the image is corrupted when I display the sprite. I created a standalone android only application(no cocos2dx) and used the same code to fetch and display the Bitmap and its displayed correctly. Any reason why the image is not being properly rendered in cocos2dx?
My code to fetch the image from the URL is:
String urlString = "http://www.mathewingram.com/work/wp-content/themes/thesis/rotator/335f69c5de_small.jpg";//http://graph.facebook.com/"+user.getId()+"/picture?type=large";
Bitmap pic = null;
pic = BitmapFactory.decodeStream((InputStream) new URL(urlString).getContent());
int[] pixels = new int[pic.getWidth() * pic.getHeight()];
pic.getPixels(pixels, 0, pic.getWidth(), 0, 0,pic.getWidth(),pic.getHeight());
int len = pic.getWidth()* pic.getHeight();
nativeFbUserName(pixels,len,pic.getWidth(), pic.getHeight());
The function "nativeFbUserName" is a call to a native c++ function which is :
void Java_com_WBS_Test0001_Test0001_nativeFbUserName(JNIEnv *env, jobject thiz,jintArray name, jint len, jint width, jint height) {
jint *jArr = env->GetIntArrayElements(name,NULL);
int username[len];
for (int i=0; i<len; i++){
username[i] = (int)jArr[i];
}
HelloWorld::getShared()->picLen = (int)len;
HelloWorld::getShared()->picHeight = (int)height;
HelloWorld::getShared()->picWidth = (int)width;
HelloWorld::getShared()->saveArray(username);
HelloWorld::getShared()->schedule(SEL_SCHEDULE(&HelloWorld::addSprite),0.1);
}
void HelloWorld::saveArray(int *arrayToSave)
{
arr = new int[picLen];
for(int i = 0; i < picLen; i++){
arr[i] = arrayToSave[i];
}
}
void HelloWorld::addSprite(float time)
{
this->unschedule(SEL_SCHEDULE(&HelloWorld::addSprite));
CCTexture2D *tex = new CCTexture2D();
bool val = tex->initWithData(arr,(cocos2d::CCTexture2DPixelFormat)0,picWidth,picHeight, CCSizeMake(picWidth,picHeight));
CCLog("flag is %d",val);
CCSprite *spriteToAdd = CCSprite::createWithTexture(tex);
spriteToAdd->setPosition(ccp(500, 300));
this->addChild(spriteToAdd);
}
Edit:
So I found this link Access to raw data in ARGB_8888 Android Bitmap that states that it might be a bug. Has anyone found a solution to this?
EDIT
So I just noticed a corruption of images on the lower right corner of the image.I am not sure why this is happening and how to fix it. Any ideas?
EDIT END
Answering my own question, I obtained a byte array from the bitmap using:
byte[] data = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
pic.compress(Bitmap.CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
And then passed this byte array to the native code.

How to load multiple drawables from id using a loop?

Must be a way looping through this code:
private void loadSprites() {
this.sprites[0] = BitmapFactory.decodeResource(getResources(), R.drawable.ic_boom01);
this.sprites[1] = BitmapFactory.decodeResource(getResources(), R.drawable.ic_boom02);
this.sprites[2] = BitmapFactory.decodeResource(getResources(), R.drawable.ic_boom03);
this.sprites[3] = BitmapFactory.decodeResource(getResources(), R.drawable.ic_boom04);
this.sprites[4] = BitmapFactory.decodeResource(getResources(), R.drawable.ic_boom05);
this.sprites[5] = BitmapFactory.decodeResource(getResources(), R.drawable.ic_boom06);
this.sprites[6] = BitmapFactory.decodeResource(getResources(), R.drawable.ic_boom07);
}
Thanks!
If I am understand your question, you want something like,
int[] drawables = {R.drawable.ic_boom01,R.drawable.ic_boom02,R.drawable.ic_boom03,R.drawable.ic_boom04,R.drawable.ic_boom05,R.drawable.ic_boom06,R.drawable.ic_boom07}
private void loadSprites() {
for(int i=0; i<this.sprites.length; i++)
this.sprites[i] = BitmapFactory.decodeResource(getResources(), drawables[i]);
}
You should place your images in the assets folder. From their you can access them via their file name. See http://developer.android.com/reference/android/content/res/AssetManager.html.
Please look at below code for that.
First make int array
int[] mImgArray = { R.drawable.ic_boom01, R.drawable.ic_boom02,
R.drawable.ic_boom03, R.drawable.ic_boom04, R.drawable.ic_boom05,
R.drawable.ic_boom06, R.drawable.ic_boom07 };
or Set this Image to ImageView using below code
mImgView1.setImageResource(mImgArray[0]);
And you can convert this image directly to bitmap and store into bitmap array using below code.
Bitmap mBmpArray=new Bitmap[mImgArray.length];
for(int i=0; i<mImgArray.length; i++)
mBmpArray[i] = BitmapFactory.decodeResource(getResources(), mImgArray[i]);
}
This works for me
//Bitmap of images for fly asset
private Bitmap fly[] = new Bitmap[8];
//Initialize array of images
for(int i = 0; i < fly.length; i++){
this.fly[i] = BitmapFactory.decodeResource( getResources(), getResources().getIdentifier("fly_frame" + i, "drawable", context.getPackageName() ) );
}
You can do that in a simple for loop.. and start from the first id and increment it by 1 at each loop.. though I don't recommend you to do this..

Categories

Resources