Hiding and showing a single Menu Button - android

I have a project for an Android class, so I'm still learning and this should be a basic question. We were given a tip calculator and already made some modifications, now we have to add a menu.
When it starts up, it will be in multi-person mode. Gives a text box and Text Field for how many people you want the bill split into. When you hit menu, it should show a Single person mode which eliminates a text box and text field. The menu then changes to show a multi-person mode button in the menu.
I've got everything to work except it's showing both buttons, I cannot figure out how to hide a button temporarily. The main error is:
Cannot invoke setVisibility(int) on the primitive type int
on the statement:
multiple_button.setVisibility(View.GONE);
I've tried every combination of hiding the button I can think of, and think that the above line is correct, but unsure of how make it work.
one_person_button = View.VISIBLE;
multiple_button = View.GONE;
I have this in the code, but it's not doing anything either.
Any help would be greatly appreciated.
edit: code. I've read through the link, but considering I don't have a OnPrepareOptions section, I need to re-read it
package com.android;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Button;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class tipcalc extends Activity
{
public static int one_person_button = Menu.FIRST;
private int multiple_button = Menu.FIRST +1;
static final private int reset_button = Menu.FIRST +2;
private static final int MENU_ITEM = 0;
private EditText txtbillamount;
private EditText txtpeople;
private EditText txtpercentage;
private TextView txtperperson;
private TextView txttipamount;
private TextView txttotal;
private Button btncalculate;
private Button btnreset;
private double billamount = 0;
private double percentage = 0;
private double numofpeople=0;
private double tipamount = 0;
private double totaltopay = 0;
private double perperson = 0;
private View view;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initControls();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuItem itemOne = menu.add(0, one_person_button, Menu.NONE,
R.string.one_person);
MenuItem itemMultiple = menu.add(1, multiple_button, Menu.NONE,
R.string.multiple);
MenuItem itemReset = menu.add(2, reset_button, Menu.NONE,
R.string.reset);
itemOne.setIcon(R.drawable.ic_menu_invite);
itemMultiple.setIcon(R.drawable.ic_menu_allfriends);
itemReset.setIcon(R.drawable.ic_menu_refresh);
one_person_button.setGroupVisible(0, true);
multiple_button.setVisibility(View.GONE);
one_person_button = View.VISIBLE;
multiple_button = View.GONE;
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if (one_person_button == View.VISIBLE) {
((TextView)findViewById(R.id.txtpeople)).setVisibility(View.INVISIBLE) ;
((TextView)findViewById(R.id.widget30)).setVisibility(View.INVISIBLE) ;
multiple_button = View.VISIBLE;
one_person_button = View.GONE;
numofpeople = 1; }
else if (multiple_button == View.VISIBLE) {
((TextView)findViewById(R.id.txtpeople)).setVisibility(View.VISIBLE) ;
((TextView)findViewById(R.id.widget30)).setVisibility(View.VISIBLE) ;
multiple_button = View.GONE;
one_person_button = View.VISIBLE;
}
return false;
}
private void initControls()
{
txtbillamount = (EditText)findViewById(R.id.txtbillamount);
txtpeople = (EditText)findViewById(R.id.txtpeople);
txtperperson=(TextView)findViewById(R.id.txtperperson);
txttipamount=(TextView)findViewById(R.id.txttipamount);
txttotal=(TextView)findViewById(R.id.txttotal);
btncalculate = (Button)findViewById(R.id.btncalculate);
btnreset = (Button)findViewById(R.id.btnreset);
btncalculate.setOnClickListener(new Button.OnClickListener() { public void onClick (View v){ calculate(); }});
btnreset.setOnClickListener(new Button.OnClickListener() { public void onClick (View v){ reset(); }});
}
private void calculate()
{
billamount=Double.parseDouble(txtbillamount.getText().toString());
numofpeople=Double.parseDouble(txtpeople.getText().toString());
RadioButton poorButton = (RadioButton) findViewById(R.id.radioButton1);
RadioButton goodButton = (RadioButton) findViewById(R.id.radioButton2);
RadioButton excellentButton = (RadioButton) findViewById(R.id.radioButton3);
if (poorButton.isChecked()){
percentage = Double.parseDouble(poorButton.getText().toString());
} else if (goodButton.isChecked()){
percentage = Double.parseDouble(goodButton.getText().toString());
} else if (excellentButton.isChecked()){
percentage = Double.parseDouble(excellentButton.getText().toString());
}
tipamount=(billamount*percentage)/100;
totaltopay=billamount+tipamount;
perperson=totaltopay/numofpeople;
txttipamount.setText(Double.toString(tipamount));
txttotal.setText(Double.toString(totaltopay));
txtperperson.setText(Double.toString(perperson));
}
private void reset()
{
txtbillamount.setText("");
txtpeople.setText("");
txtperperson.setText("");
txttipamount.setText("");
txttotal.setText("");
}
}

