I have a situation where I am creating JAR and I don't want to reference any of String or Int from /res/values. So I am hardcoding it everywhere
event_info.put("CLIENT_HALT", new EventInfo(R.string.client_halt, R.drawable.error, 0, EV_PRIO_HIGH, 0));
As you see "R.string.client_halt" refers to String "Halt" in res/values/abc.xml
But it is of type Int, hence I cannot do like this
event_info.put("CLIENT_HALT", new EventInfo("Halt", R.drawable.error, 0, EV_PRIO_HIGH, 0));
Below is EventInfo method
public EventInfo(int res_id_arg, int progress_arg, int priority_arg, int flags_arg)
{
res_id = res_id_arg;
//icon_res_id = icon_res_id_arg;
progress = progress_arg;
priority = priority_arg;
flags = flags_arg;
}
How do I overcome this issue and hardcode int value in my method. I tried below case but it won't work and give me "NumberFormatException"
String halt = "Halt";
int foo = Integer.parseInt(halt);
Thanks
By passing the id into constructor of your class, you can retrieve the string in the following way.
String stringValue = getResources().getString(R.string.client_halt);
If you are not able to get getResources() directly, pass the context in constructor and do the following
_context.getResources().getString(R.string.client_halt);
Related
I need to edit the string value in variable.
So,
00343755932
should be converted to:
0,0,3,4,3,7,5,5,9,3,2
because I must define each number as an variable array for readable one by one.
if I'm right you are trying to create an array from string. Use following code
String val = "00343755932";
int[] numberArray = new int[val.length()];
Matcher match = Pattern.compile("[0-9]").matcher(val);
int i = 0;
while(match.find()) {
System.out.println(match.group());
numberArray[i] = Integer.parseInt(match.group());
i++;
}
This what I have seen in an android application. They have a number of image buttons with ids
R.java :
public static final int img1=0x7f090080;
public static final int img2=0x7f090081;
public static final int img3=0x7f090082;
public static final int img4=0x7f090083;
public static final int img5=0x7f090084;
public static final int img6=0x7f090085;
public static final int img7=0x7f090086;
public static final int img8=0x7f090087;
In one of the activity they are traversing a for loop like below:
for (int i = 0; i < NoOfButtons; i++) {
if (i == pos) {
((ImageView) vi.findViewById(R.id.img1 + i)).setImageResource(R.drawable.circular_pagination_red);
} else {
((ImageView) vi.findViewById(R.id.img1 + i)).setImageResource(R.drawable.circular_pagination_brown);
}
I want to know how much safe and advisable it is.
One thing this is working absolutely fine. I been a part of this from months and never seen a problem in this logic. But still it irks me a bit.
Note : I am not getting any error and I know the alternate solution also. My only concern is if it is not advisable/safe I want to know why? Another is scenarios where it can create havoc for me. I have a good understanding about R.java.
Though this might work OK most of the times, this is definitely not advisable. The R class is generated automatically thus you have no control over it and it could change. There is a solution to this problem using a typed array in resources. Check for example this answer.
You might want to use reflection.
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 (and no extension, in case of images).
Searched and working on this a long while - no luck. ( It must be simple ? Thanks for the assist. )
Trying to get / set a screen full of EditTexts' text, but not with the usual, more hard-coded way:
... findViewById (R.id.SomeTextWidgetId) ;
Instead, I'm trying to figure out a reusable way via a variable holding the (String) name_of_widget.
In psuedo code:
findViewById (R.id.>> StringVarHere << ); // how to do that ?
I tried also this findViewById method, but it didn't work (!?)
//// given:
static final String FIELD_TV_FEE = "TextViewFee" ;
static final String FIELD_TV_FOO = "TextViewFoo" ;
static final String FIELD_TV_FUM = "TextViewFum" ;
//// and some arbitrary number more of similar fields
static final String [] ALL_FIELDS = {
FIELD_TV_FEE ,
FIELD_TV_FOO ,
FIELD_TV_FUM // ...
} ;
//// ...
//// this part works
int ResourceID;
String stringVarHere = FIELD_TV_FEE;
//// outputs a correct id, say '0x7f05000f' as in R.id.xxx below
ResourceID = context
.getResources()
.getIdentifier ( stringVarHere,
"id",
context
.getApplicationInfo()
.packageName
) ;
Log.d ("MyClass" , "RESID = " + Integer.toHexString(ResourceID) ) ;
/*
* that's where I'm stuck ^^^ ... how do I do:
*/
String field_name ;
for ( field_name : ALL_FIELDS ) {
(EditText) SomethingLike_a_findViewById(field_name).setText ("Hello Wurld") ;
}
I've tried .setId ...
//// details
<!-- excerpt from working xml layout -->
<EditText
android:id="#+id/TextViewFee"
android:inputType="text"
android:layout ... etc ...
/>
<EditText
android:id="#+id/TextViewFoo"
android:inputType="text"
android:layout ... etc ...
/>
<EditText
android:id="#+id/TextViewFum"
android:inputType="text"
android:layout ... etc ...
/>
As expected, the gen'ed R file has something like this:
// ...
public static final class id {
public static final int TextViewFee=0x7f05000f;
public static final int TextViewFum=0x7f05001c;
public static final int TextViewFoo=0x7f05001d;
// ... etc
Yes, thanks - it makes sense to do it in the activity. I was trying to keep it from getting too code bulky. Here's what I'm doing now, based on your and A-C's helpful suggestions. The intention is to get all the text of fields of a form back in one String[]. (I know I could brute force all the fields too.)
What do you all think about this below - seems very similar to your suggestion, madlymad ? I am wondering if this is a poor design approach ?
public class FoodBar {
private Activity activity;
private Context ctx;
public FoodBar ( Activity _activity ) {
this.activity = _activity;
this.ctx = this.activity.getApplicationContext() ;
}
public String[] getTextFromAllEditTexts () { // the UI views
int res_id = 0;
int i = 0;
String [] retValues = new String [MyClassName.ALL_FIELDS_LENGTH] ;
for (String field : MyClassName.ALL_FIELDS_ALL_VEHICLES) {
res_id = this.ctx.getResources()
.getIdentifier ( field, "id", this.ctx.getPackageName() );
((EditText) this.activity
.findViewById (res_id))
.setText( "Meat and Potatoes" ) ;
// redundant - get it right back to make sure it really went in !
retVal[i++] = ((EditText) this.activity
.findViewById (res_id))
.getText().toString() ;
}
return retVal;
} // end func
} // end class
Then from the Activity class, it's just:
String [] theFields = null;
FoodBar = new FoodBar (this);
try {
theFields = FoodBar.getTextFromAllEditTexts ();
} catch (Exception e) {
Log.d ("OOPS", "There's a big mess in the Foodbar: " + e.toString() );
}
The way you could do it is (as I understand the way you are trying):
This can be in non-Activity (YourClassname.java):
public static int getMyId(Context context, String field) {
return context.getResources().getIdentifier (field, "id", context.getPackageName());
}
in Activity-class:
for ( String field_name : YourClassname.ALL_FIELDS ) {
int resid = YourClassname.getMyId(context, field_name);
if(resid != 0) { // 0 = not found
EditText et = (EditText) findViewById(resid);
if (et != null) {
et .setText ("Hello Wurld") ;
}
}
}
But I think it's better to code in the activity class like:
String packageName = getPackageName();
Resources res = getResources();
for ( String field_name : YourClassname.ALL_FIELDS ) {
int resid = res.getIdentifier (field_name, "id", packageName);
if(resid != 0) {// 0 = not found
EditText et = (EditText) findViewById(resid);
if (et != null) {
et .setText ("Hello Wurld") ;
}
}
}
A-C suggested something along the lines of:
res_id = getResources().getIdentifier (field, "id", getPackageName());
((EditText)findViewById (res_id)).setText("NoLongerFubar");
this DOES work - when I tried it standalone in a test rig. Thanks ! Still not sure what was blowing up, but I suspect it was Context or Resource items not being accessible.
Note that variable names (such as R.id.some_id) are only available at compile time and cannot be accessed from a String value at run time. Since these ids are declared as ints, you might consider using an int[] or List<Integer> to store the ids. Depending on how dynamic your layout is and what you are doing with the Views in it, you might even want to simply create the Views at run time and store an array or List of them without using any ids at all.
Android 2.3.3
This is my code...
String[] expression = {""}; //globally declared as empty
somewhere in the code below, I am trying to assign a string to it.
expression[0] = "Hi";
I keep getting the following error...
12-08 22:12:19.063: E/AndroidRuntime(405): java.lang.ArrayIndexOutOfBoundsException
Can someone help me with this..
Can we access the index 0, directly as i am doing?
Actual Code :::
static int x = 0; // global declaration
String[] assembledArray = {""}; // global declaration
assembleArray(strSubString, expression.charAt(i)); //Passing string to the method
//Method Implementation
private void assembleArray(String strSubString, char charAt) {
// TODO Auto-generated method stub
assembledArray[x] = strSubString;
assembledArray[x+1] = String.valueOf(charAt);
x = x+2;
}
The problem is not in assembledArray[x]; it's in assembledArray[x+1].
At the first iteration, x+1 = 1, so you cannot access that part of the array. I would suggest using a dynamic array, aka an ArrayList:
ArrayList<String> assembledArray = new ArrayList<String>(); // global declaration
assembleArray(strSubString, expression.charAt(i)); //Passing string to the method
//Method Implementation
private void assembleArray(String strSubString, char charAt) {
assembledArray.add(strSubString);
assembledArray.add(String.valueOf(charAt));
}
This way, Java takes care of the resizing, and you don't need to keep track of x.
I get the id of resource like so:
int test = (context.getResourceId("raw.testc3"));
I want to get it's id and put it into a string. How can I do this? .toString does not work.
String testString = Integer.toString(test);
Or you can use Use
String.valueOf()
eg.
int test=5;
String testString = String.valueOf(test);
Very fast to do it if you dnt remember or dnt have time to type long text :
int a= 100;
String s = ""+a;
What about:
int a = 100;
String s = String.format("%d", a);