Android - Program crashes when there is not input in editText fields - android

So i'm having a problem in my code which is probably simple to solve but its my first app so cut me some slack. When I enter no values in my editText box my app crashes. Im semi aware why it occurs but I cant seem to solve it.
public void onButtonClick( View v)
{
Double n1 , n2 , answer1;
EditText e1 = (EditText) findViewById(R.id.num1);
EditText e2 = (EditText) findViewById(R.id.num2);
TextView t1 = (TextView) findViewById(R.id.answer);
n1 = Double.parseDouble(e1.getText().toString());
n2 = Double.parseDouble(e2.getText().toString());
if (n1.toString().length()< 0 || n2.toString().length()< 0){
t1.setText("Please enter a number into both the base and height");
}else {
answer1 = ((n1 * n2) / 2);
t1.setText(Double.toString(answer1));
}
}

First check if there is input in both EditTexts and only if there is convert it to Double:
if (e1.getText().length() == 0 || e2.getText().length() == 0) {
t1.setText("Please enter a number into both the base and height");
} else {
n1 = Double.parseDouble(e1.getText().toString());
n2 = Double.parseDouble(e2.getText().toString());
answer1 = ((n1 * n2) / 2);
t1.setText(Double.toString(answer1));
}
EditText.getText() will never return null (as per source code) so it's safe to use methods on it (such as length().

if (!e1.getText().toString().isEmpty()) {
// do stuff
}

Related

calculate percentage and display in a texview android studio

I am developing an application where I pass 1 variables int through a string of an activity to next activity, in the next activity I take that string and return it again and an int, then I calculate a percentage and display and a textview, the past variable and approx1 so I check if it is not empty, then I calculate the percentage ex: ((3/45) * 100) and display in a text view, reviewing again for string ... but in any way I make a mistake, what can be ?
Bundle bundle = getIntent (). GetExtras ();
String aprox1 = bundle.getString ("aprox1");
if (aprox1! = null)
try {
num3 = Integer.parseInt (aprox1);
 result = Math.round ((num3 / 45) * 100);
 TextView counter2 = (TextView) findViewById(R.id.textView16);
String abcString2 = Integer.toString (result);
counter2.setText (abcString2);
}
 catch (NumberFormatException e) {
 }
You need to have {} after the if statement like so:
if (aprox1! = null) {
try {
num3 = Integer.parseInt (aprox1);
result = Math.round ((num3 / 45) * 100);
TextView counter2 = (TextView) findViewById(R.id.textView16);
String abcString2 = Integer.toString (result);
counter2.setText (abcString2);
}
catch (NumberFormatException e) {
}
}
Its also worth noting that because num3 is an integer when you divide it by 45 you will get an Integer not a percentage.
To fix this issue, make num3 a double or cast either num3 or 45 to a double before computing the division.
For example, a simple fix would include changing line 4 to the following:
result = Math.round ((num3 / 45.0) * 100);

Android - Is there a better way to toggle a radio button on page load?

