To do value conversion both ways in android app - java

Im building a converter app and it's to convert centimetres into inches but i want it to do the opposite too, so the user can enter a value into either box to convert it. Ive tried various ways but won't work.
Here's my src code
package com.qub.buildersbuddy;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class CentInch extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cent_inch);
final EditText editCentimeters = (EditText) findViewById(R.id.editCentimeters);
final EditText editInches = (EditText) findViewById(R.id.editInches);
Button buttonConvert = (Button) findViewById(R.id.buttonConvert);
buttonConvert.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
double centimeters = Double.valueOf(editCentimeters.getText()
.toString());
double inches = centimeters * 0.393700787;
editInches.setText(String.valueOf(inches));
}
});
}
}

I know little about android but try to make something like this:
public void onClick(View arg0) {
double centimeters = 0;
double inches = 0;
//convert inches to centimeters
if(editCentimeters.getText().toString().isEmpty()){
inches = Double.valueOf(editInches.getText().toString());
//do the conversion
editCentimeters.setText(String.valueOf(inches));
}
//convert centimeters to inches
else if(editInches.getText().toString().isEmpty()){
centimeters = Double.valueOf(editCentimeters.getText().toString());
//do the conversion
editInches.setText(String.valueOf(inches));
}
}
if isEmpty() doesn't work try with .equals("") or == "". You get the point

Related

Value of sum is not changing when buttons are clicked android

I am trying to change the value of sum based on the buttons that are clicked on my app but the value of sum is not changing.
How do I get the value of sum to change based on the user's choice of button clicking? Thank you.
Here is my code attached below. Any help would be greatly appreciated.
package com.example.admin.project3;
import android.annotation.SuppressLint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.SeekBar;
import android.widget.TextView;
public class Project3 extends AppCompatActivity {
private TextView textView;
#SuppressLint("SetTextI18n")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_project3);
SeekBar seekBar = findViewById(R.id.mySeekbar);
textView = findViewById(R.id.mySeekBarNumber);
TextView myPrice = findViewById(R.id.myPrice);
RadioButton thickButton = findViewById(R.id.Thick);
RadioButton soggyButton = findViewById(R.id.Soggy);
RadioButton deliveryButton = findViewById(R.id.Deliver);
CheckBox anch = findViewById(R.id.Anchovies);
CheckBox pine = findViewById(R.id.Pineapple);
CheckBox garlic = findViewById(R.id.Garlic);
CheckBox okra = findViewById(R.id.Okra);
double myInches = Double.parseDouble(textView.getText().toString());
double sum = 0;
if(thickButton.isActivated()) sum += 2.50;
if(soggyButton.isActivated()) sum += 5.00;
if(deliveryButton.isActivated()) sum += 3.00;
if(anch.isChecked()) sum += .05*myInches;
if(pine.isChecked()) sum += .05*myInches;
if(garlic.isChecked()) sum += .05*myInches;
if(okra.isChecked()) sum += .05*myInches;
sum += myInches*.05;
String Price = Double.toString(sum);
myPrice.setText(Price);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#SuppressLint("SetTextI18n")
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
textView.setText(progress + " in");
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
}
You're checking if buttons are "activated" and if your CheckBoxes & RadioButtons are checked in onCreate(),
which means this test will only occur once the activity has started.
Instead, use setOnClickListener() on your Buttons, and setOnCheckedChangeListener()
for the RadioButtons & CheckBoxes, and then, whenever a change occurs - change the sum & set the text.
p.s
Variables shouldn't be named with capital letters in the beginning,
so change String Price to String price.

Android App Keeping Random Number the Same

