Why does my app crash when i click a certain button? - java

Hello everyone so i'm pretty new to Java and this code below will surely prove it.
I'd greatly appreciate any tip upon where i've gone wrong, thanks!
I'm trying to create a simple app that displays a random quote, and gives the chance to guess who said it.
Pretty sure the main issue has to do with ---> if (guessNameInt == whoSaidItInt)
because it only crashes when i click the button which enables the tryLuck if statement.
Heres my code below
int randomNum;
String whoSaidIt;
// quotes and numbers
public void randomRick(View view) {
if (randomNum == 0) {
Toast.makeText(getApplicationContext(), "Life is effort and I'll stop when I die!", Toast.LENGTH_LONG).show();
whoSaidIt = "Jerry";
}
if (randomNum == 1) {
Toast.makeText(getApplicationContext(), "Well look where being smart got you.", Toast.LENGTH_LONG).show();
whoSaidIt = "Jerry";
}
if (randomNum == 2) {
Toast.makeText(getApplicationContext(), "Ohh yea, you gotta get schwifty.", Toast.LENGTH_LONG).show();
whoSaidIt = "Rick";
}
}
public void tryLuck(View view) {
EditText guessedName = (EditText) findViewById(R.id.authorIs);
String guessedNameString = guessedName.getText().toString();
int guessNameInt = Integer.parseInt(guessedNameString);
int whoSaidItInt = Integer.parseInt(whoSaidIt);
if (guessNameInt == whoSaidItInt) {
Toast.makeText(getApplicationContext(), "Holy crow, Good job!", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(), "Try again", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Random randomGenerator = new Random();
randomNum = randomGenerator.nextInt(3);
}`

You're trying to convert a String to an Int. This will only work if the String is an actual int (ie a number), and not the name (Jerry or Rick). Use guessNameString.equals(whoSaidIt) instead.

Related

How to validate decimal input not allowing alone "." and empty field?

I'm writing a calculator on Android Studio, in Java, and the app crashes if the user call the result with a dot "." alone or let the EditText field in blank.
I'm looking for a solution for not allowing these two conditions happening, together or individualy, in each of the three fields.
I've already tried TextWatcher and if/else but without success.
The .xml file where the editText field are designed is already set for decimalNumber.
I've already tried this:
if(myfieldhere.getText().toString().equals(".")){myfieldhere.setText("0");}
For each "valor line" and else for the "finalresult" line if everything is fine. Both inside the setOnClickListener block. This is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.peso_layout);
result = findViewById(R.id.layresult);
conc = findViewById(R.id.layconc);
dose = findViewById(R.id.laydose);
peso = findViewById(R.id.laypeso);
calc = findViewById(R.id.laycalcpeso);
calc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
float valor1 = Float.parseFloat(peso.getText().toString());
float valor2 = Float.parseFloat(conc.getText().toString());
float valor3 = Float.parseFloat(dose.getText().toString());
float finalresult = valor1 * valor2 * valor3;
result.setText("The result is: " + finalresult);
}
});
}
The ideal output should be the app not crashing if these two conditions happen and sending an error message to the user that input is invalid.
What i'm receiving is the app crashing.
Thank you very much. I'm very beginner in Java and I'm few days struggling with this.
Dear Friend, Your directly trying to convert string input into float and then after your check value but do your code like Below.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
EditText edt1,edt2;
TextView txtans;
Button btnsum;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edt1=findViewById(R.id.edt1);
edt2=findViewById(R.id.edt2);
txtans=findViewById(R.id.txtans);
btnsum=findViewById(R.id.btnsum);
btnsum.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.btnsum){
float n1,n2;
String value1=edt1.getText().toString();
String value2=edt2.getText().toString();
if(value1.equals("") || value1.equals(".")){
n1=0;
}else {
n1= Float.parseFloat(value1);
}
if(value2.equals("")|| value2.equals(".")){
n2=0;
}else{
n2= Float.parseFloat(value2);
}
float ans=n1+n2;
txtans.setText(ans+"");
}
}
}
See In above code, First get value from edittext and then check wheather it contain null or "." inside it. if it contains then store 0.0 value in some variable. then after make sum and display in textbox.
calc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String myvalor = myfieldhere.getText().toString();
if(myvalor.equals(".") || myvalor.isEmpty())
{
// toast error : incorrect value
return;
}
try
{
float valor1 = Float.parseFloat(peso.getText().toString());
float valor2 = Float.parseFloat(conc.getText().toString());
float valor3 = Float.parseFloat(dose.getText().toString());
float finalresult = valor1 * valor2 * valor3;
result.setText("The result is: " + finalresult);
}
catch(Exception exp){// toast with exp.toString() as message}
}
});
use TextUtils for check empty String its better
if(TextUtils.isEmpty(peso.getText().toString())||
TextUtils.isEmpty(conc.getText().toString())||
TextUtils.isEmpty(dose.getText().toString())){
return;
}

EditText to Integer (Android)

I am attempting to convert an EditText, which is of type number in xml, to an Integer in order to calculate the value in seconds.
hoursIn = (EditText) findViewById(R.id.hoursET);
minIn = (EditText) findViewById(R.id.minET);
start = (Button) findViewById(R.id.startButton);
stop = (Button) findViewById(R.id.stopButton);
textViewTime = (TextView) findViewById(R.id.timeDisp);
inHr = Integer.parseInt(hoursIn.getText().toString());
inMin = Integer.parseInt(minIn.getText().toString());
hoursMs = hrsToMs(inHr);
minMs = minToMs(inMin);
totalTime = hoursMs + minMs;
When I comment the lines where inHr and inMin are initialized I get no error in runtime, however when I leave the code as it is above I get the following error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{dit.assignment3/dit.assignment3.Timer}: java.lang.NumberFormatException: Invalid int: ""
I have also attempted this while getting the same error starting at the same line of code:
final CounterClass timer = new CounterClass(totalTime, 1000);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (hoursIn != null)
{
inHr = Integer.parseInt(hoursIn.getText().toString());
hoursMs = hrsToMs(inHr);
}
if (minIn != null)
{
inMin = Integer.parseInt(minIn.getText().toString());
minMs = minToMs(inMin);
}
else
{
textViewTime.setText("PLEASE GIVE A TIME");
}
totalTime = hoursMs + minMs;
timer.start();
}
});
Thanks in advance :)
I'm certain that this codes blocks are exactly same as you've shown here. That means You are directly initializing EditText and immediately calling getText() method which causes Exception.
There wont be any value immediately after initialization so that you are getting NumberFormatException when calling Integer.parseInt to empty value.
So I suggest you to put these codes inside some event like buttonClicked like here, so that you can be sure that you've entered some texts. And It's better checking if empty as well,
public void buttonClicked(View v){
inHr = Integer.parseInt(hoursIn.getText().toString());
inMin = Integer.parseInt(minIn.getText().toString());
}
You will get an java.lang.NumberFormatException: Invalid int: "" whenever you try to parse an empty string to Integer. Thus you need to check whether the EditText is empty or not.
You could easily do that as below
if (hoursIn.getText().toString().matches("")) {
Toast.makeText(this, "You did not enter a text", Toast.LENGTH_SHORT).show();
return;
}
OR
you can simply do a check as below
if (hoursIn.getText().toString().equals("")) {
Toast.makeText(this, "You did not enter a text", Toast.LENGTH_SHORT).show();
return;
}
First you have to put the lines where you are reading from edittext inside some event like click of a button. Then check whether anything is entered in the edittext or not, then use try/catch clause to convert it into number.
Try this code.
Add a button to your activity xml file:
<Button
android:height="wrap_content"
android:width="wrap_content"
android:onClick="myClickHandler" />
hoursIn = (EditText) findViewById(R.id.hoursET);
minIn = (EditText) findViewById(R.id.minET);
start = (Button) findViewById(R.id.startButton);
stop = (Button) findViewById(R.id.stopButton);
textViewTime = (TextView) findViewById(R.id.timeDisp);
public void myClickHandler(View v){
if (hoursIn.getText().toString().matches("") || minIn.getText().toString().matches("")){
Toast.makeText(this, "You did not enter a text",Toast.LENGTH_SHORT).show();
return;
} else {
try {
inHr = Integer.parseInt(hoursIn.getText().toString());
inMin = Integer.parseInt(minIn.getText().toString());
hoursMs = hrsToMs(inHr);
minMs = minToMs(inMin);
totalTime = hoursMs + minMs;
Log.i("success");
} catch (NumberFormatException e) {
Toast.makeText(this, "Please enter number only",Toast.LENGTH_SHORT).show();
return;
}
}
}

Radiobutton behavior Android Studio

Simple problem to fix (I hope)...can't figure it out myself though.
I need one radio button to be un-checked or un-selected when the other is checked/selected.
Here is my code. Right now the app works fine but when the user goes to change the selection the first button doesn't clear:
Button convert = (Button) findViewById(R.id.btnConvert);
convert.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
weightEntered=Double.parseDouble(weight.getText().toString());
DecimalFormat tenth = new DecimalFormat("#.#");
if (lbToKilo.isChecked()) {
if (weightEntered <= 500) {
convertedWeight = weightEntered / conversionRate;
result.setText(tenth.format(convertedWeight) + " kilograms");
} else {
Toast.makeText(getApplicationContext(), "Pounds must be less than 500.", Toast.LENGTH_LONG).show();
}
}
if (kiloToLb.isChecked()) {
if (weightEntered <= 225) {
convertedWeight = weightEntered * conversionRate;
result.setText(tenth.format(convertedWeight) + " pounds");
} else {
Toast.makeText(getApplicationContext(), "Kilos must be less than 225.", Toast.LENGTH_LONG).show();
}
}
}
});
You simply need to group your RadioButtons in a RadioGroup.
That's all you need to get some mutually exclusive RadioButtons.
For your reference: http://developer.android.com/guide/topics/ui/controls/radiobutton.html

Can't get my if statement to work?

I know this has got to be simple. But for the life of me i don't know why i can't get this right.
Ok so I want to go from a listview page (got that) then click a switch to make it go to the next page (also got that.) Then I want a int to tell me which position I am on form the last page (might be working?) now i can't get the If Else statement to work in the page.
public class NightmareParts extends Activity
{
public int current_AN_Number = NightmareList.AN_position_num;
private TextView edit_title;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.part_layout);
// isn't working here. Why?
// test_edit = (TextView)findViewById(R.id.directions_tv);
// test_edit.setText(R.string.directions_text_two);
// works without this being in here.
setDoneButtonListener();
}
//Set up the Done button to initialize intent and finish
private void setDoneButtonListener()
{
Button doneButton = (Button) findViewById(R.id.back_button);
doneButton.setOnClickListener (new View.OnClickListener() {
#Override
public void onClick(View v)
{
finish();
}
});
}
private void editTitle()
{
if (current_AN_Number = 1)
{
edit_title = (TextView)findViewById(R.id.part_title);
edit_title.setText(R.string.AN_title_1);
}
}
}
The current_AN_number is coming from the last page.
Your if statement is incorrect:
if (current_AN_Number = 1)
You've used the assignment operator, when you wanted to compare it with the == operator:
if (current_AN_Number == 1)
if (current_AN_Number = 1)
Should be
if (current_AN_Number == 1)
You're not setting current_AN_Number to be 1, you are comparing if it is equal to 1. So use ==.
test_edit = (TextView)findViewById(R.id.directions_tv);
is not working because test_edit is never declared.

Toast isn't working, can't see why not

So I'm trying to write an activity that has two spinners and a button, when the two spinners are selected and the button pressed it'll take you to another activity. Except for one combination, which should produce a Toast saying that you can't do this.
Anyway, this is the code:
public void onClick(View v) {
String spinnerchoice1 = ("spinner1Value");
String spinnerchoice2 = ("spinner2Value");
if((spinnerchoice1.equals("Walking")) && (spinnerchoice2.equals("Hiking"))){
Toast.makeText(getBaseContext(), "I'm sorry, this is not possible.", Toast.LENGTH_LONG).show();
}else{
Intent i = new Intent(GetDirections.this.getApplicationContext(), DirectionDisplay.class);
i.putExtra("spinner1Value", transportSpinner.getSelectedItem().toString());
i.putExtra("spinner2Value", locationSpinner.getSelectedItem().toString());
GetDirections.this.startActivity(i);
}
}
Can anyone tell me where I'm going wrong?
Thanks
You are comparing two hard-coded strings, the if condition will never execute. Change the code to:
public void onClick(View v) {
String transport = transportSpinner.getSelectedItem().toString();
String location = locationSpinner.getSelectedItem().toString();
if ("Walking".equals(transport) && "Hiking".equals(location)) {
Toast.makeText(getBaseContext(), "I'm sorry, this is not possible.", Toast.LENGTH_LONG).show();
} else {
Intent i = new Intent(GetDirections.this.getApplicationContext(), DirectionDisplay.class);
i.putExtra("spinner1Value", transport);
i.putExtra("spinner2Value", location);
GetDirections.this.startActivity(i);
}
}
If this is your actual code then your if is never going to evaluate to true because you are setting the strings to values that are not "Walking" and "Hiking"
these two lines:
String spinnerchoice1 = ("spinner1Value");
String spinnerchoice2 = ("spinner2Value");
need to be something like this (assuming that you spinner just contains String objects and not some other type):
String spinnerchoice1 = transportSpinner.getSelectedItem().toString();
String spinnerchoice2 = locationSpinner.getSelectedItem().toString();

Categories

Resources