My current code fetches a database cursor when the page loads and then pre-fills the form. I am trying to check the proper radio button based whether user gender is "Male" or "Female". My 2 radio buttons is in a RadioGroup;
Java code:
public void fillData(Cursor row) {
sId = (EditText)findViewById(R.id.studentid);
fName = (EditText)findViewById(R.id.firstName);
lName = (EditText)findViewById(R.id.lastName);
gender = (RadioButton)findViewById(R.id.male);
gender2 = (RadioButton)findViewById(R.id.female);
course = (EditText)findViewById(R.id.course);
age = (EditText)findViewById(R.id.age);
address = (EditText)findViewById(R.id.address);
sId.setText(row.getString(0));
fName.setText(row.getString(1));
lName.setText(row.getString(2));
String temp = row.getString(3);
if (temp == "Male") {
gender.toggle();
} else {
gender2.toggle();
}
course.setText(row.getString(4));
age.setText(row.getString(5));
address.setText(row.getString(6));
}
With this code I am only getting the female radio button checked even if temp is "Male". I tested using Toast.maketext
You should compare string with equals method
if ("Male".equals(temp) {
gender.toggle();
} else {
gender2.toggle();
}
You can also use equalsIgnoreCase() in case of string matching this will be a good approach.
if ("Male".equalsIgnoreCase(temp) {
gender.toggle();
} else {
gender2.toggle();
}

How to Double Score the point for a word?

I have my first Android app and I am having difficulty on how can I double the point for a word/words whenever a player click an imageview. Basically, I want it to function like this: If the player hasn't click the imageview, the pointing system stays the same. If the player clicks the imageview the a message will pop-out (a toast perhaps telling the player that the points for the next 3 words will be doubled). How can I make this happen? How can I double the points for the 3 consecutive words without exceeding?
Here's my code for searching and calculation
//CALCULATE SCORE
private int optionTxtView = 0 ; //which textview to use for addition purposes
private int addClick = 0 ; //No. of clicks for search for calculation
private void calculate(){
x = Integer.parseInt(tv3.getText().toString().replaceAll("\\s",""));
y = Integer.parseInt(tv2.getText().toString().replaceAll("\\s",""));
z = x + y;
score.setText(Integer.toString(z));
}
//SEARCH WORD, DISPLAYING SCORE
public void viewWord(View view)
{
String s1= search.getText().toString(); //What word to search
String s2= dbHelper.getData(s1); // If in db, display equivalent score
if(optionTxtView == 0){
//display the score on textview1
tv2.setText(s2);
optionTxtView = 1;
}
else{
if(optionTxtView == 1){
//display the score on textview2
tv3.setText(s2);
optionTxtView = 0;
}
}
//Display search word/s
adapter.add(text.getText().toString());
adapter.notifyDataSetChanged();
if(addClick ==0){
calculate();
addClick = 1;
text.setText("");
generatedString="";
}
else{
if(addClick == 1){
calculate();
addClick = 2;
text.setText("");
generatedString="";
}}
boolean sDouble = false
imgView.setOnClickListener(new View.OnClickListener() {
//#Override
public void onClick(View v) {
// Show your Toast message
// double = true;
}
});
and where you are running your game code check the value of sDouble, if its true then double the scoring system inside a for loop, or set an integer value to 0 and increment it for next 3 words, after that set the value of sDouble back to false.
You may also need to make sure that the user doesn't click on the image for the next 3 tries after clicking it once.
Update:
Since your score is a String, you need to parse it to an Integer before performing any mathematical operation, use Integer.parseInt(s2).

Android Else-If, always hits Else for cat calculator that wants catnip

Working on my first Android app, Cat Calculator. Calculations work fine after the cat is purring, but if it wants catnip or fancy feast petting it again reaches the debug error from the final "Else" statement instead of the cat biting or ignoring you.
Providing full code, but the error is likely in the last 10 lines...
Appreciate any help you can provide. -Michael
/** Called when the user clicks the CatCalculator button */
public void doCalculation(View view) {
TextView homeAnswerView = (TextView) findViewById(R.id.homeAnswerView);
TextView catActivityView = (TextView) findViewById(R.id.catActivityView);
Random randomcatmood = new Random();
double catmood = randomcatmood.nextDouble();
if (catActivityView.getText().equals("cat calculator is sleeping on calculator")) {
if (catmood <= 0.33) {
catActivityView.setText("cat calculator starts purring");
} else if (catmood <= 0.66) {
catActivityView.setText("cat calculator wants fancy feast");
} else {
catActivityView.setText("cat calculator wants a catnip toy");
}
} else if (catActivityView.getText().equals("cat calculator starts purring")) {
int answerInt;
String answer;
EditText numberOne = (EditText) findViewById(R.id.number1);
EditText numberTwo = (EditText) findViewById(R.id.number2);
int numberOnee = Integer.parseInt(numberOne.getText().toString());
int numberTwoo = Integer.parseInt(numberTwo.getText().toString());
answerInt = numberOnee * numberTwoo;
answer = Integer.toString(answerInt);
homeAnswerView.setText(answer);
} else if (catActivityView.equals("cat calculator wants fancy feast")) {
catActivityView.setText("cat calculator bites you for petting it now!");
} else if (catActivityView.equals("cat calculator wants a catnip toy")) {
catActivityView.setText("cat calculator bites you for petting it now!");
} else if (catActivityView.equals("cat calculator bites you for petting it now!")) {
catActivityView.setText("cat calculator ignores you");
} else if (catActivityView.equals("cat calculator ignores you")) {
} else {
catActivityView.setText("debug: this should never happen");
}
}
You're missing a bunch of getText() in your latter lines.
Code like
catActivityView.equals("cat calculator wants fancy feast")
Compares the TextView to the String you give, not the content of the TextView. You want something like:
catActivityView.getText().equals("cat calculator wants fancy feast")
Your first two conditions are correct. All the ones after those two are missing getText().

Force close on clicking on radio button

Whenever I try to press a radio button on my emulator, it just force closes!
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b = (Button)this.findViewById(R.id.btn_confirm);
b.setOnClickListener(this);
RadioButton radio_ctf = (RadioButton) findViewById(R.id.radio_ctf);
RadioButton radio_ftc = (RadioButton) findViewById(R.id.radio_ftc);
radio_ctf.setOnClickListener(this);
radio_ftc.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
TextView tv = (TextView)this.findViewById(R.id.tv_result);
EditText et = (EditText)this.findViewById(R.id.et_name);
RadioButton radio_ctf = (RadioButton) findViewById(R.id.radio_ctf);
RadioButton radio_ftc = (RadioButton) findViewById(R.id.radio_ftc);
double y = 0;
int x = Integer.parseInt(et.getText().toString());
if(radio_ctf.isChecked())
{
y = ((double)x * 1.8) + 32;
}
if(radio_ftc.isChecked())
{
y = ((double)x - 32) * 0.555;
}
String text = "Result:" + y;
tv.setText(text);
first of all, look at the error (DDMS button, if you use eclipse) in the DDMS console.
There are a lot of reason for such error. Practically it mean, that there is unhandled java exception.
my guess that you are getting an Exception due to the value that you pass to Integer.parseInt()
you need to validate the string before parsing it.
to validate the string read the following post:
Java library to check whether a String contains a number without exceptions

Categories

Resources