Post all of your relavent source code. Without it, we cannot give you specific advice about what is going wrong.
I can tell you though you'll be needing to override onPrepareOptionsMenu() and inside there you'll want to check which mode your in and make the proper button be visible. But you need to call setVisibility(View.VISIBLE); on a reference to the button widget, not on an int.
This page holds the answer to your questions.

try calling setVisibility with 8

Related

Database contents in different pages like same layout

Showing database rows as ListView/Gridview in the same layout via adapter, is there a option to display those in separate pages like same layout. So I can switch to next page by a button.
Currently am just saving values using sharedprefernce and changes the contents from layout (Just TEXT in my case). I am trying to create app for exam tests with a question and 4 options. currently am saving user score and checked radio button id in sharedpreferences when user click NEXT button.
My code:
package com.sap.quizmaster;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private MyDatabase testdb;
private Cursor mycursor;
private TextView ques;
private RadioGroup options;
private RadioButton op1;
private RadioButton op2;
private RadioButton op3;
private RadioButton op4;
private RadioButton radioButton;
private LinearLayout default_lay;
private LinearLayout default_btn_lay;
private TextView final_text;
private Button final_btn;
private Button next_btn;
private Button prev_btn;
private int checkedid = -1;
private int q_no = 1;
private String answer;
private int score = 0;
private SharedPreferences sp;
private SharedPreferences.Editor sp_edit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ques = findViewById(R.id.ques);
op1 = findViewById(R.id.op1);
op2 = findViewById(R.id.op2);
op3 = findViewById(R.id.op3);
op4 = findViewById(R.id.op4);
next_btn = findViewById(R.id.next_btn);
prev_btn = findViewById(R.id.prev_btn);
options = findViewById(R.id.options);
final_btn = findViewById(R.id.final_btn);
final_text = findViewById(R.id.final_text);
default_lay = findViewById(R.id.default_text);
default_btn_lay = findViewById(R.id.default_btn);
//Loading sharedpreferences
sp = getSharedPreferences("QuizMaster", MainActivity.MODE_PRIVATE);
//Clearing all values from sharedpreferences when app re-launching
sp_edit = sp.edit();
sp_edit.clear();
sp_edit.commit();
testdb = new MyDatabase(this);
mycursor = testdb.getQuestion(q_no);
setQuestion();
next_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mycursor.close();
checkedid = options.getCheckedRadioButtonId();
saveInteger(q_no, checkedid);
if (checkedid != -1) {
radioButton = findViewById(checkedid);
if (radioButton.getText().equals(answer)) {
score += 3;
} else {
score -= 1;
}
}
options.clearCheck();
q_no = q_no + 1;
if(q_no>3){
default_btn_lay.setVisibility(View.GONE);
default_lay.setVisibility(View.GONE);
final_btn.setVisibility(View.VISIBLE);
final_text.setVisibility(View.VISIBLE);
final_text.setText("Your Score is "+score);
q_no = 1;
return;
}
checkedid = sp.getInt(q_no + "", -1);
if (checkedid != -1) {
radioButton = findViewById(checkedid);
radioButton.setChecked(true);
}
mycursor = testdb.getQuestion(q_no);
setQuestion();
}
});
prev_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mycursor.close();
if (q_no <= 1) {
Toast.makeText(MainActivity.this, "END", Toast.LENGTH_SHORT).show();
return;
}
q_no = q_no - 1;
mycursor = testdb.getQuestion(q_no);
setQuestion();
checkedid = sp.getInt(q_no + "", -1);
if (checkedid != -1) {
radioButton = findViewById(checkedid);
radioButton.setChecked(true);
if (radioButton.getText().equals(answer)) {
score -= 3;
} else {
score += 1;
}
}
Toast.makeText(MainActivity.this, "Button PREVIOUS pressed", Toast.LENGTH_SHORT).show();
}
});
final_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final_text.setVisibility(View.GONE);
final_btn.setVisibility(View.GONE);
default_lay.setVisibility(View.VISIBLE);
default_btn_lay.setVisibility(View.VISIBLE);
mycursor = testdb.getQuestion(q_no);
setQuestion();
sp_edit = sp.edit();
sp_edit.clear();
sp_edit.commit();
score = 0;
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
testdb.close();
mycursor.close();
}
public void setQuestion() {
answer = mycursor.getString(mycursor.getColumnIndex("ANS"));
ques.setText(mycursor.getString(mycursor.getColumnIndex("QUES")));
op1.setText(mycursor.getString(mycursor.getColumnIndex("OP1")));
op2.setText(mycursor.getString(mycursor.getColumnIndex("OP2")));
op3.setText(mycursor.getString(mycursor.getColumnIndex("OP3")));
op4.setText(mycursor.getString(mycursor.getColumnIndex("OP4")));
}
public void saveInteger(int ques, int value) {
sp_edit = sp.edit();
sp_edit.putInt(ques + "", value);
sp_edit.apply();
}
}
Just get me an link or idea to think in any easy way.
Sounds like you want to use an AdapterViewFlipper
https://developer.android.com/reference/android/widget/AdapterViewFlipper
with a custom adapter
This will generate a view from a template using data from the adapter
e.g. Each question could be on a separate page with a button to move to the next question.
Example https://abhiandroid.com/ui/adapterviewflipper
But you probably don't want to use the autoflipping option and instead link a next button to the showNext() method