I have posted with this code before but this is a different question.
When the 'guess' button is pressed, a random number is generated. The only problem with the code as it is is that it generates a new number every time regardless of whether the user guesses the right number or not. Ideally I want to give the user a 3 guess limit which would require the app to keep the random number generated the same and then reset after 3 incorrect attempts. I've come to a standstill as I've not done any java for a long time and it's perplexing me a bit in terms of incorporating it into this app.
Thanks in advance
package lab.mad.cct.c3375331task1;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Random;
public class Task1Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.task1_layout);
final TextView textResponse = (TextView) findViewById(R.id.txtResponse);
final TextView guessText = (TextView) findViewById(R.id.txtAnswer);
final EditText userGuess = (EditText) findViewById(R.id.etNumber);
Button pressMe = (Button) findViewById(R.id.btnGuess);
// When the button is clicked, it shows the text assigned to the txtResponse TextView box
pressMe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String randText = "";
Random randGen = new Random();
int ranNum = randGen.nextInt(5);
int userNumber = Integer.parseInt(userGuess.getText().to String());
int attempts = 0;
if (userNumber >19 ) {
guessText.setText("Please guess between 0 and 20");
} else if (userNumber == ranNum) {
guessText.setText("You got it!");
} else if (userNumber < ranNum) {
guessText.setText("Your answer is too low. Guess again!");
guessText.setBackgroundColor(Color.RED);
} else if (userNumber > ranNum) {
guessText.setText("Your answer is too high. Guess again!");
}
randText = Integer.toString(ranNum);
textResponse.setText("");
userGuess.setText("");
}
});
}
}
remove int userNumber = Integer.parseInt(userGuess.getText().to String()); from onClick(View v) because every time guessme button will be pressed, it will generate the new number.
declare some variables in your class
public static final int ATTEMPTS = 3;
public int attempt = 0;
public int currentRandomNumber = new Random().nextInt(5);
inside onClick();
if(attempt >= ATTEMPTS){
attempt = 0;
currentRandomNumber = new Random().nextInt(5);
} else {
attempt++;
}
// the rest of your code..
also, you are using rand..nextInt(5) but by the looks of your code you should be using ..nextInt(20)

Android App If Else Statements

I require a little bit of help with some java coding for my android guessing game app.
At the moment my if else statements cover whether a guess is too high, too low, or correct. What I want it to do is tell the user if the answer they give is close to the answer or far away from it. Say, within 50% or over 50% away. I can do if else where it uses numbers but I'm stumped when I'm trying to work out how to get it to work out the percentage based on the random number that the program generates. If it was a static number I'd be fine but I can't work it out this way.
Any help greatly appreciated.
package lab.mad.cct.c3375331task1;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Random;
public class Task1Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.task1_layout);
final TextView textResponse = (TextView) findViewById(R.id.txtResponse);
final TextView guessText = (TextView) findViewById(R.id.txtAnswer);
final EditText userGuess = (EditText) findViewById(R.id.etNumber);
Button pressMe = (Button) findViewById(R.id.btnGuess);
// When the button is clicked, it shows the text assigned to the txtResponse TextView box
pressMe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String randText = "";
Random randGen = new Random();
int ranNum = randGen.nextInt(5);
int userNumber = Integer.parseInt(userGuess.getText().toString());
int attempts = 0;
if (userNumber >19 ) {
guessText.setText("Please guess between 0 and 20");
} else if (userNumber == ranNum) {
guessText.setText("You got it!");
} else if (userNumber < ranNum) {
guessText.setText("Your answer is too low. Guess again!");
guessText.setBackgroundColor(Color.RED);
} else if (userNumber > ranNum) {
guessText.setText("Your answer is too high. Guess again!");
}
randText = Integer.toString(ranNum);
textResponse.setText("");
userGuess.setText("");
}
});
}
}
You can calculate the percentage difference between two numbers (the random number and the guessed number) like this:
public float percentDiff(int randomNumber, int guessedNumber) {
int diff = Math.abs(randomNumber - guessedNumber);
float diffPercentage = (float) diff / (float) randomNumber;
System.out.println("" + diffPercentage);
return diffPercentage;
}
A value >0.5 would be more than 50% off and vice versa.
If you want to calculate (on the fly) what the Users supplied number is percentage wise towards the randomly generated number then you can use a simple formula like:
int percentOf = ((userNumber * 100) / ranNum);

NullPointerException after changing class ( Code worked before )

