I think I'm getting confused about the activity lifecycle here, I'm trying to perform a simple weights conversion, nothing spectacular.
the user enters a value, selects whether they want it converted to lbs or kgs and when they press 'Convert' it should spit out the converted values, lookng at the stack trace it seems to have a problem with the parseInt im using.
public class WeightConverter extends Activity implements OnClickListener, OnCheckedChangeListener {
Button convertWeight;
TextView conversionResults;
EditText enterWeight;
RadioGroup weightPicker;
RadioButton radKG, radLB;
double weightValue, convertedWeight;
String weightString;
String measurement;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.weightconverter);
initializeVariables();
}
private void initializeVariables() {
convertWeight = (Button) findViewById(R.id.btnConvertWeight);
conversionResults =(TextView) findViewById(R.id.tvWeightConversion);
enterWeight =(EditText) findViewById(R.id.etWeightToConvert);
weightPicker = (RadioGroup) findViewById(R.id.rgWeightType);
radKG = (RadioButton) findViewById(R.id.radKG);
radLB = (RadioButton) findViewById(R.id.radLB);
convertWeight.setOnClickListener(this);
}
#Override
public void onClick(View v) {
;
switch (v.getId()) {
case R.id.btnConvertWeight:
weightValue = Double.parseDouble(enterWeight.getText().toString());
conversionResults.setText(weightValue + " = " + weightString + measurement);
break;
}
}
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.radKG:
convertedWeight = weightValue / 2.2;
measurement = " Kilograms";
break;
case R.id.radLB:
convertedWeight = weightValue * 2.2;
measurement = " Pounds";
break;
}weightString = String.valueOf(convertedWeight);
}
}
I'm not convinced that your onCheckedChanged method is being called at all (have you seen the code entering it using the debugger?).
Try assigning it to your weightPicker radio group as below instead:
weightPicker.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId)
{
weightValue = Integer.parseInt(enterWeight.getText().toString());
switch (checkedId) {
case R.id.radKG:
convertedWeight = weightValue / 2.2;
measurement = " Kilograms";
break;
case R.id.radLB:
convertedWeight = weightValue * 2.2;
measurement = " Pounds";
break;
}
});
You have weightValue declared as a double but trying to parse integer
double weightValue,
Instead use
weightValue = Double.parseDouble(enterWeight.getText().toString());
I would also suggest error checking on your entered value in case the user enters a non digit
Related
I had a calculator app to do as a project and I'm a bit lost. My teacher only put the java text itself, but there's some elements in the xml document that I need to add.
Here is some problems with my main document. My onClickfunctions are underlined as unused.
public class MainActivity extends AppCompatActivity {
private TextView _screen;
private String display="";
private String currentOperator="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_screen=(TextView) findViewById(R.id.textView);
_screen.setText(display);
}
private void updateScreen() {
_screen.setText(display);
}
private void **onClickNumber**(View v) {
Button b = (Button) v;
display+=b.getText();
updateScreen();
}
public void onClickOperator(View v) {
Button b= (Button) v;
display+=b.getText();
currentOperator=b.getText().toString();
updateScreen();
}
private double operateArithmetic(String a, String b, String op) {
switch (op) {
case "+": return(Double.valueOf(a) + Double.valueOf(b));
case "-": return(Double.valueOf(a) - Double.valueOf(b));
case "x": return(Double.valueOf(a) * Double.valueOf(b));
case "\u00f7": try{
return(Double.valueOf(a) / Double.valueOf(b));
} catch(Exception e){
Log.d("Calc", e.getMessage());
}
default: return -1;
}
}
private double operateTrigonometric(String a, String op) {
switch (op){
case "sin": return(Math.sin(Double.valueOf(a)));
case "cos": return(Math.cos(Double.valueOf(a)));
case "tan": try{
return(Math.tan(Double.valueOf(a)));
}catch(Exception e) {
Log.d("Calc", e.getMessage());
}
case "\u221a": return(Math.sqrt(Double.valueOf(a)));
default: return -1;
}
}
public void **onClickEqual**(View v) {
String[] operation=display.split(Pattern.quote(currentOperator));
Double result;
if(operation.length==1) {
result = operateTrigonometric(operation[0], currentOperator);
_screen.setText(display + "\n" + String.valueOf(result));
}
else if (operation.length<2)
return;
else {
return = operateArithmetic(operation[0], operation[1], currentOperator);
_screen.setText(display + "\n" + String.valueOf(result));
}
}
private void clear() {
display="";
currentOperator="";
}
public void **onClickClear**(View v){
clear();
updateScreen();
}
What is in double * are the things that appear grey. (I am using Android Studio)
My buttons have nothing special, only Layout properties to them.
My teacher noted that I need to add an OnClickNumber to my xml file (with all the buttons) and the only option I have is to add
android:onClick="onClickfunction"
the function is either Operator, Clear or Equal.
when actually running the app I get an error message for line
return = operateArithmetic(operation[0], operation[1], currentOperator);
because I'm expected to add something before the =
I'm coding a quiz app. When I clicked the score button to see if it worked, it showed I got 0 out of 5 right. I put in all the correct answers, but my code didn't tally anything up. What am I missing? I'm not sure what else to add and could really use the guidance as I am a new coder. I appreciate any help you can give.
int correctAnswers = 0;
// Start score
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void answers(View view) {
RadioButton q1 = (RadioButton) findViewById(R.id.yes_radio_button);
Boolean q1RightAnswer = q1.isChecked();
if (q1RightAnswer) {
correctAnswers += 1;
}
CheckBox q2Box1 = (CheckBox) findViewById(R.id.box1_checkbox);
boolean q2Box1RightAnswer = q2Box1.isChecked();
CheckBox q2Box2 = (CheckBox) findViewById(R.id.box2_checkbox);
boolean q2Box2WrongAnswer = q2Box2.isChecked();
CheckBox q2Box3 = (CheckBox) findViewById(R.id.box3_checkbox);
boolean q2Box3RightAnswer = q2Box3.isChecked();
if (q2Box1RightAnswer)
if (q2Box3RightAnswer) {
correctAnswers += 1;
}
if (q2Box2WrongAnswer) {
correctAnswers += 0;
}
RadioButton q3 = (RadioButton) findViewById(R.id.shuri_radio_button);
Boolean q3RightAnswer = q3.isChecked();
if (q3RightAnswer) {
correctAnswers += 1;
}
RadioButton q5 = (RadioButton) findViewById(R.id.two_radio_button);
Boolean q5RightAnswer = q5.isChecked();
if (q5RightAnswer) {
correctAnswers += 1;
}
EditText q4 = (EditText) findViewById(R.id.wakanda);
String q4RightAnswer = q4.getText().toString();
if (q4RightAnswer.equals(correctAnswers)) {
correctAnswers += 1;
} else {
// incorrect, do nothing
}
}
/**
* This method is called when the score button is clicked.
*/
public void submitScore(View view) {
Button nameField = (Button) findViewById(R.id.score);
String score = nameField.getText().toString();
// Show score message as a toast
Toast.makeText(this, "You got " + correctAnswers + "/5 correct!", Toast.LENGTH_LONG).show();
// Exit this method early because there's nothing left to do
return;
}
}
This will never be true
q4RightAnswer.equals(correctAnswers)
You need to compare matching types, not Strings to integers.
Assuming that's what you're trying to do, either parse the string or convert the int to a String.
You'll get zero printed if none of the checkboxes are marked or answers() is never called. For example, what's the difference between the answers method and the submitScore method? Both take a View parameter, so which one is actually assigned to the click event?
I would suggest doing something like
RadioButton q1, q3, q5;
EditText q4;
Checkbox qBox1, qBox2;
Button submit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
q1 = (RadioButton) findViewById(R.id.yes_radio_button);
// assign other views here
submit = (Button) findViewById(R.id.score);
submit.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
int correctAnswers = 0;
if (q1.isChecked()) correctAnswers += 1;
// TODO: check other inputs
String q4Text = q4.getText().toString();
if (q4Text.equals(String.valueOf(correctAnswers)) {
correctAnswers += 1;
}
// Toast correct answers
}
});
}
Basically, define all views as class level variables, then immediately set them after a content view is available, then only calculate the score when the button is clicked (in other words, wait for user input). Also, reset the score each time the button is clicked.
I have two problems, first, I want my seekbar to display values as follows: 5, 10, 15, 20...30. I have set max=30 and progress=5, but that doesn't do. Second, I need the value selected by the user via seekbar to be passed into calculatePayments() method after the user clicks the Calculate button. Anyone please help me out? I would appreciate it! Thanks!
public class AKMainActivity extends Activity {
private EditText loanAmount, interestRate, loanYears;
private TextView monthlyPaymentsResult, totalPaymentsResult, seek_barTV;
private static SeekBar seek_bar;
private static TextView textview_seek;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_akmain);
seekbarr();
loanAmount = (EditText)findViewById(R.id.loanET);
interestRate = (EditText) findViewById(R.id.intrateET);
monthlyPaymentsResult = (TextView) findViewById(R.id.monthlyResultTV);
totalPaymentsResult = (TextView) findViewById(R.id.totalResultsTV);
}
public void seekbarr(){
seek_bar = (SeekBar) findViewById(R.id.seekBar1);
textview_seek = (TextView) findViewById(R.id.seekbarTV);
textview_seek.setText(seek_bar.getProgress() + "Years");
seek_bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int years_number = 5;
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
textview_seek.setText(years_number + " Years");
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
years_number = progress;
textview_seek.setText(years_number + " Years");
progress = seek_bar.getProgress();
}
});
}
public void calculatePayments(View clickedButton) {
double loan = Integer.parseInt(loanAmount.getText().toString());
double interest = (Integer.parseInt(interestRate.getText().toString()));
double years = seek_bar.getProgress();
double r = years / 1200;
double r1 = Math.pow(r + 1, years);
double monthlyPayment = (double) ((r + (r / (r1 - 1))) * loan);
double totalPayment = monthlyPayment * years;
monthlyPaymentsResult.setText(new DecimalFormat("##.##").format(monthlyPayment));
totalPaymentsResult.setText(new DecimalFormat("##.##").format(totalPayment));
}
}
To set the progress increment you can do:
seekBar.incrementProgressBy(5);
You also need to get a reference to your button, the same way you did for you other views (TextView, SeekBar,etc.) and in your Button's onClick listener you can call the calculatePayments method, with the current seekbar value as an argument. To get the current value of the seekbar use:
seekBar.getProgress();
Very new to android java programming. I created a car payment calculator application for one of my classes and I am trying to create a checkbox that the user can check so that all the values stored in the TextViews and EditViews remain the same when the application is opened again.
Here is my activity:
public class MainActivity extends Activity implements OnClickListener,
OnEditorActionListener, OnItemSelectedListener, OnFocusChangeListener,
OnCheckedChangeListener {
private TextView payment;
private TextView interest;
private EditText principle;
private TextView interestText;
private CheckBox interestBox;
private EditText years;
private TextView apr;
Button plusbutton;
Button minusbutton;
private static String TAG = "CAR";
private Spinner period;
private double aprPercent;
private int t;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate");
this.getReferences();
this.setListeners();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void getReferences() {
payment = (TextView) findViewById(R.id.paymentLabel);
interest = (TextView) findViewById(R.id.interestLabel);
apr = (TextView) findViewById(R.id.aprLabel);
aprPercent = Double.parseDouble(apr.getText().toString());
interestText = (TextView) findViewById(R.id.interestText);
interestBox = (CheckBox) findViewById(R.id.checkBox1);
interestBox.setChecked(false);
principle = (EditText) findViewById(R.id.principleEditText);
years = (EditText) findViewById(R.id.yearsEditText);
period = (Spinner) findViewById(R.id.spinner1);
minusbutton = (Button) findViewById(R.id.minusbutton);
plusbutton = (Button) findViewById(R.id.plusbutton);
ArrayAdapter<CharSequence> adapter = ArrayAdapter
.createFromResource(this, R.array.split_array,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
period.setAdapter(adapter);
// principle.setOnFocusChangeListener(this);
Log.d(TAG, "getReferences principle: " + principle.getText()
+ " years:" + years.getText());
}
public void setListeners() { // where the event being consumed will be
// responding
principle.setOnFocusChangeListener(this);
principle.setOnEditorActionListener(this);
years.setOnFocusChangeListener(this);
years.setOnEditorActionListener(this);
interestBox.setOnCheckedChangeListener(this);
period.setOnItemSelectedListener(this);
Log.d(TAG, "setListeners principle: " + principle.getText() + " years:"
+ years.getText());
}
public void setPeriodValue() {
if (period.getSelectedItem().toString().equalsIgnoreCase("Monthly")) {
t = 12;
} else if (period.getSelectedItem().toString()
.equalsIgnoreCase("Quarterly")) {
t = 4;
} else if (period.getSelectedItem().toString()
.equalsIgnoreCase("Annually")) {
t = 1;
}
}
public void updateResults() {
double dblPrinciple = Double
.parseDouble(principle.getText().toString());
double dblYears = Double.parseDouble(years.getText().toString());
double num, denom, dblPayment;
double r = aprPercent / 100;
NumberFormat nf = NumberFormat.getNumberInstance();
NumberFormat curr = NumberFormat.getCurrencyInstance();
apr.setText(nf.format(aprPercent));
setPeriodValue();
num = (r / t);
denom = (1 - Math.pow((1 + num), (t * -dblYears)));
dblPayment = dblPrinciple * (num / denom);
payment.setText(curr.format(dblPayment));
interest.setText(curr
.format((dblPayment * t * dblYears) - dblPrinciple));
}
public void onFocusChange(View v, boolean hasfocus) {
Log.d(TAG, "Focus Change principle: " + principle.getText() + " years"
+ years.getText());
switch (v.getId()) {
case R.id.principleEditText:
case R.id.yearsEditText:
updateResults();
default:
updateResults();
}
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(interestBox.isChecked()) {
interest.setVisibility(View.VISIBLE);
interestText.setVisibility(View.VISIBLE);
}
else {
interest.setVisibility(View.INVISIBLE);
interestText.setVisibility(View.INVISIBLE);
}
if (interestBox.isChecked()!=true){
interest.setVisibility(View.INVISIBLE);
interestText.setVisibility(View.INVISIBLE);
}
else {
interest.setVisibility(View.VISIBLE);
interestText.setVisibility(View.VISIBLE);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
updateResults();
}
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
updateResults();
return false;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.minusbutton:
if (aprPercent == 1) {
break;
} else {
aprPercent = aprPercent - 1.0;
updateResults();
break;
}
case R.id.plusbutton:
if (aprPercent == 20) {
break;
} else {
aprPercent = aprPercent + 1.0;
updateResults();
break;
}
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
updateResults();
}
My guess is that I have to do something with sharedprefs but I'm not exactly sure how to go about it. Any push in the right direction would be great. thank you.
Use getSharedPreferences(...).edit().putString(...).commit() to store values in "onPause()" and again use getSharedPreferences(...).getString(...) to retrieve information in your "onResume()". It's just that easy.
You will have to read how to save your Activity data. In my opinion you should not use checkbox to save this data but save it by default.
To save your data while the screen rotate you will have to check the OnSaveInstanceState and OnRestoreInstanceState like in this post. It will handle the data when rotated too.
To save your data for a longer time (changing of applications, closing application), You will have to use the Android preferences but check how works the lifecycle of an Activity. Basically you will need to save in the OnPause or OnDestroy and reload it in the OnResume or OnCreate.
Concerning the preferences you have a nice tutorial on the Vogella Website
//Get Data
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity());
String url = settings.getString("url", "n/a");
//Save Data
Editor edit = preferences.edit();
edit.putString("username", "new_value_for_user");
edit.apply();
Im trying to make a currency converter homework (i am new to programming)
made everything but the radio button is keeped pressed and isnt doing nothing
(not puting text into the TextView and the radio buttons is locked on "pressed" mode
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_convert);
mResult = (TextView) findViewById(R.id.result);
mToConvert = (EditText) findViewById(R.id.toConvert);
mRadioGroup = (RadioGroup) findViewById(R.id.radioG);
mDollar = (RadioButton) findViewById(R.id.dollar);
Meuro = (RadioButton) findViewById(R.id.euro);
mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup rGroup, int checkedId)
{
switch (mRadioGroup.getCheckedRadioButtonId())
{
case R.id.dollar:
Double dollarConvert = Double.valueOf(mToConvert.getText().toString()); //convert the string to int
double price = dollarConvert * 1.28;
mDollar.setChecked(true);
Meuro.setChecked(false);
String result = mToConvert.getText().toString();
mResult.setText(result + price);
break;
case R.id.euro:
Double euroConvert = Double.valueOf(mToConvert.getText().toString()); //convert the string to int
double value = euroConvert * 1.28;
mDollar.setChecked(false);
Meuro.setChecked(true);
String result1 = mToConvert.getText().toString();
mResult.setText(result1 + value);
break;
default:;
}
}
});
}
}
you will need to set RadioGroup.setoncheckedchangelistener for RadioGroup to do some Action when check changes event fire.
mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup rGroup, int checkedId)
{
//do your code here
}
});