Moving TextView Box made my android app crash - java

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.

Related

Rectangle Area Calculation

I am trying to calculate the rectangle area in my application. I have created a simple layout but for some reason, data is not parsed into the application. I tried to print it in the console but nothing is shown.
This is my Main Class:
package com.example.week3labcode;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button calcButton;
EditText number1, number2, resultFinal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
calcButton = (Button)findViewById(R.id.button1);
number1 = (EditText) findViewById(R.id.edtext1);
number2 = (EditText) findViewById(R.id.edtext2);
resultFinal = (EditText) findViewById(R.id.edtext3);
}
#Override
public void onClick(View v){
if(v == calcButton){
number1 = (EditText) findViewById(R.id.edtext1);
number2 = (EditText) findViewById(R.id.edtext2);
double num1 = Double.parseDouble(number1.getText().toString());
double num2 = Double.parseDouble(number2.getText().toString());
calcRectangle(num1, num2);
}
}
public void calcRectangle(double x, double y){
double result = x * y;
System.out.println(result);
resultFinal = (EditText) findViewById(R.id.edtext3);
resultFinal.setText(Double.toString(result));
System.out.println('H' + result);
}
}
And the following code in my XML file that provides layout for the application:
<?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="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/label1"
android:layout_centerHorizontal="true"
android:layout_marginVertical="20px"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Rectangle Area Calculation" />
<TextView
android:id="#+id/label2"
android:layout_below="#+id/label1"
android:layout_centerHorizontal="true"
android:layout_marginVertical="10px"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter Length" />
<EditText
android:id="#+id/edtext1"
android:layout_toRightOf="#+id/label2"
android:layout_centerHorizontal="true"
android:layout_alignBaseline="#+id/label2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
<TextView
android:id="#+id/label3"
android:layout_below="#+id/label2"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter breadth" />
<EditText
android:id="#+id/edtext2"
android:layout_toRightOf="#+id/label3"
android:layout_alignBaseline="#+id/label3"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
<Button
android:id="#+id/button1"
android:layout_below="#+id/label3"
android:layout_centerHorizontal="true"
android:layout_marginTop="50px"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calculate" />
<TextView
android:id="#+id/label4"
android:layout_below="#+id/button1"
android:layout_centerHorizontal="true"
android:layout_marginVertical="20px"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Area in cm2" />
<EditText
android:id="#+id/edtext3"
android:layout_toRightOf="#+id/label4"
android:layout_centerHorizontal="true"
android:layout_alignBaseline="#+id/label4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
<Button
android:id="#+id/button2"
android:layout_below="#+id/label4"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Clear Entries" />
</RelativeLayout>
You have not set OnClickListener to your Button so calcRectangle() method is never called.
calcButton = (Button)findViewById(R.id.button1);
calcButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
number1 = (EditText) findViewById(R.id.edtext1);
number2 = (EditText) findViewById(R.id.edtext2);
double num1 = Double.parseDouble(number1.getText().toString());
double num2 = Double.parseDouble(number2.getText().toString());
calcRectangle(num1, num2);
}
});
OR
calcButton.setOnClickListener(this);

how to use edittext inside the radiogroup in android?

**I have used four radio buttons for adding and subtraction the amount in the wallet. whenever i open the app it crashes .Whenever i open the app it crashes i don't what is error please someone help me. i am new to android. In this app i have used four radio buttons for add the amount and subtracting the amount. **
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#drawable/form"
tools:context="com.sivaneshsg.wallet.MainActivity">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Amount"
android:textSize="25sp"
android:textStyle="italic"
android:textColor="#android:color/black"
android:paddingTop="5dp"
android:paddingBottom="10dp"
android:paddingLeft="10dp"/>
<EditText
android:id="#+id/inputamount"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Amount in Rs."
android:paddingTop="5dp"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:inputType="number"
android:ems="10"
/>
<RadioGroup
android:id="#+id/rgroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Income"
android:textStyle="italic"
android:textSize="20sp"
android:textColor="#android:color/black"
android:paddingBottom="10dp"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton
android:id="#+id/cash1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cash"
android:textSize="15dp"
android:paddingRight="10dp"
android:textColor="#android:color/black"
/>
<RadioButton
android:id="#+id/card1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Card"
android:textColor="#android:color/black"
/>
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Expense"
android:textSize="20dp"
android:textStyle="italic"
android:textColor="#android:color/black"
android:paddingBottom="10dp"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton
android:id="#+id/cash2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cash"
android:textColor="#android:color/black"
android:textSize="15sp"
android:paddingRight="10dp"
/>
<RadioButton
android:id="#+id/card2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Card"
android:textSize="15sp"
android:textColor="#android:color/black"
/>
</LinearLayout>
</RadioGroup>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OK"
/>
<TextView
android:id="#+id/amountcard"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/black"
android:text="Amount in Card : RS. 0"
android:textSize="25sp"
android:padding="10dp"/>
<TextView
android:id="#+id/amountcash"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Amount in Cash : Rs. 0"
android:textSize="25sp"
android:textColor="#android:color/black"
android:padding="10dp"/>
<TextView
android:id="#+id/amountwallet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Total Amount in Wallet : RS. 0"
android:textSize="23sp"
android:textColor="#android:color/black"
android:textStyle="bold"
android:padding="10dp"/>
</LinearLayout>
package com.sivaneshsg.wallet;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.T;
public class MainActivity extends AppCompatActivity {
int cashamount = 0;
int cardamount = 0;
int totalamount;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText et = (EditText) findViewById(R.id.inputamount);
final int amount = Integer.parseInt(et.getText().toString());
RadioGroup rg = (RadioGroup) findViewById(R.id.rgroup);
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == R.id.card1) {
cardamount = cardamount + amount;
} else if (checkedId == R.id.cash1) {
cashamount = cashamount + amount;
} else if (checkedId == R.id.cash2) {
cashamount = cashamount - amount;
} else if (checkedId == R.id.card2) {
cardamount = cardamount - amount;
}
}
});
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView cash = (TextView) findViewById(R.id.amountcash);
TextView card = (TextView) findViewById(R.id.amountcard);
TextView wallet = (TextView) findViewById(R.id.amountwallet);
cash.setText("Amount in Cash : RS. " + cashamount);
card.setText("Amount in Card : RS. " + cardamount);
totalamount = cashamount + cashamount;
wallet.setText("Total Amount in Wallet : RS. " + totalamount);
}
});
}
}
**Whenever i open the app it crashes i don't what is error please someone help me. i am new to android. In this app i have used four radio buttons for add the amount and subtracting the amount. **
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
public class teste extends AppCompatActivity {
int cashamount = 0;
int cardamount = 0;
int totalamount;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.iuiu);
EditText et = (EditText) findViewById(R.id.inputamount);
final String amount = (et.getText().toString());
RadioGroup rg = (RadioGroup) findViewById(R.id.rgroup);
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == R.id.card1) {
cardamount = Integer.parseInt(cardamount + amount);
} else if (checkedId == R.id.cash1) {
cashamount = Integer.parseInt(cashamount + amount);
} else if (checkedId == R.id.cash2) {
cashamount -= Integer.parseInt(amount);
} else if (checkedId == R.id.card2) {
cardamount -= Integer.parseInt(amount);
}
}
});
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView cash = (TextView) findViewById(R.id.amountcash);
TextView card = (TextView) findViewById(R.id.amountcard);
TextView wallet = (TextView) findViewById(R.id.amountwallet);
cash.setText("Amount in Cash : RS. " + cashamount);
card.setText("Amount in Card : RS. " + cardamount);
totalamount = cashamount + cashamount;
wallet.setText("Total Amount in Wallet : RS. " + totalamount);
}
});
}
}
try the above code your problem was here
final int amount = Integer.parseInt(et.getText().toString());