Can't increment counter and not sure if correct comparison of background and drawable

I'm trying to check if a corresponding text is the same with the image that is displayed in a button.
For example, the String "heart" is displayed, i want to know if the image displayed on the button is an image of heart, and if the right image is loaded, when you click the button, the counter will increment.
package com.example.simplegame;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Game extends Activity {
public int correct = 0;
ArrayList<Integer> ShapesArray = new ArrayList<Integer>();
ArrayList<String> ShapestoFind = new ArrayList<String>();
TextView Answer;
Button Check;
Button img1;
Button img2;
Button img3;
Button img4;
Button img5;
Button img6;
Button img7;
Button img8;
Button img9;
Random rand = new Random();
public String Shape;
Drawable bgImg1;
private int myImg1;
private int myImg2;
private int myImg3;
private int myImg4;
private int myImg5;
private int myImg6;
private int myImg7;
private int myImg8;
private int myImg9;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
ShapesArray.add(R.drawable.circle);
ShapesArray.add(R.drawable.heart);
ShapesArray.add(R.drawable.square);
ShapesArray.add(R.drawable.triangle);
ShapestoFind.add("Heart");
ShapestoFind.add("Circle");
ShapestoFind.add("Triangle");
ShapestoFind.add("Square");
int size = ShapesArray.size();
final TextView PName = (TextView) findViewById (R.id.choice);
Answer = (TextView) findViewById (R.id.textAnswer);
img1 = (Button) findViewById (R.id.button1);
img2 = (Button) findViewById (R.id.button2);
img3 = (Button) findViewById (R.id.button3);
img4 = (Button) findViewById (R.id.button4);
img5 = (Button) findViewById (R.id.button5);
img6 = (Button) findViewById (R.id.button6);
img7 = (Button) findViewById (R.id.button7);
img8 = (Button) findViewById (R.id.button8);
img9 = (Button) findViewById (R.id.button9);
Check = (Button) findViewById(R.id.button10);
int rndInt = rand.nextInt(size);
Shape = ShapestoFind.get(rndInt);
PName.setText(Shape);
Collections.shuffle(ShapesArray);
img1.setBackgroundResource(ShapesArray.get(0));
this.myImg1 = ShapesArray.get(0);
img1.setOnClickListener(new OnClickListener(){
public void onClick(View v){
if(Shape.equals("Heart")){
if(myImg1 == R.drawable.heart){
correct++;
}
}
else if(Shape.equals("Circle")){
if(myImg1 == R.drawable.circle){
correct++;
}
}
else if(Shape.equals("Square")){
if(myImg1 == R.drawable.square){
correct++;
}
}
else if(Shape.equals("Triangle")){
if(myImg1 == R.drawable.triangle){
correct++;
}
}
}
});
Collections.shuffle(ShapesArray);
img2.setBackgroundResource(ShapesArray.get(1));
this.myImg2 = ShapesArray.get(1);
img2.setOnClickListener(new OnClickListener(){
public void onClick(View v){
if(Shape.equals("Heart")){
if(myImg2 == R.drawable.heart){
correct++;
}
}
if(Shape.equals("Circle")){
if(img2.getBackground().equals(R.drawable.circle)){
correct++;
}
}
if(Shape.equals("Square")){
if(img1.getBackground().equals(R.drawable.square)){
correct++;
}
}
if(Shape.equals("Triangle")){
if(img1.getBackground().equals(R.drawable.triangle)){
correct++;
}
}
}
});
Collections.shuffle(ShapesArray);
img3.setBackgroundResource(ShapesArray.get(0));
Collections.shuffle(ShapesArray);
img4.setBackgroundResource(ShapesArray.get(1));
Collections.shuffle(ShapesArray);
img5.setBackgroundResource(ShapesArray.get(0));
Collections.shuffle(ShapesArray);
img6.setBackgroundResource(ShapesArray.get(1));
Collections.shuffle(ShapesArray);
img7.setBackgroundResource(ShapesArray.get(0));
Collections.shuffle(ShapesArray);
img8.setBackgroundResource(ShapesArray.get(1));
Collections.shuffle(ShapesArray);
img9.setBackgroundResource(ShapesArray.get(0));
this.myImg1=R.drawable.heart;
Check.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
Answer.setText(Integer.toString(correct));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.game, menu);
return true;
}
}
I'm still kinda new to Android. I don't know if what I want is possible. Can Someone Please help. :(
You cannot compare a Drawable with a Resource ID, which is what you are doing in:
if(img1.getBackground().equals(R.drawable.heart)){
...
Maybe what you want is to save the Resource ID of the background when you set it, like:
this.mImg1Bg = R.drawable.heart;
img1.setBackground(this.mImg1Bg);
And then on the onClick() you test with:
if(this.mImg1Bg == R.drawable.heart) {
...
EDIT:
Now with the entire code it is easier.
I will assume that you have this at the end of onCreate():
this.myImg1=R.drawable.heart;
just for testing purposes, as you are redefining it as it was set already.
Now you have another problem with the string test. Shape variable is not what you want to test. Maybe if you test it like:
public void onClick(View v){
String txt = ((Button)v).getText();
if(txt.equals("Heart")){
if(myImg1 == R.drawable.heart){
correct++;
}
}
...
}
I don't know what exactly you are showing in your Activity, but it seems to me that you could simplify a lot if you used:
HashMap<String, Integer> shapes;
shapes.put("Heart", R.drawable.heart);
...
to store the shapes strings and relation to resources.
An ArrayList of Pair's to store the combinations on the buttons:
ArrayList<Pair<Integer,String>> buts;
buts.add(new Pair<Integer,String>(R.drawable.heart, "Heart"));
...
Set a tag on each button view to know which button number was clicked:
img1.setTag(1);
...
Then assign the same OnClickListener to all buttons. For instance by implementing the interface by your Activity, like:
public class Game extends Activity implements OnClickListener {
...
img1.setOnClickListener(this);
...
And check the onClick() like this:
public void onClick(View v) {
int res = buts.get((Integer)v.getTag()).first;
String txt = buts.get((Integer)v.getTag()).second;
if(res == shapes.get(txt)) {
correct++;
}
}
And then don't forget to assign the correct to some UI TextView so you can view the result.

updating the wrong textedit field

Could you guys lend me some fresh eyes and tell me what where I should look to find the missing link? I am trying to do a mortgage calculation by pulling value from purchasePrice, downPayment, and interestRate EditText fields to do the calculation. I tested the updateStandand() by setting the TextEdit field to interest rate. However, when I run the app in AVD, if I type a purchase price, the monthly payment field would reflect the price. If i move down to interest rate field and type in a number, the monthly payment field would change to the value of the interest rate.
Thank you!
package com.example.mortgagecalc;
import com.example.mortgagecalc.R.string;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.text.Editable;
public class Main extends Activity {
private static final String PURCHASE_AMOUNT = "PURCHASE_AMOUNT";
private static final String CUSTOM_LENGTH = "CUSTOM_LENGTH";
private static final String DOWN_PAYMENT = "DOWN_PAYMENT";
private static final String INTEREST_RATE = "INTEREST_RATE";
private int currentPurchaseAmount; //purchase amount entered by user
private int currentCustomLength; //length of loan set with SeekBar
private int currentDownPayment; //down payment entered by user
private double currentInterestRate; //interest rate entered by user
private EditText purchaseAmountEditText; //accepts user input for purchase amount
private EditText downPaymentEditText; //accepts user input for down payment amount
private EditText interestRateEditText; //accepts user input for interest rate
private EditText tenYearEditText; //display monthly payment for 10yr. loan
private EditText twentyYearEditText; //display monthly payment for 20yr. loan
private EditText thirtyYearEditText; //display monthly payment for 30yr. loan
private EditText customMonthlyEditText; //display monthly payment for custom length
private TextView customLengthTextView; //display custom loan length
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//check if app just started or being restored from memory
if (savedInstanceState == null) //app just started running
{
currentPurchaseAmount = 0; //initialize to zero
currentCustomLength = 10; //initialize custom loan length to 10
currentDownPayment = 0; //initialize to zero
currentInterestRate = 0.0; //initialize to zero
}
else
{
currentPurchaseAmount = savedInstanceState.getInt(PURCHASE_AMOUNT);
currentCustomLength = savedInstanceState.getInt(CUSTOM_LENGTH);
currentDownPayment = savedInstanceState.getInt(DOWN_PAYMENT);
currentInterestRate = savedInstanceState.getDouble(INTEREST_RATE);
}
purchaseAmountEditText = (EditText) findViewById(R.id.purchaseAmountEditText);
downPaymentEditText = (EditText) findViewById(R.id.downPaymentEditText);
interestRateEditText = (EditText) findViewById(R.id.interestRateEditText);
tenYearEditText = (EditText) findViewById(R.id.tenYearEditText);
twentyYearEditText = (EditText) findViewById(R.id.twentyYearEditText);
thirtyYearEditText = (EditText) findViewById(R.id.thirtyYearEditText);
customMonthlyEditText = (EditText) findViewById(R.id.customMonthlyEditText);
customLengthTextView = (TextView) findViewById(R.id.customMonthlyTextView);
purchaseAmountEditText.addTextChangedListener(textWatcher);
downPaymentEditText.addTextChangedListener(textWatcher);
interestRateEditText.addTextChangedListener(textWatcher);
SeekBar customSeekBar = (SeekBar) findViewById(R.id.customSeekBar);
customSeekBar.setOnSeekBarChangeListener(customSeekBarListener);
}
private void updateStandard(){
double interestRate = currentInterestRate;
//double loanPrinciple = currentPurchaseAmount - currentDownPayment;
//double tenYearMonthlyPayment = loanPrinciple;
tenYearEditText.setText(String.valueOf(interestRate));
}
private void updateCustom(){
//customLengthTextView.setText(currentCustomLength + "year");
double customInterestRate = ((currentInterestRate/12) * .01);
int customLoanPrinciple = currentPurchaseAmount - currentDownPayment;
double customMonthlyPayment = customLoanPrinciple * customInterestRate /
(1-Math.pow(1+customInterestRate, -(currentCustomLength*12)));
customMonthlyEditText.setText(Double.toString(customMonthlyPayment));
}
#Override
protected void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putDouble(PURCHASE_AMOUNT, currentPurchaseAmount);
outState.putDouble(DOWN_PAYMENT, currentDownPayment);
outState.putDouble(INTEREST_RATE, currentInterestRate);
outState.putDouble(CUSTOM_LENGTH, currentCustomLength);
}
private OnSeekBarChangeListener customSeekBarListener = new OnSeekBarChangeListener(){
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)
{
currentCustomLength = seekBar.getProgress();
updateCustom();
}
#Override
public void onStartTrackingTouch(SeekBar seekBar)
{
}
#Override
public void onStopTrackingTouch(SeekBar seekBar)
{
}
};
private TextWatcher textWatcher = new TextWatcher()
{
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
try
{
currentPurchaseAmount = Integer.parseInt(s.toString());
currentDownPayment = Integer.parseInt(s.toString());
currentInterestRate = Integer.parseInt(s.toString());
}
catch(NumberFormatException e)
{
currentPurchaseAmount = 0;
currentDownPayment = 0;
currentInterestRate = 0.0;
}
updateStandard();
updateCustom();
}
#Override
public void afterTextChanged(Editable s)
{
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
};
#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;
}
}
You're using a single TextWatcher for all three fields, and updating all three fields in the onTextChanged method.
I'm guessing that what you really want is three separate TextWatcher instances - one for each field, and to update only that one value in each one.

