All of the above answers are correct, but they will not help you if, for some reason, the data coming to you is not Integer . for example, the server mistakenly sent you a username instead of userId (must be Integer).
This can happen, so we should always put in checks to prevent it. Otherwise, our application will fail, and it will not be pleasant for the user. Therefore, when converting String to Integer always use a try-catch to prevent application crashes. I use the following code to prevent the application from crashing due to Integer parsing -
try { Log.d(TAG, Integer.parseInt(string)); } catch (NumberFormatException e) { Log.w(TAG, "Key entered isn't Integer"); }
Rohan kandwal
source share