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.
Related
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)
My Simple Interest calculator is crashing with a null pointer exception error, not sure what the problem is, there are no errors in the IDE before I complile, this is new to me. Here is my code and logcat: edit: Icouldn't post a logcat as the editor thinks it's code and I can't get it to format correctly
Code:
package com.codeherenow.sicalculator;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.SeekBar;
public class SICalculatorActivity extends Activity
implements SeekBar.OnSeekBarChangeListener, View.OnClickListener{
private int years;
private TextView YT;
private SeekBar bar;
private EditText principal = (EditText) findViewById(R.id.PA_field);
private EditText interest = (EditText) findViewById(R.id.IR_field);
public EditText pvalue;
public EditText ivalue;
private double mPvalue = 0;
private double mIvalue = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sicalculator);
bar = (SeekBar)findViewById(R.id.seekBar);
bar.setOnSeekBarChangeListener(this);
pvalue = (EditText) principal.getText();
ivalue = (EditText) interest.getText();
String s = principal.getText().toString();
mPvalue = Double.parseDouble(s);
String s2 = interest.getText().toString();
mIvalue = Double.parseDouble(s2);
}
#Override
public void onProgressChanged (SeekBar seekBar,int i, boolean b){
years = i;
YT = (TextView) findViewById(R.id.Years);
YT.setText(years + " Year(s)");
}
#Override
public void onStartTrackingTouch (SeekBar seekBar){
}
#Override
public void onStopTrackingTouch (SeekBar seekBar){
}
#Override
public void onClick(View view) {
TextView fTextView = (TextView) findViewById(R.id.finalText);
double finValue = mPvalue * (mIvalue/100) * years;
fTextView.setText("The interest for " + pvalue + "at a rate of " + ivalue + "for " + years + "year(s) is " + finValue);
}
}
You can't instantiate view variables by calling findViewById as you're declaring them. You have to declare them first and then instantiate either in onCreate or some method invoked after the Activity is bound with the view. Make sure to do it after setContentView(R.layout.sicalculator);
Okay, after seeing your layout, stacktrace and reading more in to your code, I saw that there are fundamental issues which ought to give you more crashes, so let's fix them.
First, pvalue and ivalue variables are unnecessary! Remove them.
Related: You cannot assign an Editable to an EditText. So this line is invalid ivalue = (EditText) interest.getText(); Because getText() returns an Editable. But these are all redundant and unnecessary anyways.
Second, in onCreate method, let's just initialize views and not try to get values and parse them yet; the user (or you) haven't interacted nor entered any values there yet; so trying to parse null values in to Doubles will crash your app.
Your onCreate method should look something like this. (Note that I'm also initializing your button and setting the click listener here).
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.sicalculator);
principal = (EditText) findViewById(R.id.PA_field);
interest = (EditText) findViewById(R.id.IR_field);
bar = (SeekBar) findViewById(R.id.seekBar);
bar.setOnSeekBarChangeListener(this);
calcBtn = (Button)findViewById(R.id.calc_btn);
calcBtn.setOnClickListener(this);
}
Now, you should get the values and parse them in your onClick listener - only when the user has entered values and clicked on the Calculate button, so your onClick() method should look something like this:
#Override
public void onClick(View view)
{
TextView fTextView = (TextView) findViewById(R.id.finalText);
mPvalue = Double.valueOf(principal.getText().toString());
mIvalue = Double.valueOf(interest.getText().toString());
double finValue = mPvalue * (mIvalue / 100) * years;
fTextView.setText("The interest for " + mPvalue + "at a rate of " + mIvalue + "for " + years + "year(s) is " + finValue);
}
And that should clear the logic and order or declaring, initializing, retrieving values from variables for you. I hope this explains how Java and Android basics work.
Oh by the way, I actually ran the code and it's running on my phone so this isn't just off the top of my head. If this helped you, please accept the answer.
Best wishes,
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
While trying to run my app, I noticed that a few errors claiming that many variables can not be resolved, even though declared in the code
i changed it to the following code, but once I enter the app, it collapses:
public String GetErr(){
String error="";
if(Facebook_name.toString().equals("")&& Facebook_chk.isChecked())//check with title if not available.
{
error+="facebook account not entered/n";//also check if not available
}
if(Name.toString().equals(""))
error+="Name not entered/n";
if(Id.toString().contains("[a-zA-Z]+") || Id.toString().equals(""))
error+="Id entered is invalid/n";
if(Pass.toString().length()<5 || Pass.toString().equals(""))
error+="Passwords must contain 5 or more digits";
// int day= Date.getDayOfMonth();
// int month = Date.getMonth();
// int year=Date.getYear();
//Calendar enter = Calendar.getInstance();
// Calendar today = Calendar.getInstance();
// enter.set(year,month,day);
// today.set(Calendar.YEAR,Calendar.MONTH,Calendar.DAY_OF_MONTH);
//if((enter.getTime().before(today.getTime())))
// error+="Date entered either passed or not available.";
return error;
}
EDIT: Now the geterr() returns an empty string at all times.
You are declaring variables in the onCreate() method, so that is their scope. You can not use them outside this function. So when you use them in the GetErr() method, you get an error. You can solve this by moving the variables you need in multiple methods to global variables (so declare them in the class instead of in the method.
Edit
package com.example.app;
//import java.util.Calendar;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
//import android.widget.DatePicker;
import android.widget.TextView;
public class Second extends Activity implements OnClickListener {
CheckBox Facebook_chk;
TextView Facebook_name;
TextView Name;
TextView Id;
TextView Txterr;
TextView Pass;
Button Btn1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.second);
Btn1 = (Button) findViewById(R.id.Btn1);
Facebook_chk = (CheckBox)findViewById(R.id.Cfbook);//Represents the facebook checkbox.
Facebook_name = (TextView)findViewById(R.id.Face);//represents the facebook text.
Name = (TextView)findViewById(R.id.Name);//represents the Name text.
Id = (TextView)findViewById(R.id.Id);//represents the Id text.
Txterr = (TextView)findViewById(R.id.Txterr);//represents the Id text.
Pass = (TextView)findViewById(R.id.Pass);//represents the Pass text.
Btn1.setOnClickListener(this);
Facebook_chk.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
if(Facebook_chk.isChecked())
Facebook_name.setEnabled(true);
else
Facebook_name.setEnabled(false);
;
}
});
}
public String GetErr(){
String error="";
if(Facebook_name==null && Facebook_chk.isChecked())//check with title if not available.
{
error+="facebook account not entered/n";//also check if not available
}
if(Name==null)
error+="Name not entered/n";
if(Id.toString().contains("[a-zA-Z]+") || Id==null)
error+="Id entered is invalid/n";
if(Pass.toString().length()<5)
error+="Passwords must contain 5 or more digits";
// int day= Date.getDayOfMonth();
// int month = Date.getMonth();
// int year=Date.getYear();
//Calendar enter = Calendar.getInstance();
// Calendar today = Calendar.getInstance();
// enter.set(year,month,day);
// today.set(Calendar.YEAR,Calendar.MONTH,Calendar.DAY_OF_MONTH);
//if((enter.getTime().before(today.getTime())))
// error+="Date entered either passed or not available.";
return error;
}
#Override
public void onClick(View v) {
if(v == Btn1){
String err = GetErr();
if(err != ""){
Txterr.setText(err);
}
}
}
}
define:
CheckBox Facebook_chk
TextView Facebook_name
TextView Name
TextView Id
TextView Txterr
TextView Pass
As Global Variables, like:
public class Second extends Activity implements OnClickListener {
CheckBox Facebook_chk;
TextView Facebook_name;
TextView Name;
TextView Id;
TextView Txterr;
TextView Pass;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.second);
Facebook_chk = (CheckBox)findViewById(R.id.Cfbook);//Represents the facebook checkbox.
Facebook_name = (TextView)findViewById(R.id.Face);//represents the facebook text.
Name = (TextView)findViewById(R.id.Name);//represents the Name text.
Id = (TextView)findViewById(R.id.Id);//represents the Id text.
Txterr = (TextView)findViewById(R.id.Txterr);//represents the Id text.
Pass = (TextView)findViewById(R.id.Pass);//represents the Pass text.
...
}
...
}
UPDATE:
If you would like to make a View to respond for Click Event, you'll need to make sure you've set that View clickable.
Since you did:
View v = findViewById(R.id.Btn1);
v.setOnClickListener((OnClickListener) this);
I've no idea R.id.Btn1 is really a Button or just a View. If it is a Button, please change to:
Button button = findViewById(R.id.Btn1);
button.setOnClickListener(this);
If it's not a button, just some View and you want it to respond to your Click, please add one line after findViewById
v.setClickable(true);
Again, if you intend to use this v sometime later in your code, you need to declare it as a global variable just like you did on your TextViews
Ref public void setClickable (boolean clickable)
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.