Pass value outside of public void onClick

So im sure this is probably a fairly easy question but I am stumped because I am a beginner.
I am looking to pass a value from one class to another, and I have my helper function down and working just fine. If i create an integer outside of my onClick I can pass it no problem. If I create it inside the onClick though it doesn't seem to make it out.
package com.movi.easypar;
//import java.util.logging.Handler;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class EntryScreen extends Activity implements OnClickListener {
Button buttonSetHoles, buttonSetPlayers, buttonLetsGo;
TextView textGameSetup;
public int setHoles; <--- declared here###############################
private String name1 = "Crista";
private String name2 = "Rob";
private String name3 = "Gato";
private String name4 = "Movi";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.entryscreen);
//******************//
//***DEFINE FONTS***//
//******************//
Typeface merge = Typeface.createFromAsset(getAssets(), "merge.otf");
//*****************************************************//
//***CREATES THE UI FOR EACH OF THESE IN JAVA MEMORY***//
//*****************************************************//
buttonSetHoles = (Button)findViewById(R.id.buttonSetHoles);
buttonSetPlayers = (Button)findViewById(R.id.buttonSetPlayers);
buttonLetsGo = (Button)findViewById(R.id.buttonLetsGo);
textGameSetup = (TextView)findViewById(R.id.textGameSetup);
buttonSetHoles.setTypeface(merge);
buttonSetPlayers.setTypeface(merge);
buttonLetsGo.setTypeface(merge);
textGameSetup.setTypeface(merge);
buttonSetHoles.setText("Set Holes");
buttonLetsGo.setText("Lets Go");
buttonSetPlayers.setText("Set Players");
//******************************//
//***DEFINES BUTTON LISTENERS***//
//******************************//
buttonSetHoles.setOnClickListener(this);
buttonSetPlayers.setOnClickListener(this);
buttonLetsGo.setOnClickListener(this);
}
//*************************************************//
//***SETS ON CLICK FUNCTIONALITY FOR ALL BUTTONS***//
//*************************************************//
#Override
public void onClick(View src) {
switch(src.getId()){
case R.id.buttonSetPlayers:
break;
case R.id.buttonSetHoles:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final CharSequence[] items = {"18", "9"};
builder.setTitle("Set Holes");
builder.setItems(items, new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialogInterface, int item) {
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
if (items[item].equals("9")){
EntryScreen.this.setHoles = 9; <---#### VALUE SET HERE ####
}
else if (items[item].equals("18")){
EntryScreen.this.setHoles = 18;
}
return;
}
});
builder.create().show();
return;
case R.id.buttonLetsGo:
//*********************************//
//***LAUNCHES ACTUAL APPLICATION***//
//*********************************//
TranslateAnimation slide = new TranslateAnimation(0, -500, 0,0 );
slide.setDuration(1000);
slide.setFillAfter(true);
buttonLetsGo.startAnimation(slide);
buttonSetPlayers.startAnimation(slide);
buttonSetHoles.startAnimation(slide);
Intent myIntent = new Intent(src.getContext(), EasyPar.class);
startActivityForResult(myIntent, 0);
break;
}
EntryScreen.this.finish();
}
public String getNames() {
return name1;
}
public void setNames(String playerName1) {
name1 = playerName1;
}
public int getHoles() {
return setHoles; <---- #### THIS DOES NOT SEE VALUE SET IN ONCLICK ####
}
}
This helper does not seem to be able to see the setHoles value that is created onClick.
Any suggestions? Thanks in advance!
It's a scope thing. A variable defined in a function has local scope, and will be destroyed when the function returns. You need a field to hold your value if you wish to retain it.
[EDIT]
Then allow me to elaborate. You can create a field by typing the following line outside a function, inside the class:
[Access][Type][Name];
ex:
class foo{
public int dice;
public void onClick(){
//now the dice's value is saved throught the lifecycle of the Activity
}
}
[EDIT]
I copied your code and ran it. (Modified just a little.)
public class Main extends Activity implements OnClickListener {
Button buttonSetHoles, buttonSetPlayers, buttonLetsGo;
TextView textGameSetup;
public int setHoles; //<--- declared here###############################
private String name1 = "Crista";
private String name2 = "Rob";
private String name3 = "Gato";
private String name4 = "Movi";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//******************//
//***DEFINE FONTS***//
//******************//
Typeface merge = Typeface.createFromAsset(getAssets(), "merge.otf");
//*****************************************************//
//***CREATES THE UI FOR EACH OF THESE IN JAVA MEMORY***//
//*****************************************************//
/*
buttonSetPlayers = (Button)findViewById(R.id.buttonSetPlayers);
buttonLetsGo = (Button)findViewById(R.id.buttonLetsGo);
textGameSetup = (TextView)findViewById(R.id.textGameSetup);
*/
buttonSetHoles = (Button) findViewById(R.id.buttonSetHoles);
/*
buttonSetHoles.setTypeface(merge);
buttonSetPlayers.setTypeface(merge);
buttonLetsGo.setTypeface(merge);
textGameSetup.setTypeface(merge);
buttonSetHoles.setText("Set Holes");
buttonLetsGo.setText("Lets Go");
buttonSetPlayers.setText("Set Players");
*/
//******************************//
//***DEFINES BUTTON LISTENERS***//
//******************************//.
buttonSetHoles.setOnClickListener(this);
/*
buttonSetPlayers.setOnClickListener(this);
buttonLetsGo.setOnClickListener(this);
*/
}
//*************************************************//
//***SETS ON CLICK FUNCTIONALITY FOR ALL BUTTONS***//
//*************************************************//
#Override
public void onClick(View src) {
switch (src.getId()) {
case R.id.buttonSetHoles:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final CharSequence[] items = { "18", "9" };
builder.setTitle("Set Holes");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int item) {
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
if (items[item].equals("9")) {
setHoles = 9;// <---#### VALUE SET HERE ####
Toast.makeText(Main.this, "getHoles()=" + getHoles(), Toast.LENGTH_SHORT);
}
else if (items[item].equals("18")) {
setHoles = 18;
Toast.makeText(Main.this, "getHoles()=" + getHoles(), Toast.LENGTH_SHORT);
}
return;
}
});
builder.create().show();
return;
}
//finish();
}
public String getNames() {
return name1;
}
public void setNames(String playerName1) {
name1 = playerName1;
}
public int getHoles() {
return setHoles;
}
}
And it seems to work just fine.
If you declare the variable inside the method, an external method is surely not able to see it, it's not in the same scope, you can still declare it outside and then set a value from inside the onClick() method.
Declare it as public/private variable outside the methods.
are you sure your setHoles is even being set? to 9 or 18? try adding a println(setHoles) in your onclick to ensure that the value is being set properly. Also, you are declaring your setHoles variable outside of onCreate but within the same class as getHoles() and onClick() right?
when you compare Strings always use equal method.
like:
if (items[item].equals( "9")){
}
and i prefer to user Setters and Getters on variables:
setHoles(int value){}
and
int getHoles(){}

