I'm simply trying to convert a string that is generated from a barcode scanner to an int so that I can manipulate it by taking getting the remainder to generate a set number of integers. So far I have tried:
int myNum = 0;
try {
myNum = Integer.parseInt(myString.getText().toString());
} catch(NumberFormatException nfe) {
}
and
Integer.valueOf(mystr);
and
int value = Integer.parseInt(string);
The first one gives me the error :The method getText() is undefined for the type String
while the last two don't have any compile errors but the app crashes immediately when those are called. I thought it had to do with my barcode scanning intent method but I put it into the OnCreate and still got the error.
Change
try {
myNum = Integer.parseInt(myString.getText().toString());
} catch(NumberFormatException nfe) {
to
try {
myNum = Integer.parseInt(myString);
} catch(NumberFormatException nfe) {
It's already a string? Remove the getText() call.
int myNum = 0;
try {
myNum = Integer.parseInt(myString);
} catch(NumberFormatException nfe) {
// Handle parse error.
}
You just need to write the line of code to convert your string to int.
int convertedVal = Integer.parseInt(YOUR STR);
Use regular expression:
int i=Integer.parseInt("hello123".replaceAll("[\\D]",""));
int j=Integer.parseInt("123hello".replaceAll("[\\D]",""));
int k=Integer.parseInt("1h2el3lo".replaceAll("[\\D]",""));
output:
i=123;
j=123;
k=123;
Use regular expression:
String s="your1string2contain3with4number";
int i=Integer.parseInt(s.replaceAll("[\\D]", ""))
output: i=1234;
If you need first number combination then you should try below code:
String s="abc123xyz456";
int i=((Number)NumberFormat.getInstance().parse(s)).intValue()
output: i=123;
barcode often consist of large number so i think your app crashes because of the size of the string that you are trying to convert to int. you can use BigInteger
BigInteger reallyBig = new BigInteger(myString);
You can not convert to string if your integer value is zero or starts with zero (in which case 1st zero will be neglected).
Try change.
int NUM=null;
try this
String t1 = name.getText().toString();
Integer t2 = Integer.parseInt(mynum.getText().toString());
boolean ins = myDB.adddata(t1,t2);
public boolean adddata(String name, Integer price)
// Convert String to Integer
// String s = "fred"; // use this if you want to test the exception below
String s = "100";
try
{
// the String to int conversion happens here
int i = Integer.parseInt(s.trim());
// print out the value after the conversion
System.out.println("int i = " + i);
}
catch (NumberFormatException nfe)
{
System.out.println("NumberFormatException: " + nfe.getMessage());
}
Related
I want to convert String into int.
For example:
if String is "0x1F60A" then it should be convert into int same as 0x1F60A
String str = "0x1F60A";
int i = 0x1F60A; // it must be something like this.
Why I need this. Because I'm going to convert unicode int into Emoji
I'm using this code.
final String emojiString = str.substring(start,end);
// value in emojiString is 0x1F60A
int unicode = // need to convert this string into int
ss.replace(start, end, new String(Character.toChars(unicode)));
Can you please let me know how can I do that.
For conversion of Unicode to Int:
You have to omit the 2 first characters with .substring(2)
int code = Integer.parseInt(unicodeStr.substring(2), 16);
For conversion of String to int:
try {
myNum = Integer.parseInt(myString);
} catch(NumberFormatException nfe) {
}
int unicode = Integer.parseInt(emojiString.substring(2), 16);
I am creating an epub reader for android. For the pagination part, I am trying to get the whole string content and then search for space in the string. Then I get the text height and compare it with the screen height. if still (text height < screen height) I loop through the string and do the same thing in a while loop.
Every thing went well, but when it comes to the end of the string I get IndexOutOfBoundsException. I have attached the screenshot of the Logcat below.
The code I used to get the no of pages is like this
public String getNoOfPages(String text){
String remainingString = "";
try{
int screenHeight = getScreenHeight();
String originalText = text;
String strToModify = text;
StringBuilder newString = new StringBuilder();
StringBuilder oldString = new StringBuilder();
int startIndex = 0;
String strToFind = " ";
int index = strToModify.indexOf(strToFind,startIndex);
newString.append(originalText.substring(startIndex, index+1));
oldString.append(newString.toString());
startIndex = index+1;
int textHeight = getTextHeight(newString.toString());
while(textHeight < screenHeight){
index = strToModify.indexOf(strToFind,startIndex);
oldString.replace(0,oldString.toString().length(),newString.toString());
newString.append(originalText.substring(startIndex, index+1));
startIndex = index+1;
textHeight = getTextHeight(newString.toString());
}
remainingString = originalText.substring(oldString.length()-1,originalText.length());
}catch(Exception e){
Log.d("chathura123","Error in getNoOfPages " );
e.printStackTrace();
}
return remainingString;
}
The logic is when the remaining string is an empty string("") ,it means that is the end of the content of the page. So I want to check until it returns an empty string.
The above method is called inside another while loop. (In Async Task)
String tmp = null;
try{
tmp = reader.getNoOfPages(content);
while (!tmp.equals("")) {
tmp = reader.getNoOfPages(tmp);
page_count++;
if(page_count==80){
Log.d("chathura123", "80 th iteration");
}
Log.d("chathura123", "inside while "+page_count);
}
}catch(Exception e){
Log.d("chathura123", "error occured in getPageCount");
}
What is the wrong with this? Why I am getting OutOfBoundsException?
Thank you.
may be on the last line, when there are no characters there is an error for originalText.substring(startIndex, index+1) what if originalText doesnt have index+1 length/index.
I am wondering how to convert an EditText input to an int, I have the user input a number, which then divides it by 8.
MainActivity.java:
#SuppressWarnings("unused")
public void calcSpeed(View view)
{
setContentView(R.layout.activity_speed);
final TextView mTextView = (TextView) findViewById(R.id.textView3);
mTextView.setText("You should be getting: " +netSpedCalcd);
}
activity_main.xml:
<EditText
android:id="#+id/editText1"
android:inputType="number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="62dp"
android:ems="10" >
you have to used.
String value= et.getText().toString();
int finalValue=Integer.parseInt(value);
if you have only allow enter number then set EditText property.
android:inputType="number"
if this is helpful then accept otherwise put your comment.
Use Integer.parseInt, and make sure you catch the NumberFormatException that it throws if the input is not an integer.
I'm very sleepy and tired right now but wouldn't this work?:
EditText et = (EditText)findViewById(R.id.editText1);
String sTextFromET = et.getText().toString();
int nIntFromET = new Integer(sTextFromET).intValue();
OR
try
{
int nIntFromET = Integer.parseInt(sTextFromET);
}
catch (NumberFormatException e)
{
// handle the exception
}
Try this,
EditText x = (EditText) findViewById(R.id.editText1);
int n = Integer.parseInt(x.getText().toString());
You can use parseInt with try and catch block
try
{
int myVal= Integer.parseInt(mTextView.getText().toString());
}
catch (NumberFormatException e)
{
// handle the exception
int myVal=0;
}
Or you can create your own tryParse method :
public Integer tryParse(Object obj) {
Integer retVal;
try {
retVal = Integer.parseInt((String) obj);
} catch (NumberFormatException nfe) {
retVal = 0; // or null if that is your preference
}
return retVal;
}
and use it in your code like:
int myVal= tryParse(mTextView.getText().toString());
Note: The following code without try/catch will throw an exception
int myVal= new Integer(mTextView.getText().toString()).intValue();
Or
int myVal= Integer.decode(mTextView.getText().toString()).intValue();
Try the line below to convert editText to integer.
int intVal = Integer.parseInt(mEtValue.getText().toString());
I had the same problem myself. I'm not sure if you got it to work though, but what I had to was:
EditText cypherInput;
cypherInput = (EditText)findViewById(R.id.input_cipherValue);
int cypher = Integer.parseInt(cypherInput.getText().toString());
The third line of code caused the app to crash without using the .getText() before the .toString().
Just for reference, here is my XML:
<EditText
android:id="#+id/input_cipherValue"
android:inputType="number"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
You can use like this
EditText dollar=(EditText) findViewById(R.id.money);
int rupees=Integer.parseInt( dollar.getText().toString());
First, find your EditText in the resource of the android studio by using this code:
EditText value = (EditText) findViewById(R.id.editText1);
Then convert EditText value into a string and then parse the value to an int.
int number = Integer.parseInt(x.getText().toString());
This will work
int total_Parson = Integer.parseInt(etRegularTickets.getText().toString());
int ticket_price=Integer.parseInt(TicketData.get(0).getTicket_price_regular());
total_ticket_amount = ticket_price * total_Parson;
etRegularPrice.setText(""+total_ticket_amount);
In Kotlin, you can do this.
val editText1 = findViewById(R.id.editText)
val intNum = editText1.text.toString().toInt()
In kotlin, there is shortest way thanks to the Extension Function
fun EditText.toInt(): Int {
return this.text.toString().toInt()
}
Use it in your code like below:
mEditText.toInt()
I have this code to control if a EditTextPreference is null or not:
case R.id.prochain_vidange:
settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String choix_huile = settings.getString("listPref_huile_moteur", "0");
km = settings.getString("km", "");
Log.d("TAG",km);
int x= Integer.valueOf(km);
if (km != "")
{
if (Integer.valueOf(choix_huile) == 0) {
............
The problem is in this line:
int x= Integer.valueOf(km);
What could be the problem ?
Thanks.
If you give Integer.valueOf(String s) a string that is not a valid number, it throws a NumberFormatException. Change the default value to 0:
km = settings.getString("km", "0");
Alternatively, you can catch the exception, and set x to 0:
km = settings.getString("km", "");
int x;
try {
x = Integer.valueOf(km);
} catch(NumberFormatException e) {
x = 0;
}
Integer.valueOf trys to make a new Integer with .parseInteger(String s), "" cant be parsed to a valid number so you get a NumberFormatException
You can catch it with a try catch block or you can simply dont try to make a Integer with the String "".
before:
int x= Integer.valueOf(km);
if (km != "") {
after:
if (km != "") {
int x= Integer.valueOf(km);
Integer.valueOf(km) can throw an exception if the the km string is not able to be parsed as an integer.
However, wrapping it in a try { } catch() block is not an approach I would recommend.
The whole purpose of having a default value on the getString() method in SharedPreferences is that there can be a default value to fall back on if the preference doesn't exist. So the better way to solve this is to modify your settings.getString(...) call to be like this:
km = settings.getString("km", "0");
Then your subsequent call to Integer.valueOf(km) will not have a blank to fail upon.
Is the input string coming from a blank text field where the user can enter any value? If so, it's at that point that you can validate the value that the user entered. By validating the input early on, you won't need to scatter the checking/validating mechanism to other areas of your code.
I've made a class which holds some string and integers, in that class I made a function to convert the data in the class in to a readable string;
public String GetConditions() {
String BigString = null;
String eol = System.getProperty("line.separator");
try {
BigString += "Depth: " + ci(Depth) + eol;
and so on...
Because I have to convert many integers, I made an extra function to convert a integer to a string;
public String ci(Integer i) {
// convert integer to string
if (i != null) {
String a = new Integer(i).toString();
return a;
} else {
return "n/a";
}
}
This throws a NullPointerException exception on return a. I'm quite new to Java, this is probally a noob question... Sorry about, thanks in advance!
There is a much simpler way to convert an Integer to a String: use String#valueOf(int).
public String ci(Integer i)
{
return i == null ? "n/a" : String.valueOf(i);
}
Try converting the Integer you pass in your method to string, instead of instantiating a new one.
You can do it straight forward like:
String a = i.toString();
or
String a = Integer.toString(i.intValue());
Thanks guys, but I found the problem, I've tried to add something to a string which was 'null' , this line:
String BigString = null;