Trying to receive input and display if it's correct or incorrect using ANDROID STUDIO

**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.

Crash on creating a list size >1 to pass into list view (Index out of bounds)

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.

Android studio, android scrolling down and up enable

I want to add something like scrolling from top to bottom and vice versa but i don't know how to add this function, i was trying with ScrollView but that gave nothing.
MainActivity.java :
package com.example.marek.przelicznikpaliw;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
private EditText a1;
private EditText b1;
private EditText c1;
private EditText d1;
private TextView tv;
private TextView tv2;
private TextView tv3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//pola
a1 = (EditText) findViewById(R.id.cel);
b1 = (EditText) findViewById(R.id.pali);
c1 = (EditText) findViewById(R.id.litr);
d1 = (EditText) findViewById(R.id.koszt);
// wynik
tv = (TextView) findViewById(R.id.wynikKoszt);
tv2 = (TextView) findViewById(R.id.wynikKilometry);
tv3 = (TextView) findViewById(R.id.wynikKosztx2);
findViewById(R.id.button).setOnClickListener(onClickListener);
findViewById(R.id.button2).setOnClickListener(onClickListener);
}
private View.OnClickListener onClickListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
float a = 0;
float b = 0;
float c = 0;
float d = 0;
float wynik = 0;
float wynik2 = 0;
float wynik3 = 0;
try {
a = Float.parseFloat(a1.getText().toString());
b = Float.parseFloat(b1.getText().toString());
c = Float.parseFloat(c1.getText().toString());
d = Float.parseFloat(d1.getText().toString());
} catch (Exception e) {
e.printStackTrace();
}
if (view.getId() == R.id.button) {
wynik = ((b / 100) * a) * c;
tv.setText(String.valueOf(wynik));
wynik2 = (((b / 100) * a) * c)*2;
tv3.setText(String.valueOf(wynik2));
} else if (view.getId() == R.id.button2) {
wynik3 = d / ((b * c) / 100);
tv2.setText(String.valueOf(wynik3));
}
}
};
}
activity_main.xml :
<LinearLayout 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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity"
android:orientation="vertical"
android:onClick="onButtonClick"
android:weightSum="1">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/cel"
android:hint="Ilosc km do celu to:"
android:layout_centerHorizontal="true"
android:numeric="integer|decimal" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/pali"
android:hint="Ile litrow pali na 100km"
android:layout_centerHorizontal="true"
android:layout_below="#+id/cel"
android:numeric="integer|decimal" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/litr"
android:hint="Cena za litr"
android:layout_below="#+id/pali"
android:layout_centerHorizontal="true"
android:numeric="integer|decimal" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button"
android:layout_below="#+id/litr"
android:layout_centerHorizontal="true"
android:hint="Licz zlotowki"
android:text="Licz koszty"
android:clickable="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/koszt"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:hint="Za ile zl zostalo zatankowane gaz/paliwo?"
android:numeric="integer|decimal" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Licz kilometry"
android:id="#+id/button2"
android:layout_below="#+id/koszt"
android:layout_centerHorizontal="true"
android:clickable="true" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Dojedziesz w wybrany cel za(zł):"
android:id="#+id/textView" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/emptystring"
android:id="#+id/wynikKoszt"
android:textIsSelectable="false" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Oraz spowrotem za(zł):"
android:id="#+id/textView2" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/emptystring"
android:id="#+id/wynikKosztx2"
android:layout_weight="0.06" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Za tę kwotę przejedziesz(km):"
android:id="#+id/textView3" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/emptystring"
android:id="#+id/wynikKilometry" />

Categories