Android - register button click and take action based on radio selection

I'm trying to teach myself how to write android apps and I'm having trouble registering a button click and taking actions based on which radio button is selected at the time. This is a simple tip calculator:
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.RadioGroup;
import android.view.View;
public class TipCalc extends Activity implements RadioGroup.OnCheckedChangeListener,View.OnClickListener
{
TextView result;
RadioGroup radiogroup1;
RadioButton r1,r2,r3;
Button calculate;
EditText bill, resulttotal;
private int radioCheckedId = -1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
radiogroup1 = (RadioGroup) findViewById(R.id.radiogroup1);
Button calculate = (Button) findViewById(R.id.calculate);
RadioButton r1 = (RadioButton) findViewById(R.id.poor);
RadioButton r2 = (RadioButton) findViewById(R.id.average);
RadioButton r3 = (RadioButton) findViewById(R.id.excellent);
EditText bill = new EditText(this);
EditText resulttotal = new EditText(this);
radiogroup1.setOnCheckedChangeListener(this);
calculate.setOnClickListener(this);
//bill.setText("0");
//resulttotal.setText("0");
}
public void onCheckedChanged(RadioGroup group, int checkedId) {
radioCheckedId = checkedId;
}
public void onClick(View v)
{
if (v == calculate)
{
String billtotal;
double total = 0;
billtotal = bill.getText().toString();
final int aInt = Integer.parseInt(billtotal);
if (radioCheckedId == 1)
{
total = aInt * 1.1;
final String aString = Double.toString(total);
resulttotal.setText(aString);
}
if (radioCheckedId == 2)
{
total = aInt * 1.15;
final String aString = Double.toString(total);
resulttotal.setText(aString);
}
if (radioCheckedId == 3)
{
total = aInt * 1.2;
final String aString = Double.toString(total);
resulttotal.setText(aString);
}
}
}
}
Everything loads just fine, but nothing happens when I press the calculate button in the virtual phone.
The problem is where you're comparing the RadioGroup's selected id... you'll want to change your onClick() to:
public void onClick(View v) {
if (v == calculate) {
String billtotal;
double total = 0;
billtotal = bill.getText().toString();
final int aInt = Integer.parseInt(billtotal);
if (radioCheckedId == R.id.poor) {
total = aInt * 1.1;
final String aString = Double.toString(total);
resulttotal.setText(aString);
}
if (radioCheckedId == R.id.average) {
total = aInt * 1.15;
final String aString = Double.toString(total);
resulttotal.setText(aString);
}
if (radioCheckedId == R.id.excellent) {
total = aInt * 1.2;
final String aString = Double.toString(total);
resulttotal.setText(aString);
}
}
}
onCheckedChanged() gives you will be the R.id for the view and not just a number which tells you which it is in sequence.
A few quick (unrelated) suggestions:
Use a switch statement instead of a bunch of if-statements.
Put something in there to check for -1 (nothing checked) too... just to be sure.
In the onClick() I usually check for which View was clicked by checking the incoming view's id. This just makes it where you don't have to keep everything stored and (IMHO) is a little more clear what you're talking about.
The above suggestions would look something like:
public void onClick(View v) {
if (v.getId() == R.id.calculate) {
String billtotal;
double total = 0;
billtotal = bill.getText().toString();
final int aInt = Integer.parseInt(billtotal);
switch(radioCheckedId) {
case R.id.poor:
total = aInt * 1.1;
final String aString = Double.toString(total);
resulttotal.setText(aString);
break;
case R.id.average:
total = aInt * 1.15;
final String aString = Double.toString(total);
resulttotal.setText(aString);
break;
case R.id.excellent:
total = aInt * 1.2;
final String aString = Double.toString(total);
resulttotal.setText(aString);
break;
default:
// do something for when nothing is selected... maybe throw an error?
break;
}
}
}
Lastly, if all you're doing in onCheckedChanged() is storing the value you could get rid of it all together and just check for it in the onClick(). Something like:
public void onClick(View v) {
int radioCheckedId = radiogroup1.getCheckedRadioButtonId();
if (v == calculate) {
// ...
Unrelated, but another problem I noticed (and someone else mentioned)... if your EditTexts are listed in the XML layout then you'd need to get hooks to them like this (and not create new ones):
EditText bill = (EditText) findViewById(R.id.bill );
EditText resulttotal = (EditText) findViewById(R.id.resulttotal);
Also, you could probably just use a TextView instead of an EditView for the result if yo udon't need it to be editable.
import java.text.NumberFormat;
import java.util.Locale;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.RadioGroup;
import android.view.View;
public class TipCalc extends Activity
{
TextView result;
RadioGroup radiogroup1;
RadioButton r1,r2,r3;
Button calculate;
EditText bill, resulttotal;
Locale currentLocale = Locale.getDefault();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
radiogroup1 = (RadioGroup) findViewById(R.id.radiogroup1);
final Button calculate = (Button) findViewById(R.id.calculate);
final RadioButton r1 = (RadioButton) findViewById(R.id.poor);
final RadioButton r2 = (RadioButton) findViewById(R.id.average);
final RadioButton r3 = (RadioButton) findViewById(R.id.excellent);
final EditText bill = (EditText) findViewById(R.id.bill);
final EditText tiptotal = (EditText) findViewById(R.id.tiptotal);
final EditText resulttotal = (EditText) findViewById(R.id.resulttotal);
bill.setText("0.00");
tiptotal.setText("0.00");
resulttotal.setText("0.00");
calculate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) throws NumberFormatException {
if (v == calculate)
{
NumberFormat currencyFormatter;
currencyFormatter = NumberFormat.getCurrencyInstance(currentLocale);
double atotal = 0;
double btotal = 0;
String billtotal = bill.getText().toString();
Double aDbl = 0.00;
try
{
aDbl = Double.parseDouble(billtotal);
}
catch(NumberFormatException n)
{
aDbl = 0.00;
}
if (r1.isChecked())
{
atotal = aDbl * 1.1;
btotal = aDbl * 0.1;
}
if (r2.isChecked())
{
atotal = aDbl * 1.15;
btotal = aDbl * 0.15;
}
if (r3.isChecked())
{
atotal = aDbl * 1.2;
btotal = aDbl * 0.2;
}
final String bString = currencyFormatter.format(btotal);
tiptotal.setText(bString);
final String aString = currencyFormatter.format(atotal);
resulttotal.setText(aString);
}
}
});
}
}
I have some similar problem. I have a countdown in a radio group activity.
When user clicks the next Button the radio group is checked to see if an option is selected.
I implemented the button pressed at the end of the countdown, now i need to pass a checked radio Id to bypass the default user message of an option not selected.
case R.id.next:
Log.d(" ID BOTAO",((java.lang.String) String).valueOf(rGroup3.getCheckedRadioButtonId()));
if(rGroup3.getCheckedRadioButtonId()==-1){
Context context = getApplicationContext();
CharSequence text = "Please, select an option!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
break;
}
Your problem is that you never add EditText instances to the current layout.
You should add them as children of the main layout.

Categories

Resources