1

I want to convert string type into int. I am doing automation using espresso.

As per espresso automation syntax for clicking on object, onView(withid(R.id.btn_0).perform(click())

I have json file, where I have stored the object,

"btn_0": {
      "ANDROID": "withId=R.id.btn_0"
  }

Now, when I read btn_0, i get string value for the btn_0 object and withId() takes int.

Note: Integer.parseInt() will not work.

Can anyone help me with this?

Neerajkumar
  • 300
  • 4
  • 19

3 Answers3

2

You can parse a resource name to an integer using the Resources.getIdentifier() method, I have prepared an example for you:

@Test
public void parseResourceIdTest() {
    final Context context = InstrumentationRegistry.getTargetContext();

    assertEquals(R.id.btn_0, parseResourceId(context, "btn_0"));
}

public static int parseResourceId(@NonNull Context context, @NonNull String string) {
    return context.getResources().getIdentifier(string, "id", context.getPackageName());
}
1

Instead of passing entire ID like "R.id.modeName" only pass "modeName"

final Context context = InstrumentationRegistry.getTargetContext(); int obj = context.getResources().getIdentifier("modeName", "id", context.getPackageName()); onView(withId(obj)).perform(click());

Kamran
  • 11
  • 2
-1

Below is work around,try this

   while( i < withId.length()) {
      num *= 10;
      num += withId.charAt(i++) - '0'; 

   }

this workarround available here please check it : How do I convert a String to an int in Java?

srinivas
  • 1
  • 3
  • My string is not "1234". It is "R.id.btn_0" which is internally integer for espresso automation. However, @Jarosław Wiśniewski has solved my problem – Neerajkumar Jul 06 '18 at 10:33