I'm doing basic calculator for Android in Java. My calculator worked but i had all code in one class. Then i wanted to make code more readable and i created another Calculation class and i put calculation code in there. And now for some reason my app crashes. LogCat says: NullPointerException. (My app starts fine and then when i choose desirable currency to convert and when i click on ImageButton(convert) then app crashes). Here is my code:
CroToEu class:
package com.eu.calculator;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
public class CroToEur extends Activity {
TextView resultView;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.cro_to_eur);
final ImageButton convert = (ImageButton) findViewById(R.id.converButton);
convertButton(convert);
}
private void convertButton(final ImageButton convert) {
resultView = (TextView) findViewById(R.id.resultView);
convert.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
Calculate now = new Calculate();
now.croToEu();
if(event.getAction() == MotionEvent.ACTION_DOWN) {
convert.setImageResource(R.drawable.convert_button_ontouch);
checkForEmptyEntry();
} else if (event.getAction() == MotionEvent.ACTION_UP) {
convert.setImageResource(R.drawable.convert_button);
}
return false;
}
private void checkForEmptyEntry() {
if(Calculate.HRKfield.getText() == null || "".equals(Calculate.HRKfield.getText().toString())) {
resultView.setText("You left empty field");
} else {
resultView.setText(Calculate.HRKfield.getText()+" HRK = "+Calculate.fixDecimal+" EUR");
}
}
});
}
}
And my calculation class:
package com.eu.calculator;
import java.math.BigDecimal;
import android.app.Activity;
import android.widget.EditText;
public class Calculate extends Activity {
public static EditText HRKfield; //S tem dobimo vrednost iz polja edittext
public static double EUR = 0.133;//drži vrednost
public static Double HRK; // Možnost uporabe double za parsing
public static double result; // rezultat
public static BigDecimal fixDecimal; // rezultat pretvori na decimalko
public BigDecimal croToEu() {
HRKfield = (EditText) findViewById(R.id.enterField);
try {
HRK = Double.parseDouble(HRKfield.getText().toString()); //tukaj dobimo čisto številko, ki jo uporabnik vnese v polje
result = HRK * EUR;
fixDecimal = new BigDecimal(result);
fixDecimal = fixDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
} catch (NumberFormatException e) {
}
return fixDecimal;
}
}
Don' t extend Calculate class with Activity . Remove extends Activity in Calculate class
If you are trying to just create a helper class whcih does the calculation for you then don't extend Activity on your Calculate class. Instead get your croToEu method to return a variable and call this from the other class as follows.
Calculate now = new Calculate();
BigDecimal val = now.croToEu();
Id actually have the caluclate class as follows
public abstract class Calculate {
public static final double EUR = 0.133;//drži vrednost
public static BigDecimal croToEu(double hrkValue) {
BigDecimal fixDecimal = new BigDecimal(hrkValue * EUR);
fixDecimal = fixDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
return fixDecimal;
}
}
Then in your main activity class call
BigDecimal val = Calculate.croToEu(hrkValue);
if(Calculate.HRKfield.getText() == null || "
this is wrong to get the view of other activity .........
you are in CroToEur and your acessing the HRKfield of Calculate activity which will be null
So should pass the data from CroToEur activity to Calculate activity using intent and set that in HRKfield in onCreate of CroToEur
You are missing your onCreate() method and even setContentView in Calculate.class and so it cannot find your edittext HRKfield, and so it is throwing NullpointerException

If statements cause app to crash

I'm working on an app that involved comparing to numbers inputted by the user via text box, but wen I put in any if statements the program crashes whenever they are called. Otherwise the program runs just fine without any crashes or errors.
package improvecredit.app.basic;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.text.Editable;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class ImprovrCreditBasicActivity extends Activity {
/** Called when the activity is first created. */
public int minCredScore = 300;
public int maxCredScore = 850;
public int inputScore;
public int idealScore;
public Editable inputString;
public Editable idealString;
public EditText user;
public EditText desired;
public TextView output;
public Button submit;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
user = (EditText) findViewById(R.id.user_text);
desired = (EditText) findViewById(R.id.desired_text);
output = (TextView) findViewById(R.id.output_text);
submit = (Button) findViewById(R.id.submit_button);
//submit.setOnClickListener(new View.OnClickListener());
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//inputString = user.getText();
//idealString = desired.getText();
inputScore = Integer.getInteger(user.getText().toString());
idealScore = Integer.getInteger(desired.getText().toString());
if (inputScore >= 0 && idealScore >= 0){
if (inputScore < minCredScore || idealScore < minCredScore){
output.setText("Invalid Entries");
}
if (inputScore > maxCredScore || idealScore > maxCredScore){
output.setText("Invalid Entries");
}
if (inputScore > idealScore){
output.setText("Nice Credit Score!");
}
if (inputScore < idealScore){
output.setText("For more information on how to improve your credit score, please visit" + "/n" + "http://www.creditscoresandcredit.com/");
}
}
else{
output.setText("Please enter valid credit scores");
}
}
});
}
If someone can point out what may have been done wrong in the code I would really appreciate it.
On first glance, don't use Integer.getInteger(), use Integer.parseInt().
If that doesn't fix it, please include the crash log from the console so we can see exactly what exception is being raised.
I'm betting that there is a null value introduced. If you check for null before using the variables idealScore and inputScore in the If statement, it will avoid this error. Until you paste the error trace, we can only guess for you.

Categories

Resources