Converting EditText to int? (Android) - android

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()

Related

Checking for empty edittext android

I have an edittext with input type set to number. I want to check if edittext is empty.
<EditText
android:id="#+id/noOfTranset"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="55dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:hint="Enter number:"
android:inputType="number"
android:textColor="#android:color/black"
android:maxLength="2"/>
Below is the code which I have tried but doesn't checks for empty edittext. What am I missing here? Thanks.
String numTrans = et1.getText().toString();
int transaction = Integer.parseInt(numTrans);
if(numTrans.trim().length() == 0 || numTrans.equals("") || numTrans == null){
// none of the above conditions check for empty edittext
}
Problem is your trying to convert the empty string to an Integer. Integer.parseInt will throw NumberFormatException when the input text is null or empty.
Change your code to parse string to integer only when the input text is not empty
if(!TextUtils.isEmpty(numTrans)){
int transaction = Integer.parseInt(numTrans);
// do your other stuff here
}
How about something like this?
EditText usernameEditText = (EditText) findViewById(R.id.editUsername);
sUsername = usernameEditText.getText().toString();
if (sUsername.matches("")) {
Toast.makeText(this, "You did not enter a username", Toast.LENGTH_SHORT).show();
return;
}
Taken from: Check if EditText is empty.
This is very simple you should check by using trim function like:
String numTrans = et1.getText().toString();
if(!numTrans.trim().length() > 0)
{
int transaction = Integer.parseInt(numTrans);
//code here for empty edittext....
}

Android: Button enabled property is not working

i have the String in Edit Text, i want to change change the button state through the string. Please help me out of this problem i am beginner in android.
Here is the code.
String Result = jsonResult.toString();
JSONObject jsonResponse = new JSONObject(Result);
int successValue = jsonResponse.getInt("success");
String messageValue= jsonResponse.getString("message");
String successStringValue = String.valueOf(successValue);
String messageStringValue = String.valueOf(messageValue);
t1.setText(messageStringValue);
String tt1=t1.getText().toString();
if (tt1 != "Appointment is ready."){
b1.setEnabled(true);}
else{
b1.setEnabled(false);}
Change your condition to
if (tt1.equalsIgnoreCase("Appointment is ready.")){
b1.setEnabled(true);
}
else
{
b1.setEnabled(false);
}
use this code for making edittext not editable
<EditText ...
android:clickable="false"
android:cursorVisible="false"
android:focusable="false"
android:focusableInTouchMode="false">
</EditText>
if(!(tt1.equals("Some String")))
{
//enable button
}
else
{
//disable it
}
Stings are compared by doing ".equals()"

Android - How to get float values and control?

I have two editText. First edit text is amount, second edit text is description. I get the amunt edit text values float, description edit text values string. But error when control values. I think wrong "(tutarEdit.getText().toString().equals("")".
Thanks in Advance..
final EditText tutarEdit = (EditText) layout.findViewById(R.id.editTextTutar);
final EditText aciklamaEdit = (EditText) layout.findViewById(R.id.editTextAciklama);
Float tutar = Float.parseFloat(tutarEdit.getText().toString());
String aciklama = aciklamaEdit.getText().toString();
if(tutarEdit.getText().toString().equals("") || aciklamaEdit.getText().toString().equals("")){
Toast.makeText(MainActivity.this, "Void", Toast.LENGTH_LONG).show();
}
You are getting parse error when tutarEdit is "", surround it with try/catch
Float tutar = 0;
try {
tutar = Float.parseFloat(tutarEdit.getText().toString());
} catch (Exception e) {
e.printStackTrace();
}

Param in button to change activity

My button sends a parameter to the function.
<Button
android:id="#+id/tela1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Chinese Day"
android:onClick="loadPage"
android:tag="page1"
/>
My function should use this parameter to load the page1 activity.
public void loadPage(View view) {
String page = (String) view.getTag();
setContentView(R.layout.page);
}
How to make this work?
Tks
You want to specify in the button's tag the name of the layout, right?
Try the following:
String page = (String) view.getTag();
int layoutId= getResources().getIdentifier(page, "layout", getPackageName());
setContentView(layoutId);
Hope this helps.
You could use Java reflection API.
Each activity is an integer in R.layout. You only need to search for the attribute inside R.layout and then get its integer value to shove into setContentView.
try {
String tag = (String) btn.getTag(); // Button in variable "btn"
Class<R.layout> cls = R.layout.class;
Field field = cls.getDeclaredField(tag);
Integer obj = (Integer) field.get(null); // You could do these two in one line
int value = obj.intValue();
Log.i("Test", "Actvity id code = " + obj.toString()); // Testing code
setContentView(value);
}
catch (Exception e) {
e.printStackTrace();
return;
}

Android: converting String to int

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());
}

Categories

Resources