Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access a string using a dynamic string name in android (similar to eval in javascript)?

Tags:

java

android

I'm trying to access string variables using dynamic names depending on what position my gallery is at. To get the value of a string using a fixed name I use the following which is fine (the string is called pic1info):

String strTest = getResources().getString(R.string.pic1info);  

My strings are named pic1info, pic2info, pic3info etc and I want to replace the static definition of pic1info to include the position so pass the contents of the following string in place of pic1info above so that it returns a different string depending on the current position:

String strDynamicStringName= "pic" + position + "info";

In javascript the equivalent would be eval, i'm sure there's a simple way to do this but i can't work out how!

Thanks so much for your help as ever!

Dave

like image 561
deshg Avatar asked Jun 04 '11 16:06

deshg


People also ask

How do you make a variable name dynamic in Java?

There are no dynamic variables in Java. Java variables have to be declared in the source code1. Depending on what you are trying to achieve, you should use an array, a List or a Map ; e.g. It is possible to use reflection to dynamically refer to variables that have been declared in the source code.

What is dynamic initialization in Java?

Dynamic initialization of object refers to initializing the objects at run time i.e. the initial value of an object is to be provided during run time. Dynamic initialization can be achieved using constructors and passing parameters values to the constructors.


2 Answers

use this: android.content.res.Resources.getIdentifier

int resID = getResources().getIdentifier("pic" + position + "info", "string", getPackageName());
String strTest = getResources().getString(resID);
like image 50
Kristin Avatar answered Sep 21 '22 12:09

Kristin


No, there's no simple way to do that in Java, but you can create an array of ints, where each index represents the R-value of that string.

private static final int[] LOOKUP_TABLE = new int[] {
   R.string.pic1info,
   R.string.pic2info,
   R.string.pic3info,
   R.string.pic4info
};

Getting a string would then become:

String strTest = getResources().getString(LOOKUP_TABLE[position]);  
like image 24
Kaj Avatar answered Sep 23 '22 12:09

Kaj