I'm learning to build apps for Android by making a trivia app with 3 questions: 1 using radio buttons, 1 free text field, 1 with checkboxes.
The logic is that once a user chooses or enters an answer, the radio buttons, checkboxes and EditText will be grayed out, then the user will click on the score button to get a Toast with the score and a custom message.
I have 2 problems:
(1) The EditText doesn't gray out - I have tried multiple variations using setFocusable() and setEnabled() to no avail.
(2) The score variable doesn't assign question 2 (the one with the EditText) 1 point even when the answer entered is correct.
I have started over from scratch but I haven't been able to fix these things. Any leads?
My XML
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
android:padding="16dp"
android:background="#fefcf1">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:src="#drawable/seinfeld_trivia_logo"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginTop="30dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Who are the 4 main characters?"
android:textColor="#000"
android:textSize="16sp"
android:layout_marginBottom="5dp"/>
<RadioGroup
android:id="#+id/question_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:id="#+id/question_one_answer_one"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Jerry, Elaine, George, Kessler"
android:textSize="14sp"
android:onClick="onRadioButtonQ1Clicked"/>
<RadioButton
android:id="#+id/question_one_answer_two"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Jerry, Elaine, George, Kramer"
android:textSize="14sp"
android:onClick="onRadioButtonQ1Clicked"/>
<RadioButton
android:id="#+id/question_one_answer_three"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Newman, Jerry, Kramer, George"
android:textSize="14sp"
android:onClick="onRadioButtonQ1Clicked"/>
</RadioGroup>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginTop="20dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="What is Kramer's given name?"
android:textColor="#000"
android:textSize="16sp"
android:layout_marginBottom="5dp"/>
<EditText
android:id="#+id/question_two_answer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onQ2AnswerEntered"
android:enabled="true"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginTop="20dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="What is correct about Festivus? Check all that apply."
android:textColor="#000"
android:textSize="16sp"
android:layout_marginBottom="5dp"/>
<CheckBox
android:id="#+id/question_three_answer_one"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="There is an aluminum pole"
android:layout_marginBottom="5dp"
android:onClick="onCheckBoxesQ3Clicked"/>
<CheckBox
android:id="#+id/question_three_answer_two"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="You eat ham"
android:layout_marginBottom="5dp"
android:onClick="onCheckBoxesQ3Clicked"/>
<CheckBox
android:id="#+id/question_three_answer_three"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="You air your grievances"
android:layout_marginBottom="5dp"
android:onClick="onCheckBoxesQ3Clicked"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp">
<Button
android:id="#+id/reset_me"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#03A9F4"
android:textColor="#fff"
android:text="Try Again"
android:layout_gravity="center_horizontal"
android:layout_marginRight="30dp"
android:onClick="resetQuiz"/>
<Button
android:id="#+id/score_me"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#03A9F4"
android:textColor="#fff"
android:text="Show me my score"
android:layout_gravity="center_horizontal"
android:padding="20dp"
android:onClick="showScoreMessage"/>
</LinearLayout>
</LinearLayout>
</ScrollView>
My Java
package com.example.android.seinfeldtrivia;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.Rect;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
public class MainActivity extends AppCompatActivity {
//Declaring variables - Question 1
RadioButton Q1A1, Q1A2, Q1A3;
RadioGroup Q1RadioGroup;
//Declaring variables - Question 2
EditText Q2AnswerEditText;
//Declaring variable for extracting the string from the EditText on Q2
String question2Answer;
//Declaring variables - Question 3
CheckBox Q3A1, Q3A2, Q3A3;
//Declaring variables to check the state of the checkboxes on Q3
boolean checkedQ3A1, checkedQ3A2, checkedQ3A3;
//Declaring variable - Score
int score;
//Declaring variable for the score and reset button
Button scoreMe, resetQuiz;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initializing views - Question 1
Q1RadioGroup = (RadioGroup) findViewById(R.id.question_1);
Q1A1 = (RadioButton) findViewById(R.id.question_one_answer_one);
Q1A2 = (RadioButton) findViewById(R.id.question_one_answer_two);
Q1A3 = (RadioButton) findViewById(R.id.question_one_answer_three);
//Initializing views - Question 2
Q2AnswerEditText = (EditText) findViewById(R.id.question_two_answer);
//Initializing views - Question 3
Q3A1 = (CheckBox) findViewById(R.id.question_three_answer_one);
Q3A2 = (CheckBox) findViewById(R.id.question_three_answer_two);
Q3A3 = (CheckBox) findViewById(R.id.question_three_answer_three);
//Initializing views - Score & Reset buttons
scoreMe = (Button) findViewById(R.id.score_me);
resetQuiz = (Button) findViewById(R.id.reset_me);
}
//To disable the radio groups once the user has chosen an answer
public static void enableQuestion(View view, boolean enabled) {
view.setEnabled(enabled);
view.setFocusable(enabled);
if (view instanceof ViewGroup) {
ViewGroup vg = (ViewGroup) view;
for (int i = 0; i < vg.getChildCount(); i++)
enableQuestion(vg.getChildAt(i), enabled);
}
}
//Getting the values of the answers entered
/*
* Checking which answer was selected - Question 1
*/
public void onRadioButtonQ1Clicked(View view) {
// Check that the user chose an answer
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.question_one_answer_one:
if (checked) {
yourAnswerQ1 = Q1A1;
enableQuestion(Q1RadioGroup, false);
break;
}
//Correct answer
case R.id.question_one_answer_two:
if (checked) {
yourAnswerQ1 = Q1A2;
score++;
enableQuestion(Q1RadioGroup, false);
break;
}
case R.id.question_one_answer_three:
if (checked) {
yourAnswerQ1 = Q1A3;
enableQuestion(Q1RadioGroup, false);
break;
}
}
}
/*
* Checking which answer was selected - Question 2
*/
public void onQ2AnswerEntered(View view) {
question2Answer = Q2AnswerEditText.getText().toString();
question2Answer = question2Answer.toLowerCase();
if (question2Answer.equals("cosmo")) {
//If the question is not empty, check if the answer is correct and add one point to the score
//and display the score msg
score++;
}
Q2AnswerEditText.setEnabled(false);
}
/*
* Checking which answers were selected - Question 3
*/
public void onCheckBoxesQ3Clicked(View view) {
checkedQ3A1 = Q3A1.isChecked();
checkedQ3A2 = Q3A2.isChecked();
checkedQ3A3 = Q3A3.isChecked();
if (checkedQ3A1 && checkedQ3A3) {
score++;
}
// Check which checkbox button was checked
switch(view.getId()) {
case R.id.question_four_answer_one:
if (checkedQ3A1) {
yourAnswerQ3A1 = Q3A1;
enableQuestion(Q3A1, false);
break;
}
case R.id.question_four_answer_two:
if (checkedQ3A2) {
yourAnswerQ3A2 = Q3A2;
enableQuestion(Q3A2, false);
break;
}
case R.id.question_four_answer_three:
if (checkedQ3A3) {
yourAnswerQ3A3 = Q3A3;
enableQuestion(Q3A3, false);
break;
}
}
}
public void showScoreMessage(View view) {
String scoreMessage = String.format(getResources().getString(R.string.your_score_is), score);
String customMessage = "";
//To display a short message together with the score, according to what score the user got
if (score == 0 || score == 1) {
customMessage = "No soup for you!";
} else if (score == 2) {
customMessage = "Do a fit of strength and try again.";
} else {
customMessage = "You're a master of your domain.";
}
//Displaying the score message and the score
Toast.makeText(this, scoreMessage + customMessage, Toast.LENGTH_SHORT).show();
}
public void resetQuiz(View view) {
//Enabling the questions
enableQuestion(Q1RadioGroup, true);
//Resetting questions: clearing the checked radio buttons and checkboxes
Q1RadioGroup.clearCheck();
//Resetting questions: Q3 - deleting the text in the EditText
Q3AnswerEditText.setText("");
Q3AnswerEditText.setEnabled(true);
//if the checkboxes are checked, then uncheck and enable them
if (checkedQ3A1) {
Q3A1.setChecked(false);
enableQuestion(Q3A1, true);
}
if (checkedQ3A2) {
Q3A2.setChecked(false);
enableQuestion(Q3A2, true);
}
if (checkedQ3A3) {
Q3A3.setChecked(false);
enableQuestion(Q3A3, true);
}
//Resetting the score variable
score = 0;
}
}
Using android:enabled=false or editText.setEnabled(false)
It will grey out Edittext.
Related
**activity_main xml**
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.hynes.equations.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Please select what type of equation to solve"
android:id="#+id/textView2" />
<Button
android:text="Check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignRight="#+id/textView3"
android:layout_alignEnd="#+id/textView3"
android:layout_marginRight="230dp"
android:layout_marginEnd="230dp"
android:id="#+id/button2" />
<TextView
android:layout_centerVertical="true"
android:id="#+id/textView5"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_height="50dp"
android:layout_width="250dp"
android:layout_alignRight="#+id/textView2"
android:layout_alignEnd="#+id/textView2" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:layout_above="#+id/button2"
android:layout_alignRight="#+id/textView5"
android:layout_alignEnd="#+id/textView5"
android:layout_marginRight="170dp"
android:layout_marginEnd="170dp"
android:layout_marginBottom="36dp"
android:id="#+id/editText2" />
<RadioGroup android:id="#+id/radio_group"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<RadioButton
android:text="Addition"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="26dp"
android:id="#+id/addition"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:text="Subtraction"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/radioButton"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="14dp"
android:id="#+id/subtraction"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:text="Division"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/radioButton2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="16dp"
android:id="#+id/division"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:text="Multiplication"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/radioButton3"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="20dp"
android:id="#+id/multiplication"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
`
MAIN ACTIVITY
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;`
import android.widget.RadioGroup;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
private int x;
private int y;
public int a;
public int b;
Random random = new Random();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onRadioButtonClicked(View view){
TextView display = (TextView) findViewById(R.id.textView5);
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radio_group);
int btnID = radioGroup.getCheckedRadioButtonId();
switch(btnID){
case R.id.addition:
x = random.nextInt(100);
y = random.nextInt(100);
display.setText(x + "+" + y + "=");
break;
case R.id.subtraction:
x = random.nextInt(100);
y = random.nextInt(100);
display.setText(x + "-" + y + "=");
break;
case R.id.division:
y = random.nextInt(5);
x = y*2;
display.setText(x + "/" + y + "=");
break;
case R.id.multiplication:
x = random.nextInt(10);
y = random.nextInt(10);
display.setText(x + "*" + y + "=");
break;
}
public void onClickCheck(View view){
TextView result = (TextView) findViewById(R.id.textView5);
EditText ans = (EditText) findViewById(R.id.editText2);
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radio_group);
int btnID = radioGroup.getCheckedRadioButtonId();
if(boolean(RadioButton) findViewById(R.id.addition)) ){
int key = x+y;
int try = 0;
while(!ans.equals(key)){
try = try + 1;
if(try ==0){
result.setText("Incorrect, try again!");
try++
}else if (try>2){
result.setText("Incorrect, the answer is : " + key);
}
if(ans.equals(key)){
result.setText("You are correct !");
}
}
}
}
}
}
}
This is a android studio app that's suppose to randomly generate a math equation upon creation which I've done. There's addition, subtraction, division, and multiplication. My random equation generator works perfectly. But I'm stuck at my onClickCheck method which i want to get the user's answer/input and check to see if it's correct or incorrect and display a message accordingly. My onClick method is wrong but it's a start. I don't know what methods i need to get my code to accept inputs properly. Any help would be appreciated.
It looks like you aren't assigning an OnClickListener to the button.
You need to put:(in onCreate)
Button button = (Button)findViewById(R.id.button2);
button.setOnClickListener(onClickCheck);
or
Button button = (Button)findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onClickCheck(view);
}
});
Same for the radio button.
Im trying to create a dice rolling tool as part of a larger application. However if i try to roll more than 1 dice in my dice roll function the application crashes. Howver as im new to Java i cant seem to find the cause of the index out of bounds error.
DiceActvity.Java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RadioButton;
import java.util.ArrayList;
import java.util.List;
public class DiceActivity extends AppCompatActivity
{
ListView LVDiceList;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dice);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Radio button
final RadioButton rbGreater = (RadioButton) findViewById(R.id.greaterThanRadioB);
final RadioButton rbLess = (RadioButton) findViewById(R.id.lessThanRadioB);
//Edit boxes
final EditText txtDiceType = (EditText) findViewById(R.id.diceTypeEdTxt);
final EditText txtNumberDice = (EditText) findViewById(R.id.numDiceEdTxt);
final EditText txtFilterNum = (EditText) findViewById(R.id.filterNumEdTxt);
//Buttons
Button btnRoll = (Button) findViewById(R.id.rollButton);
Button btnDiscard = (Button) findViewById(R.id.discardButton);
//Display Array
final List<Integer> diceList = new ArrayList<Integer>(10);
//Array Adapter
final ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(this, android.R.layout.simple_spinner_item, diceList);
//Set adapter
LVDiceList = (ListView) findViewById(R.id.diceResultListV);
LVDiceList.setAdapter(adapter);
//Roll the dice
btnRoll.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//Hide soft keyboard
Utils.hideKeyboard(DiceActivity.this);
//Validation of fields
//If both fields >0
if (Integer.valueOf(txtDiceType.getText().toString()) > 0 && Integer.valueOf(txtNumberDice.getText().toString()) > 0)
{
int number = Integer.valueOf(txtNumberDice.getText().toString());
int sides = Integer.valueOf(txtDiceType.getText().toString());
//Populate array
for (int i=0;i <number; i++)
{
diceList.add(i, rollDice(sides,number).get(i));
}
//Update the list view
adapter.notifyDataSetChanged();
}
return;
}
});
//Clear the list of results
btnDiscard.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
diceList.clear();
adapter.notifyDataSetChanged();
}
});
//Radio Button Validation
rbGreater.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(rbGreater.isChecked() == true)
{
rbLess.setChecked(false);
}
}
});
rbLess.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(rbLess.isChecked() == true)
{
rbGreater.setChecked(false);
};
}
});
}
//Returns a list of rolled dice results
private List<Integer> rollDice(int chance, int amount)
{
final List<Integer> rollArray = new ArrayList<Integer>(amount);
int result;
//Gives a random number between 1 and X,Y number of times
{
//BASE Equation||Min + (int)(Math.random() * ((Max - Min) + 1))
//1 = minimum roll
result = 1 + (int) (Math.random() * ((chance - 1) + 1));
rollArray.add(result);
}
return rollArray;
}
}
content_dice.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="garethgriffiths.tabletopcompanion.DiceActivity"
tools:showIn="#layout/activity_dice">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/textView_NumDice"
android:id="#+id/numDiceTextV"
android:layout_alignBottom="#+id/numDiceEdTxt"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:textSize="25dp"
android:textStyle="bold"
android:textAlignment="gravity"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="4"
android:id="#+id/numDiceEdTxt"
android:maxLength="3"
android:text="#string/edText_NumDice"
android:gravity="right"
android:selectAllOnFocus="true"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/numDiceTextV"
android:layout_toEndOf="#+id/numDiceTextV"
android:numeric="integer"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/textView_DiceType"
android:id="#+id/diceTypeTextV"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/numDiceTextV"
android:layout_alignBottom="#+id/diceTypeEdTxt"
android:layout_toLeftOf="#+id/diceTypeEdTxt"
android:layout_toStartOf="#+id/diceTypeEdTxt"
android:textSize="25dp"
android:textStyle="bold"
android:textAlignment="gravity"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="4"
android:id="#+id/diceTypeEdTxt"
android:maxLength="2"
android:text="#string/edText_DiceType"
android:layout_below="#+id/numDiceEdTxt"
android:layout_alignLeft="#+id/numDiceEdTxt"
android:layout_alignStart="#+id/numDiceEdTxt"
android:gravity="right"
android:selectAllOnFocus="true"
android:numeric="integer"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/radioB_LessThan"
android:id="#+id/lessThanRadioB"
android:layout_above="#+id/discardButton"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="36dp"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/radioB_GreaterThan"
android:id="#+id/greaterThanRadioB"
android:layout_alignTop="#+id/lessThanRadioB"
android:layout_toRightOf="#+id/lessThanRadioB"
android:layout_toEndOf="#+id/lessThanRadioB"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="4"
android:maxLength="3"
android:id="#+id/filterNumEdTxt"
android:layout_alignTop="#+id/greaterThanRadioB"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:text="#string/edText_NumFilter"
android:gravity="center"
android:selectAllOnFocus="true"
android:numeric="integer"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_Discard"
android:id="#+id/discardButton"
android:layout_alignTop="#+id/rollButton"
android:layout_toLeftOf="#+id/rollButton"
android:layout_toStartOf="#+id/rollButton"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_Roll"
android:id="#+id/rollButton"
android:layout_marginTop="108dp"
android:layout_below="#+id/diceTypeTextV"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/diceResultListV"
android:scrollIndicators="right"
android:visibility="visible"
android:layout_below="#+id/discardButton"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
</RelativeLayout>
Heres a small Class used to hide softkeyboard thats called in DiceActivity
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
/**
* http://stackoverflow.com/questions/1109022/close-hide-the-android-soft-keyboard
* Used to close soft keyboard
*/
public class Utils
{
public static void hideKeyboard(Activity activity)
{
// Check if no view has focus:
View view = activity.getCurrentFocus();
if (view != null)
{
InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
}
Your method private List<Integer> rollDice(int chance, int amount) returns a list of Integer. And according to your comment inside the method it should have multiple numbers in it.
But this method always returns only one number.
Now you invoke this method here:
for (int i=0;i <number; i++)
{
diceList.add(i, rollDice(sides,number).get(i));
}
You are invoking this method in a loop. Storing the results in a NEW list.
You get an exception because in the second loop get(i) is 1 and there is only 1 entry in this list on index 0.
To correct this is should read: .get(0)
Also this kind of implementation is very messy. Please take a paper and a pencil to figure it out.
Well, the issue is... my code is supposed to output the amount from the radiobutton clicked by the user, but it's not outputting the amount at all... I'm really not sure what the problem is. I created a radiogroup and used if-statements to determine if a radiobutton was checked or not. I think the issue is somewhere in calculating the amount.
Do I need to make a button? I thought it would calculate the amount automatically with the if-statements when a radiobutton were clicked. If I need a button, how would I go about creating one? (I'm trying to avoid using listener for now)
I'm a complete noob at android/java. I really would appreciate it if someone could explain what's wrong with my code. Thanks!
JAVA CODE
package com.Rox.crazyjoe;
import java.text.DecimalFormat;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.RadioButton;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final double smallcst = 1.25;
final double mediumcst = 2.00;
final double largecst = 3.50;
double amount;
RadioButton small = (RadioButton) findViewById(R.id.radioSmall);
RadioButton medium = (RadioButton) findViewById(R.id.radioMedium);
RadioButton large = (RadioButton) findViewById(R.id.radioLarge);
if (small.isChecked())
{
amount = smallcst;
}
else if(large.isChecked())
{
amount = largecst;
}
else if(medium.isChecked())
{
amount = mediumcst;
}
else
{
amount = 0;
}
DecimalFormat money = new DecimalFormat("$##.00");
TextView t0 = (TextView)findViewById(R.id.textAmount);
t0.setText("Total Amount: " + money.format(amount));
}
}
XML CODE:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="16dp"
android:text="Size: "
android:textAppearance="?android:attr/textAppearanceMedium" />
<RadioGroup
android:id="#+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:orientation="vertical" >
<RadioButton
android:id="#+id/radioSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_toRightOf="#+id/textView1"
android:text="Small" />
<RadioButton
android:id="#+id/radioMedium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/radioButton1"
android:layout_below="#+id/radioButton1"
android:text="Medium" />
<RadioButton
android:id="#+id/radioLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/radioMedium"
android:layout_below="#+id/radioMedium"
android:text="Large" />
</RadioGroup>
<TextView
android:id="#+id/textAmount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="40dp"
android:layout_marginRight="54dp"
android:text="TextView" />
</RelativeLayout>
You will need an event to trigger the checking of the radio buttons. At the moment, it is just checking the if statement in the onCreate and that's it (if you had a radiobutton checked by default, a value would be set here). I recommend attaching a listener to the entire RadioGroup
radioGroup1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton radioButton = (RadioButton) findViewById(checkedId);
//other logic here (like what do you want to do with this selected RadioButton)
}
});
I have had this problem crop up a few times and I can't figure out why it should happen. What happened was after moving some stuff around my TextView box ended up on top of an EditText box, which is no good. So I went and moved the TextView box to the bottom of the screen. When I did that, the app would crash when I tried to access the piggybank. However, if I move the TextView box up to the top again, it works fine.. I really don't get it. Anyways, this is the error that I got
06-22 09:06:41.928: E/AndroidRuntime(10958): java.lang.RuntimeException: Unable to
start activity ComponentInfo{net.finalexam/net.finalexam.Piggy}:
java.lang.ClassCastException: android.widget.RadioButton
This is piggy xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/piggy" >
<EditText
android:id="#+id/txtQuarters"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="27dp"
android:ems="10"
android:hint="Number of quarters"
android:inputType="number" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/txtDimes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtQuarters"
android:layout_centerHorizontal="true"
android:ems="10"
android:hint="Number of dimes"
android:inputType="number" />
<EditText
android:id="#+id/txtNickles"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtDimes"
android:layout_centerHorizontal="true"
android:ems="10"
android:hint="Number of nickles"
android:inputType="number" />
<EditText
android:id="#+id/txtPennies"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtNickles"
android:layout_centerHorizontal="true"
android:ems="10"
android:hint="Number of pennies"
android:inputType="number" />
<EditText
android:id="#+id/txtDollars"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtPennies"
android:layout_centerHorizontal="true"
android:ems="10"
android:hint="Number of Dollars"
android:inputType="number" />
<RadioGroup
android:id="#+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtDollars"
android:layout_centerHorizontal="true" >
<RadioButton
android:id="#+id/radAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Add" />
<RadioButton
android:id="#+id/radSubtract"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Subtract" />
</RadioGroup>
<Button
android:id="#+id/btnCalculate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/radioGroup1"
android:layout_centerHorizontal="true"
android:text="Calculate" />
<TextView
android:id="#+id/txtResults"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/btnCalculate"
android:layout_centerHorizontal="true"
android:layout_marginTop="27dp"
android:textSize="40sp" android:textStyle="bold" android:textColor="#000000"/>
</RelativeLayout>
This is the Piggy Java file
package net.finalexam;
import java.text.DecimalFormat;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
public class Piggy extends Activity
{
double quartersValue = .25;
double dimesValue = .10;
double nicklesValue = .05;
double penniesValue = .01;
double dollarsValue = 1;
double quartersMoney;
double dollarsMoney;
double dimesMoney;
double nicklesMoney;
double penniesMoney;
double totalMoney;
double newTotalMoney;
double oldTotalMoney = 0;
int numberOfQuarters;
int numberOfDimes;
int numberOfNickles;
int numberOfPennies;
int numberOfDollars;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.piggybank);
final EditText quarters = (EditText) findViewById(R.id.txtQuarters);
final EditText dimes = (EditText) findViewById(R.id.txtDimes);
final EditText nickles = (EditText) findViewById(R.id.txtNickles);
final EditText pennies = (EditText) findViewById(R.id.txtPennies);
final EditText dollars = (EditText) findViewById(R.id.txtDollars);
Button calculate = (Button) findViewById(R.id.btnCalculate);
final TextView results = ((TextView) findViewById(R.id.txtResults));
final RadioButton add = (RadioButton) findViewById(R.id.radAdd);
final RadioButton subtract = (RadioButton) findViewById(R.id.radSubtract);
calculate.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
if (quarters.getText().toString().equals(""))
{
numberOfQuarters = 0;
}
else
{
numberOfQuarters = Integer.parseInt(quarters.getText().toString());
}
if (dimes.getText().toString().equals(""))
{
numberOfDimes = 0;
}
else
{
numberOfDimes = Integer.parseInt(dimes.getText().toString());
}
if (nickles.getText().toString().equals(""))
{
numberOfNickles = 0;
}
else
{
numberOfNickles = Integer.parseInt(nickles.getText().toString());
}
if (pennies.getText().toString().equals(""))
{
numberOfPennies = 0;
}
else
{
numberOfPennies = Integer.parseInt(pennies.getText().toString());
}
if (dollars.getText().toString().equals(""))
{
numberOfDollars = 0;
}
else
{
numberOfDollars = Integer.parseInt(dollars.getText().toString());
}
quartersMoney = numberOfQuarters * quartersValue;
dimesMoney = numberOfDimes * dimesValue;
nicklesMoney = numberOfNickles * nicklesValue;
penniesMoney = numberOfPennies * penniesValue;
dollarsMoney = numberOfDollars;
totalMoney = quartersMoney + dimesMoney + nicklesMoney + penniesMoney + dollarsMoney;
DecimalFormat currency = new DecimalFormat("$###,###.##");
if (add.isChecked())
{
if (totalMoney > 0)
{
newTotalMoney = oldTotalMoney + totalMoney;
oldTotalMoney = newTotalMoney;
results.setText(currency.format(newTotalMoney));
}
else
{
Toast.makeText(Piggy.this, "You need to do more chores!!", Toast.LENGTH_LONG).show();
}
}
if (subtract.isChecked())
{
newTotalMoney = oldTotalMoney - totalMoney;
}
if (newTotalMoney > 0)
{
oldTotalMoney = newTotalMoney;
results.setText(currency.format(newTotalMoney));
}
else
{
Toast.makeText(Piggy.this, "Save more money kido!!", Toast.LENGTH_LONG).show();
};
}
});
}
}
I have searched for an answer but they all seem to be slightly different situations. Any ideas? Thanks. And like I said, this works fine if the TextView box is overlapping the quarters EditText box.
Edit 1 Here is the screen before the piggy bank
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ImageView
android:id="#+id/ic_launcher_money"
android:layout_width="100px"
android:layout_height="100px"
android:layout_marginLeft="4px"
android:layout_marginRight="10px"
android:layout_marginTop="2px"
android:src="#drawable/ic_launcher_money"></ImageView>
<TextView
android:id="#+id/bankses"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#+id/bankses"
android:textSize="25sp">
</TextView>
</LinearLayout>
Main.java
package net.finalexam;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Main extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
String[] banks ={"Piggy Bank","Adult Bank"};
setListAdapter(new ArrayAdapter<String>(this,R.layout.main, R.id.bankses, banks));
}
protected void onListItemClick(ListView l, View v, int position, long id){
switch(position){
case 0:
startActivity(new Intent(Main.this,Piggy.class));
break;
case 1:
startActivity(new Intent(Main.this,Adultbank.class));
break;
}
}
}
Try cleaning your project on Eclipse. It often fixes that kind of problems.
I'm new to programming for the android and I'm trying to create a simple program.
If the user enters a number in the attacker ws field and the same number defender ws field you should get an answer.
I'm missing something.
package com.example.helloandroid;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class HelloAndroid extends Activity implements OnClickListener
{
private EditText text, text2, text3;
private Button btutorial1;
int result = text.toString().compareTo(text2.toString());
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = new TextView(this);
tv.setText("I hope this works");
text = (EditText) findViewById(R.id.editText1);
text2 =(EditText) findViewById(R.id.editText2);
text3 = (EditText) findViewById(R.id.editText3);
btutorial1 = (Button) findViewById(R.id.button1);
btutorial1.setOnClickListener(this);
}
public void onClick(View view)
{
switch (view.getId())
{
case R.id.button1:
if (text.getText().toString().equals(1) && text2.getText().toString().equals(2))
{
text3.setText("Five and above");
return;
}
else if (text.getText().toString().equals(1) && text2.getText().toString().equals(3))
{
text3.setText("Five and above");
return;
}
else if (text.getText().toString().equals(1) && text2.getText().toString().equals(3))
{
text3.setText("Four and above");
return;
}
else if (text.getText().toString().equals(text2.getText().toString()))
{
text3.setText("Four and above");
return;
}
else
{
text3.setText("Not Working");
return;
}
}
}
}
My XML class named main
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView android:id="#+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Enter Attacker ws"></TextView>
<EditText android:id="#+id/editText1" android:text="" android:layout_height="wrap_content" android:layout_width="match_parent" android:inputType="number" android:visibility="visible"></EditText>
<TextView android:id="#+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Enter Opponent ws"></TextView>
<EditText android:id="#+id/editText2" android:text="" android:layout_height="wrap_content" android:layout_width="match_parent" android:visibility="visible" android:inputType="number"></EditText>
<Button android:id="#+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Calculate" android:visibility="visible" android:onClick="myClickHandler"></Button>
<EditText android:id="#+id/editText3" android:layout_height="wrap_content" android:layout_width="match_parent" android:name="result" android:editable="false"></EditText>
</LinearLayout>
In java with objects == checks if 2 variables have the same memory location, not that they are the same value. Use .equals() instead and it should work
If you are comparing two integers then do this.
int number1 = Integer.parseInt(text);
int number2= Integer.parseInt(text2);
now in if condition compare number1 and number2.
if (number1 == number2)
{
text3.setText("Four and above");
return;
}
Remember this will work only for integers. for any string you will get exception you can handle it later on.
if you are planning to compare text then use use text.getText().toString().equals(text2.getText().toString())