I have created a simple program to try to figure out how to do this. it has two edit text fields (input type number decimal), a text view and a button. I want the sum of the two input fields to be displayed in the text view when the user hits the button. can someone tell me how to set the value of one edit text field to zero if the user left it blank? I have tried many ways but nothing worked.
Edit: i want to achieve this while keeping the hint of edit text as before (without changing the value to zero like " setText("0"); ".
here's my java code (tell me what to add)
package com.example.android.testedittexttozero;
import...
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void calculate(View v) { //the button
final EditText number1 = (EditText) findViewById(R.id.numberFirst);
EditText number2 = (EditText) findViewById(R.id.numberSecond);
TextView total = (TextView) findViewById(R.id.totalTV);
try {
int a = Integer.parseInt(number1.getText().toString());
int b = Integer.parseInt(number2.getText().toString());
int sum = a + b;
total.setText("" + sum);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "One or more field is empty", Toast.LENGTH_LONG).show();
}
}
}
Do you know that in java if you dont initialize a variable with a default value, it's default value be 0?
in short:
try {
int a;//by default, it will be 0;
int b = Integer.parseInt(number2.getText().toString());//let it be 2
int sum = a + b;
total.setText("" + sum);//Ans will be 2 only
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "One or more field is empty", Toast.LENGTH_LONG).show();
}
If you don't enter any value in a, it will be set to as 0. Like if you leave a blank, and enter 2 in second edittext, the ans will be two nevertheless..
public void ZeroingEmpytEditText() {
int f= 0; // Zeroing Factor
if (number1.getText().toString().length() > 0) {
a = Integer.parseInt(number1.getText().toString());
} else {
a=f;
}
if (number2.getText().toString().length() > 0) {
b = Integer.parseInt(number2.getText().toString());
} else {
b=f;
}
int sum = a + b ;
total.setText(sum + "");
}
you can set value 0 of edit text in oncreate method.
like,
public class MainActivity extends AppCompatActivity {
EditText number1,number2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
number1 = (EditText) findViewById(R.id.numberFirst);
number2 = (EditText) findViewById(R.id.numberSecond);
number1.settext("0");
number2.settext("0");
}
public void calculate(View v) { //the button
TextView total = (TextView) findViewById(R.id.totalTV);
try {
int a = Integer.parseInt(number1.getText().toString());
int b = Integer.parseInt(number2.getText().toString());
int sum = a + b;
total.setText("" + sum);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "One or more field is empty", Toast.LENGTH_LONG).show();
}
}
}
its helpfull for you.
Related
Im new to Android development. I want to take a user input as a double value and then pass it to the next activity, and then sum it with another value, but I am having trouble passing it.
When passing this double array called winning onto activity 2, I recieve an error. The error is: Incompatible types.
Required: java.util.ArrayList Found: double[]
Activity 1
public void btnAdd_OnClick(View v)
{
{
if (txtWinnings.getText().toString().isEmpty()) {
displayToast("Please enter an amount");
}else{
double winning =
Double.parseDouble(txtWinnings.getText().toString());
if(winning > 0) {
winnings.add(winning);
txtWinnings.setText("");
txtWinnings.setHint("You have added " + (winnings.size()) +
" tournament winnings");
} else {
displayToast("You must enter an amount more than 0");
}
}
}
}
public void btnClear_OnClick(View v)
{
if(winnings.size() < 0)
{
displayToast("You have no winnings to clear");
}else {
winnings.clear();
displayToast("Cleared");
}
}
public void btnSummary_OnClick(View v)
{
{
if(winnings.size() > 0)
{
Intent i = new Intent(this, SummaryActivity.class);
i.putExtra("winnings", winnings);
startActivity(i);
}else{
displayToast("You must enter at least one amount of winnings");
}
}
}
public void displayToast(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
Activity 2
public class SummaryActivity extends AppCompatActivity {
ArrayList<Double> winnings = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_summary);
setTitle("Summary");
TextView lblTournaments = (TextView) findViewById(R.id.txtAverage);
TextView lblTotal = (TextView) findViewById(R.id.txtTotal);
TextView lblMax = (TextView) findViewById(R.id.txtMax);
TextView lblMin = (TextView) findViewById(R.id.txtMin);
TextView lblAverage = (TextView) findViewById(R.id.txtAverage);
Intent i = getIntent();
winnings = i.getDoubleArrayExtra("winnings");
}
}
winnings is a ArrayList<Double>. You cannot assign it a double[] as you do at this line :
winnings = i.getDoubleArrayExtra("winnings");
You can convert the double[] to a List<Double> like this :
List<Double> winnings = Arrays.stream(i.getDoubleArrayExtra("winnings"))
.mapToObj(d-> d)
.collect(Collectors.toList());
Using streams for that is a bit overkill but learning streams is worth it.
EDIT :
Stream might not be available (see comments). Without Stream, you can manually empty the winnings collection then iterate on the array to fill it again :
double[] array = i.getDoubleArrayExtra("winnings");
winnings.clear();
for(double winning : array) {
winnings.add(winning);
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Please guys I am writing this android app, but I'm getting a run time error in the logCat : java.lang.RuntimeException: Unable to start activity: java.lang.NumberFormatException: Invalid int: ""
public class MainActivity extends Activity{
EditText et;
Button guess, randomize;
TextView tv1, tv2;
int num1;
int num2;
int userAns;
int answer;
final Random rand = new Random();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
et = (EditText) findViewById(R.id.editText1);
tv1 = (TextView) findViewById(R.id.textView1);
tv2 = (TextView) findViewById(R.id.textView2);
guess = (Button) findViewById(R.id.btnSubmit);
randomize = (Button) findViewById(R.id.button1);
randomize(rand);
tv2.setText(num1 + " + " + num2);
userAns = Integer.parseInt(et.getText().toString());
guess.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
answer = num1 + num2;
if (userAns == answer) {
tv1.setText("Correct... The Answer is " +answer);
} else {
tv1.setText("wrong");
}
}
});
randomize.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
randomize(rand);
}
});
}
private void randomize(final Random rand) {
num1 = 1 + rand.nextInt(50);
num2 = 1 + rand.nextInt(50);
}
}
numberFormatException is usually caused by a string to int conversion going wrong. I'm suspecting this line.
userAns = Integer.parseInt(et.getText().toString());
since it's not initialized with text yet.
wrap it in a try/catch
EDIT:
How to fix
I would recommend moving
userAns = Integer.parseInt(et.getText().toString());
inside guess.setOnClickListener like so:
guess.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
answer = num1 + num2;
try {
userAns = Integer.parseInt(et.getText().toString());
if (userAns == answer) {
tv1.setText("Correct... The Answer is " +answer);
} else {
tv1.setText("wrong");
}
} catch(Exception e) {
// output error that 'et' field is emtpy or doesnt contain a number
}
}
});
et is empty unless you set it to a default value. As such, et.getText will return "", which is not a valid number so parseInt will throw an exception. You need to wait to get that text until the user has pressed the guess button and get it then.
I made an app for my use for calculating a string of values appear in an another activity. My app has 3 editTexts and one button. If we press button calculate with the input in edit text and calculated values will displayed in a second activity. I made it successfully but my problem is if the user is leave any of the boxes empty and press the button, the system will Force Close. To avoid this I made editText in graphical layout pre entered with a hint. But if the user accidentally presses button after editing the editText again system shows a Force Close.
I tried many if else methods but it does not work. Some one show me a correct way to check all editText boxes.
public class Screen1 extends Activity {
public static StringBuilder EXTRA_MESSAGE=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen1);
Button bu1= (Button)findViewById(R.id.bu);
bu1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View message)
{ int f1,f3,f4;
String vis;
EditText t1=(EditText)findViewById(R.id.a);
EditText t3=(EditText)findViewById(R.id.c);
EditText t4=(EditText)findViewById(R.id.d);
String e1=t1.getText().toString();
String e3= t3.getText().toString();
String e4= t4.getText().toString();
f1 =Integer.parseInt(e1);
f4=Integer.parseInt(e4);
f3=Integer.parseInt(e3);
StringBuilder sb = new StringBuilder();
for( float i= (float)0.1;i<=5;i=i+(float) .1)
{
sb.append(String.format("%.1f", i)+" mcg = "+(f1*60*i*f4)/(f3*1000)+"\n");
}
vis=sb.toString();
Intent intent = new Intent(message.getContext(),Screen2.class);
intent.putExtra("EXTRA_MESSAGE",vis);
startActivity(intent);
}
});
}
}
Using [TextUtils][1] check isEmpty() text inside your onClick:
#Override
public void onCreate(Bundle savedInstanceState){
EditText t1=(EditText)findViewById(R.id.a);
EditText t3=(EditText)findViewById(R.id.c);
EditText t4=(EditText)findViewById(R.id.d);
Button bu1 = (Button) findViewById(R.id.bu);
bu1.setOnClickListener(this);
}
#Override
public void onClick(View message){
boolean foundEmpty = false;
if(TextUtils.isEmpty(t1.getText())) {
foundEmpty = true;
t1.setError("Please Enter a value");
}
if(TextUtils.isEmpty(t2.getText()){
foundEmpty = true;
t2.setError("Please Enter a value");
}
if(TextUtils.isEmpty(t3.getText()){
foundEmpty = true;
t3.setError("Please enter a value");
}
if(!foundEmpty){
/* none of your text fields are empty */
int f1, f3, f4;
f1 =Integer.parseInt(e1);
f4=Integer.parseInt(e4);
f3=Integer.parseInt(e3);
final StringBuilder sb = new StringBuilder();
for( float i= (float)0.1;i<=5;i=i+(float) .1) {
sb.append(String.format("%.1f", i)+
" mcg = "+
(f1*60*i*f4)/(f3*1000)+"\n");
}
final String vis = sb.toString();
Intent intent = new Intent(message.getContext(), Screen2.class);
intent.putExtra("EXTRA_MESSAGE", vis);
startActivity(intent);
}
}
From what I gather from your question, you're getting an error when bu1 is clicked, and at least one of the EditTexts is empty. This is because you're calling Integer.parseInt() on an empty String. The following code will check if the boxes are empty, and show a Toast if any are. It will also show a Toast if the user enters anything that's not a valid number:
public class Screen1 extends Activity
{
private static final String EXTRA_MESSAGE = "extra_msg";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.screen1);
final EditText t1 = (EditText)findViewById(R.id.a);
final EditText t3 = (EditText)findViewById(R.id.c);
final EditText t4 = (EditText)findViewById(R.id.d);
Button bu1 = (Button)findViewById(R.id.bu);
bu1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View message)
{
int f1,f3,f4;
String e1 = t1.getText().toString();
String e3 = t3.getText().toString();
String e4 = t4.getText().toString();
if (e1.equals("") || e3.equals("") || e4.equals(""))
{
Toast.makeText(Screen1.this, "Please enter all numbers.", Toast.LENGTH_SHORT).show();
return;
}
try
{
f1 = Integer.parseInt(e1);
f4 = Integer.parseInt(e4);
f3 = Integer.parseInt(e3);
StringBuilder sb = new StringBuilder();
for (float i = 0.1f; i <= 5; i = i + .1f)
{
sb.append(String.format("%.1f", i) + " mcg = " + (f1 * 60 * i * f4) / (f3 * 1000) + "\n");
}
Intent intent = new Intent(Screen1.this, Screen2.class);
intent.putExtra(EXTRA_MESSAGE, sb.toString());
startActivity(intent);
}
catch (NumberFormatException e)
{
Toast.makeText(Screen1.this, "Invalid numbers.", Toast.LENGTH_SHORT).show();
}
}
}
);
}
}
I have an app here which adds the number. I have 4 edittexts here. What I want to happen is that when i entered none in one of the edittexts, it will assume that I entered 0. How can it be done? Here is my code:
public class Order extends Activity {
Button GoBackHome;
private Button button1;
private EditText txtbox1,txtbox2,txtbox3,txtbox4;
private TextView tv;
Button PayNow;
#Override
public void onBackPressed() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.order);
GoBackHome = (Button) findViewById(R.id.gohomebutton);
PayNow = (Button) findViewById(R.id.button2);
txtbox1= (EditText) findViewById(R.id.editText1);
button1 = (Button) findViewById(R.id.button1);
tv = (TextView) findViewById(R.id.editText5);
txtbox2= (EditText) findViewById(R.id.editText2);
txtbox3= (EditText) findViewById(R.id.editText3);
txtbox4= (EditText) findViewById(R.id.editText4);
button1.setOnClickListener(new clicker());
GoBackHome.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Intent i = new Intent(Order.this, MainActivity.class);
startActivity(i);
}
});
PayNow.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final Intent i = new Intent(Order.this, Payment.class);
startActivity(i);
}
});
}
class clicker implements Button.OnClickListener
{
public void onClick(View v)
{
String a,b,c,d;
Integer vis;
a = txtbox1.getText().toString();
b = txtbox2.getText().toString();
c = txtbox3.getText().toString();
d = txtbox4.getText().toString();
vis = Integer.parseInt(a)*2+Integer.parseInt(b)*3+Integer.parseInt(c)*4+Integer.parseInt(d)*5;
tv.setText(vis.toString());
}
}
}
You can do as Tushar said or you can initialize the value in the XML. Something like
<EditText
android:name="#+id/editText1"
android:text="0"/>
FYI you might also find it cleaner to handle your button clicks on xml like:
<Button
android:name="#+id/btn1"
android:onClick="handleClicks"/>
and then in java you'd have a public void method:
public void handleClicks(View clickedView){
if(clickedView.getId() == btn1.getId(){
...
} else if (...){}
}
initialize as :
txtbox1.setText("0");
Check the EditText length when you get it
String value = null;
if(ed.getText().length()){
value = textBox.getText().toString();
} else
value = 0+"";
You can set android:hint="0" in your XML file, then, in your code, you can check if it's empty (maybe using TextUtils.isEmpty()) and setting some variable to 0.
android:hint="0" will make a "0" appear in your EditTexts, but the "0" will disappear when anything is inputted.
Then you can change the onClick() to this:
class clicker implements Button.OnClickListener {
public void onClick(View v) {
String a,b,c,d;
Integer vis;
a = txtbox1.getText().toString();
b = txtbox2.getText().toString();
c = txtbox3.getText().toString();
d = txtbox4.getText().toString();
try {
vis = Integer.parseInt(a)*2+Integer.parseInt(b)*3+Integer.parseInt(c)*4+Integer.parseInt(d)*5;
tv.setText(vis.toString());
} catch (NumberFormatException e) {
vis = "0";
}
// Do something with "vis"
}
}
Or you can create a method to check a value, try to parse to an int or return a default value.
public int getInt(String edtValue, int defaultValue) {
int value = defaultValue;
if (edtValue != null) {
try {
value = Integer.parseInt(edtValue);
} catch (NumberFormatException e) {
value = defaultValue;
}
}
return value;
}
Then you change your call to
vis = this.getInt(a, 0) * 2 + this.getInt(b, 0) * 3 + this.getInt(c, 0) * 4 + this.getInt(d, 0) * 5;
I need help trying to fix my code. I thought it was simple (probably is) but I can't get it. I am have a simple adding calculator. It works fine, but if I leave 1 or both Number text fields empty, the program crashes.
I have my if statement, but apparently I am not telling it to do the right thing.
public class MainActivity extends Activity {
Double firstNum, secondNum, answerNum;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText first = (EditText) findViewById(R.id.txtFirst);
final EditText second = (EditText) findViewById(R.id.txtSecond);
final TextView answer = (TextView) findViewById(R.id.txtAnswer);
Button calc = (Button) findViewById(R.id.btnCalc);
calc.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// convert pulled info to double using variable names
firstNum = Double.parseDouble(first.getText().toString());
secondNum = Double.parseDouble(second.getText().toString());
if (first == null || second == null)
{
Toast.makeText(MainActivity.this, "Please Enter value", Toast.LENGTH_SHORT).show();
}
else {
// add numbers
answerNum = (firstNum + secondNum);
//set format
DecimalFormat total = new DecimalFormat ("###,###,###.##");
answer.setText("Answer is " + total.format(answerNum));
}
}
});
}
}
You have exception because of line: Double.parseDouble(second.getText().toString()), it cannot parse empty string to double, so you should add some validation code.
If you want to validate edittext means try this following code it will work fine.
public class MainActivity extends Activity {
double firstNum = 0;
double secondNum = 0, answerNum;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText first = (EditText) findViewById(R.id.editText1);
final EditText second = (EditText) findViewById(R.id.editText2);
final TextView answer = (TextView) findViewById(R.id.textView1);
Button calc = (Button) findViewById(R.id.button1);
calc.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (first.getText().toString().equals("")
|| second.getText().toString().equals("")) {
Toast.makeText(MainActivity.this, "Please Enter value",
Toast.LENGTH_SHORT).show();
} else {
firstNum = Double.parseDouble(first.getText().toString());
secondNum = Double.parseDouble(second.getText().toString());
answerNum = (firstNum + secondNum);
DecimalFormat total = new DecimalFormat("###,###,###.##");
answer.setText("Answer is " + total.format(answerNum));
}
}
});
}
}