I am trying to set an easy app that taken two numbers gives the sum of hose two. I found something about how to do this but as I try to convert string to int the app crashes. Can you help me?
Here's my method:
public void do_sum(View v)
{
EditText t1 = (EditText) findViewById(R.id.number1);
EditText t2 = (EditText) findViewById(R.id.button);
String s1 = t1.getText().toString();
String s2 = t2.getText().toString();
int n1 = Integer.parseInt(s1);
int n2 = Integer.parseInt(s2);
int res = n1+n2;
((EditText) findViewById(R.id.result)).setText(String.valueOf(res));
}
Please can you help me?
There is a small error in your code, you should use R.id.number2 instead of R.id.button when getting the second number from the EditText view:
EditText t1 = (EditText) findViewById(R.id.number1);
EditText t2 = (EditText) findViewById(R.id.number2);
Additionally, to avoid crashing the app, you can add a try-catch block to catch the NumberFormatException that might be thrown if the strings in s1 and s2 cannot be parsed into integers:
try {
int n1 = Integer.parseInt(s1);
int n2 = Integer.parseInt(s2);
int res = n1 + n2;
((EditText) findViewById(R.id.result)).setText(String.valueOf(res));
} catch (NumberFormatException e) {
// Handle the exception here
}
Related
I have around 50 EditText fields and I want to get their values using a loop. Getting the values individually as below works fine:
SharedPreferences settings = getSharedPreferences(filename, 0);
SharedPreferences.Editor editor = settings.edit();
editor.clear(); //not sure if this is required
final EditText t1 = (EditText) findViewById(R.id.text1Value);
String T1 = t1.getText().toString();
editor.putstring("text1",T1);
final EditText t2 = (EditText) findViewById(R.id.text2Value);
String T2 = t2.getText().toString();
editor.putstring("text2", T2);
................................ and so on till EditText t50.
I have tried achieving this through the loop below but couldn't get it to work.
for(int x=1; x<50; x++)
{
EditText et[x] = (EditText) findViewById(R.id.text[x]Value);
String t[x] = et[x].getText().toString();
String Ref = "text" + x;
editor.putString(Ref, t[x]);
}
You can try this by creating an array of the ids of the textview and looping through the array.
Try this:
int[] ids = new int[]{R.id.text1Value,R.id.text2Value,R.id.text3Value};//and so on
int i =1;
for(int id : ids){
EditText t = (EditText) findViewById(id);
String Ref = "text" + i;
editor.putString(Ref, t.getText().toString());
i++;
}
If I assume you have all of these EditTexts inside a Layout called ll (should work for structures other than Layout too, such as a ViewGroup etc.):
ArrayList<String> values = new ArrayList<String>();
for (int i = 0; i < ll.getChildCount(); i++) {
if (ll.getChildAt(i) instanceof EditText) {
EditText et = (EditText)ll.getChildAt(i);
values.add(et.getText().toString());
}
}
My Android is a little rusty so apologies if there is something wrong with that, but should give you the general idea anyway
int[] ids = new int[]{R.id.text1Value,R.id.text2Value,R.id.text3Value};//and so on
int i =1;
for(int id : ids){
EditText t = (EditText) findViewById(id);
String Ref = "text" + i;
editor.putString(Ref, t.getText().toString());
i++;
}
private void clearScreen() {
int[] _ids = null;
_ids = new int[]{R.id.etIdTAtividade, R.id.etNomeTAtividade, R.id.etNmAtividade};
for (int i = 0; i < (_ids.length); i++) {
EditText t = (EditText) findViewById(_ids[i]);
t.setText("");
}
}
I'm working on a simple calculator
I'm still a beginner and don't know much about java or android
however, everytime I click on the button the app crashes!
what's wrong with the code ?
final Button btn = (Button) findViewById(R.id.btn);
final EditText ET = (EditText) findViewById(R.id.ET);
final EditText ET2 = (EditText) findViewById(R.id.ET2);
final EditText ET3 = (EditText) findViewById(R.id.ET3);
final TextView TV = (TextView) findViewById(R.id.textView4);
final TextView TV2 = (TextView) findViewById(R.id.textView5);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String et = ET.getText().toString();
String et2 = ET2.getText().toString();
String et3 = ET3.getText().toString();
for (int i = Integer.parseInt(et2); i < Integer.parseInt(et3); i++) {
try {
str = et.replace("X", "" + i);
}
catch (Exception e) {
str = et.replace("x", "" + i);
}
int rslt = Integer.parseInt(str);
TV.append( " " + i )
TV2.append( " " + rslt )
}
}
}
});
That's all codes already
this code is meant to make a table for a F(X) method like the one on the casio calculator. I may need it for school
like :
F(X) = X^2 + X*4 - 3
One problem I see is that outer try misses corresponding catch block and you do not check whether proper number is entered in Et2 and Et3. Integer.parseInt will throw an exception if provided text is not a proper number.
I am designing a basic BMI calculator and I have the calculator working, but I need to convert the calculated answer from a TextView which is a double to an integer to enable me right statements with <> operators based on the calculated answer.
How do I convert the answer from the TextView to an integer?
v.findViewById(R.id.bmi).setOnClickListener(this);
return v;
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.bmi:
try {
EditText w = (EditText) getView().findViewById(R.id.w);
String value = w.getText().toString();
EditText h = (EditText) getView().findViewById(R.id.h);
String value1 = h.getText().toString();
TextView ans = (TextView) getView().findViewById(R.id.ans);
Double l1 = Double.parseDouble(value);
Double l2 = Double.parseDouble(value1);
ans.setText(Double.toString(l1 / (l2 * l2)));
}
catch (Exception e)
{
new AlertDialog.Builder(getActivity()).setNeutralButton("OK",null).setMessage("ALL FIELDS ARE REQUIRED TO COMPUTE YOUR BMI! ").show();
break;
}
}
}
}
First, The conversion is NOT from textview to int. textView aint a datatype. If you want the result in int use parseInt() method. int i = Integer.parseInt(value).
[EDIT]
Try this, this will work.
TextView tv = (TextView) findViewById(R.id.tv);
EditText et = (EditText) findViewById(R.id.et);
try {
double d = Double.valueOf(String.valueOf(et.getText()));
tv.setText(String.valueOf( (int) d));
}catch (NumberFormatException e){
Toast.makeText(MainActivity.this, "Enter valid number.", Toast.LENGTH_SHORT).show();
}
I have simplified it for your understanding. The code can still be optimized.
Hi all I am having a little trouble handling this question. I have 5 EditText boxes and I ask the user to put a number in them. Then I want to calculate the sum of the EditText boxes and do something with the sum. However I am having trouble in the case if the user don't put a number in all the boxes.
Is it possible to put a default value "0" in the boxes just in case not all the boxes are filled but the sum to be calculated although not all the boxes are filled?
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_extra_question);
textBox1 = (EditText) findViewById(R.id.editText1);
textBox2 = (EditText) findViewById(R.id.editText2);
textBox3 = (EditText) findViewById(R.id.editText3);
textBox4 = (EditText) findViewById(R.id.editText4);
textBox5 = (EditText) findViewById(R.id.editText5);
buttON = (Button) findViewById(R.id.button1);
buttON.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
number1 = Integer.parseInt(textBox1.getText().toString());
number2 = Integer.parseInt(textBox2.getText().toString());
number3 = Integer.parseInt(textBox3.getText().toString());
number4 = Integer.parseInt(textBox4.getText().toString());
number5 = Integer.parseInt(textBox5.getText().toString());
sum = number1 + number2 + number3 + number4 + number5;
if(sum > 100)
{
Toast.makeText(getApplicationContext(), "Nice!", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "Fail!", Toast.LENGTH_LONG).show();
}
}
});
Do this for each number:
number1 = textBox1.getText().toString().trim().isEmpty()?0:Integer.parseInt(textBox1.getText().trim().toString());
Create on function like this
public int getIntFromString(String str) {
if (str != null) {
if (str.equalsIgnoreCase("")) {
return 0;
} else {
try {
return Integer.parseInt(str);
} catch (NumberFormatException e) {
return 0;
}
}
} else {
return 0;
}
}
Then Your code should be
number1 = getIntFromString(textBox1.getText().toString().trim());
number2 = getIntFromString(textBox2.getText().toString().trim());
number3 = getIntFromString(textBox3.getText().toString().trim());
number4 = getIntFromString(textBox4.getText().toString().trim());
number5 = getIntFromString(textBox5.getText().toString().trim());
Yes your idea is correct. For each of the edit texts , just check:
if(textBox1.getText().toString().equals(""))
{
number1 = 0;
}
else
number1 = Integer.parseInt(textBox1.getText().toString());
You have to check Empty String using the below code and put "0" in every missing value.
number1 = textBox1.getText().toString().isEmpty()?0:Integer.parseInt(textBox1.getText().toString());
number2 = textBox2.getText().toString().isEmpty()?0:Integer.parseInt(textBox2.getText().toString());
number3 = textBox3.getText().toString().isEmpty()?0:Integer.parseInt(textBox3.getText().toString());
number4 = textBox4.getText().toString().isEmpty()?0:Integer.parseInt(textBox4.getText().toString());
number5 = textBox5.getText().toString().isEmpty()?0:Integer.parseInt(textBox5.getText().toString());
Hello guys I m new to android and want to display the quadratic formula calculation here is the code i am doing in android there is no error showing in this code but still on the emulator its not displaying the result :-(
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b1 = (Button) findViewById(R.id.btnSubmit);
final EditText et1 = (EditText) findViewById(R.id.etVA);//whats wrong
final EditText et2 = (EditText) findViewById(R.id.etVC);//whats wrong
final EditText et3 = (EditText) findViewById(R.id.etVC);//whats wrong
final TextView answer = (TextView) findViewById(R.id.txtResult);//whats wrong
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
String a1 = et1.getText().toString();//whats wrong
double a = Double.parseDouble(a1);//whats wrong
String b1 = et2.getText().toString();//whats wrong
double b = Double.parseDouble(b1);//whats wrong
String c1 = et3.getText().toString();//whats wrong
double c = Double.parseDouble(c1);//whats wrong
double x1 = (-b+Math.sqrt(b*b-4*a*c))/(2*a);//whats wrong
System.out.println("x1 = "+ x1);
String R = x1+ ""; //whats wrong
answer.setText("Your Answer is " + R); //whats wrong
}
});
}
try like this
String a1 = et1.getText().toString();
double a = Double.valueof(a1);
String b1 = et2.getText().toString();
double b = Double.valueof(b1);
String c1 = et3.getText().toString();
double c = Double.valueof(c1);
double x1 = (-b+Math.sqrt(b*b-4*a*c))/(2*a);
System.out.println("x1 = "+ x1);
String R = String.valueof(x1);
answer.setText("Your Answer is " + R);
Your program doesn't have any errors and you must provide the valid inputs. Otherwise you will get the output Your Answer is NAN i.e., Not a Number.
The valid inputs in the sense, the values of a, b and c provided must satisfy the equation ax2 + bx + c = 0. So that the quadratic formula can be used find the roots.
Example Valid Inputs :
a = 1.0
b = 3.0
c = 2.0
Output For the above Inputs :
Your Answer is -1.0
I have found the solution. Code was fine but I was only doing a simple logical mistake
final EditText et1 = (EditText) findViewById(R.id.etVA);
final EditText et2 = (EditText) findViewById(R.id.etVC);//that is the mistake it should be like (R.id.etVB)....
final EditText et3 = (EditText) findViewById(R.id.etVC);
call onclicklistner() through View
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
}
});