I have been trying to learn Java for Android development, so I decided to try to make a simple converter application to learn from. At the moment i have a simple UI and I am trying to convert from Celsius to Fahrenheit. the converter will, when working, convert betweem Celsius, Fahrenheit and Kelvin.
When I click the button that is supposed to run the calculation method, i get the error "Unfortunately, Converter has stopped."
Below is my code, I have also included the XML for the view as well.
package com.michaelmurphy.converter;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.Spinner;
public class Temperature extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.temperature_view);
// TODO Auto-generated method stub
}
public void tempCalc()
{
//define variables
float value = 0;
String from = "";//for spinner
String to = "";//for spinner
//get entered value
EditText input = (EditText) findViewById(R.id.editText1);
//convert to string
String enteredValue = input.getText().toString();
//convert string into float
float num = Float.valueOf(enteredValue);
//retrieve the from spinner value
final Spinner fromSpinner = (Spinner) findViewById(R.id.spinner1);
from = fromSpinner.getSelectedItem().toString();
//retrieve the to spinner value
final Spinner toSpinner = (Spinner) findViewById(R.id.spinner1);
to = toSpinner.getSelectedItem().toString();
EditText output = (EditText) findViewById(R.id.textView2);
/*if(from.equals(to)) //the same conversion type
{
//error
}*/
if(from.equals("Celcius"))
{
if(to.equals("Fahrenheit"))
{
value = celToFar(num);
}
else
{
//value = celToKel(num);
}
}
else if(from.equals("Fahrenheit"))
{
if(to.equals("Celcius"))
{
//value = fahToCel(num);
}
else
{
//value = fahToKel(num);
}
}
else //kelvin
{
if(to.equals("Celcius"))
{
//value = kelToCel(num);
}
else
{
//value = kelToFah(num);
}
}
//set the label to variable value
String valueStr = Float.toString(value);//cast float to string
output.setText(valueStr);
}
public float celToFar(float cel)
{
float fah = cel * 9/5 + 32;
return fah;
}
}
View XML code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/app_name"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="numberDecimal" >
<requestFocus />
</EditText>
<Spinner
android:id="#+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/temp_arr" />
<Spinner
android:id="#+id/spinner2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/temp_arr" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/convertBtn"
android:onClick="tempCalc" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
Is anyone able to point out where I am going wrong, I have no idea. Thanks
Change:
public void tempCalc()
To
public void tempCalc(View v)
Any onClick method expects a View parameter. As you don't pass one, the method signatures don't match, and your app throws an exception.
Related
So I want to read the input of an EditText field. It is not working. I debugged it and I saw, that the EditText view was listed there. But when I printed it to the console, it was empty. I don't know why, because I did put a text in it. Also, the ID is right, and I really don't know what's wrong
Here is the View where the EditText is:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".counters.AddCounter">
<TextView
android:id="#+id/txtNewCounter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/allerta"
android:text="#string/addNewCounter"
android:textSize="30sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/btnSaveCounter"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:fontFamily="#font/allerta"
android:text="#string/save"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="#+id/txtCounterName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:fontFamily="#font/allerta"
android:text='#string/newCounterName'
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/txtNewCounter" />
<EditText
android:id="#+id/inpuTextNewCounterName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="10dp"
android:contentDescription="#string/name"
android:ems="10"
android:hint="#string/name"
android:inputType="textPersonName"
android:singleLine="true"
android:text="Cookies don't"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/txtCounterName" />
<TextView
android:id="#+id/txtCounterEntryValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="20dp"
android:fontFamily="#font/allerta"
android:text="#string/entryNum"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/inpuTextNewCounterName" />
<EditText
android:id="#+id/numEntryNum"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="10dp"
android:layout_marginEnd="10dp"
android:ems="10"
android:hint="#string/number"
android:inputType="number"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/txtCounterEntryValue" />
</androidx.constraintlayout.widget.ConstraintLayout>
Here is my code to evaluate the form:
public class AddCounter extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_counter);
//Setting save button action listener
findViewById(R.id.btnSaveCounter).setOnClickListener(new ActionListeners().getSaveCounter());
}
public static void evaluateCounter(View view) throws NoNameException, NumberOutOfBoundException {
//Getting context
Context context = view.getContext();
//Counter Name
View viewEdit = View.inflate(context, R.layout.activity_add_counter, null);
EditText counterName = viewEdit.findViewById(R.id.inpuTextNewCounterName);
System.out.println("Cookies fly like:" + counterName.getText().toString() + "!");
//Input to string
String name = counterName.getText().toString();
//If no name was specified exception thrown
if (name.equals("")) {
throw new NoNameException(context.getString(R.string.noNameSpecified));
}
//get entry number
EditText numberView = View.inflate(context, R.layout.activity_add_counter, null).findViewById(R.id.numEntryNum);
//Number
int number = 0;
//If nothing specified
if (!(numberView.getText().toString().equals(""))) {
if (Integer.parseInt(numberView.getText().toString()) > 1000 || Integer.parseInt(numberView.getText().toString()) < -1000) {
throw new NumberOutOfBoundException(context.getString(R.string.numOutOfBound));
}
}
//New Counter Object
Counter counter = new Counter(number, name);
//storing counter
ToJson toJson = new ToJson();
toJson.storeCounter(counter, context);
}
}
As you can see here, this if-statement is always true.
To look, what the text looks like, I printed out a text:
System.out.println("Cookies fly like:" + counterName.getText().toString() + "!");
I did put a word in the input and the output is empty, as you can see here:
I/System.out: Cookies fly like:!
Here is my ActionListener:¨
public class ActionListeners {
private OnClickListener saveCounter = v -> {
try {
//Evaluate Counter
AddCounter.evaluateCounter(v);
} catch (NoNameException e) {
//If no name was specified
CounterMethods.makeSnackbar(v, Snackbar.LENGTH_SHORT, HapticFeedbackConstants.REJECT, v.getContext().getString(R.string.noNameSpecified));
e.printStackTrace();
} catch (NumberOutOfBoundException e) {
//If entry is higher or lower than available
CounterMethods.makeSnackbar(v, Snackbar.LENGTH_SHORT, HapticFeedbackConstants.REJECT, v.getContext().getString(R.string.numOutOfBound));
}
};
public OnClickListener getSaveCounter() {
return this.saveCounter;
}
}
As you can see, I did set the text to "Cookies can't fly" in the xml file, however, if I change the text to something different in the app, the output is the text I did set in the XML.
I/System.out: Cookies fly like:Cookies can't fly!
What is the problem?
try this
public class AddCounter extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_counter);
//declare Counter Name EditText
EditText counterName = findViewById(R.id.inpuTextNewCounterName);
//declare btnSaveCounter Button
Button btnSaveCounter = findViewById(R.id.btnSaveCounter);
//declare get entry number EditText
EditText numberView = findViewById(R.id.numEntryNum);
//btnSaveCounter setOnClickListener
btnSaveCounter.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//Input to string
String name = counterName.getText().toString();
System.out.println("Cookies fly like:" + name + "!");
//If no name was specified
if (name.equals("")){
System.out.println( "getString(R.string.noNameSpecified)" );//todo
}
//If nothing specified
String numbrv = numberView.getText().toString();
if (!(numbrv.equals(""))){
if (Integer.parseInt(numbrv) > 1000 || Integer.parseInt(numbrv) < -1000) {
System.out.println( "getString(R.string.numOutOfBound)" );//todo
}
}
//Number
int number = 0;
//New Counter Object
Counter counter = new Counter(number, name);
//storing counter
ToJson toJson = new ToJson();
toJson.storeCounter(counter, context);
} });
}
}
I'm kinda new to android. So I'm trying calculate the price of something using EditText instead of ListView, and I have increment and decrement buttons included to increase the value on the EditText component.
So the increment and decrement buttons are working okay. They are decrementing and incrementing the value in EditText, and are calculating the price just fine, but when I type in the EditText instead of using the buttons the value I typed doesn't get used.
Here's my Code.
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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="#drawable/latte" />
<TextView
android:id="#+id/quantitytxt_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="Quantity ( Cup(s) )"
android:textAllCaps="true"
android:textColor="#android:color/white"
android:textSize="16sp" />
<Button
android:id="#+id/decrementButton"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_below="#id/quantitytxt_textview"
android:onClick="decrement"
android:text="-"
android:textSize="15sp" />
<EditText
android:id="#+id/quantity_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/quantitytxt_textview"
android:layout_toRightOf="#id/decrementButton"
android:padding="10dp"
android:inputType="text"
android:text="0"
android:textColor="#android:color/white"
android:textSize="16sp" />
<Button
android:id="#+id/incrementButton"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_below="#id/quantitytxt_textview"
android:layout_toRightOf="#id/quantity_textview"
android:onClick="increment"
android:text="+"
android:textSize="15sp" />
<TextView
android:id="#+id/pricetxt_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/quantity_textview"
android:padding="10dp"
android:text="Price (1 Cup = KES 5)"
android:textAllCaps="true"
android:textColor="#android:color/white"
android:textSize="16sp" />
<TextView
android:id="#+id/price_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/pricetxt_textview"
android:padding="10dp"
android:text="KES 0"
android:textColor="#android:color/white"
android:textSize="16sp" />
<Button
android:id="#+id/myButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/price_textview"
android:onClick="submitOrder"
android:text="Order"
android:textSize="15sp" />
</RelativeLayout>
Java
package com.teqqli.justjava;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.text.NumberFormat;
/**
* This app displays an order form to order coffee.
*/
public class MainActivity extends AppCompatActivity {
int quantity = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* This method is called when the order button is clicked.
*/
public void submitOrder(View view) {
int price = quantity*5;
displayPrice(price);
}
public void increment (View view) {
quantity = quantity + 1;
display(quantity);
}
public void decrement (View view) {
if (quantity>0){
quantity = quantity - 1;
display(quantity);
}
}
/**
* This method displays the given quantity value on the screen.
*/
private void display(int number) {
EditText quantityText = (EditText) findViewById(R.id.quantity_textview);
quantityText.setText("" + number);
}
/**
* This method displays the given price on the screen.
*/
private void displayPrice(int number) {
TextView priceTextView = (TextView) findViewById(R.id.price_textview);
// priceTextView.setText(NumberFormat.getCurrencyInstance().format(number));
priceTextView.setText("KES " + number);
}
}
Kindly can anyone assist me?
Use quantityText.getText() function to get the value and store it in a variable and then do the increment and decrement operation on this value.
Something like this:
int value = Integer.parseInt(quantityText.getText().toString().trim());
and then pass this value to your increment and decrement functions.
Try:
public class MainActivity extends AppCompatActivity {
EditText quantityText;
int quantity = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
quantityText= (EditText) findViewById(R.id.quantity_textview);
}
/**
* This method is called when the order button is clicked.
*/
public void submitOrder(View view) {
quantity = Integer.parseInt(quantityText.getText().toString());
int price = quantity*5;
displayPrice(price);
}
public void increment (View view) {
quantity = quantity + 1;
display(quantity);
}
public void decrement (View view) {
if (quantity>0){
quantity = quantity - 1;
display(quantity);
}
}
/**
* This method displays the given quantity value on the screen.
*/
private void display(int number) {
quantityText.setText("" + number);
}
/**
* This method displays the given price on the screen.
*/
private void displayPrice(int number) {
TextView priceTextView = (TextView) findViewById(R.id.price_textview);
priceTextView.setText("KES " + number);
}
}
its simple, for create onclick event:
final EditText input = (EditText) findViewById(R.id.textview_id);
final TextView view = (TextView) findViewById(R.id.textview_id);
final Button button = findViewById(R.id.button_id);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
view.setText(input.getText().toString());
}
});
The reason your EditText doesn't get used is because you are not getting the value from EditText. So get that value like;
String valueFromEditText=quantityText.getText().toString(); // Getting string value from EditText
int valueFromEditTextInIntegerFormat=Integer.parseInt(valueFromEditText) // Converting string value received into integer format
Now use this integer value for performing whatever operations you want
Good Luck :)
You need to create this method:
private void display()
{
EditText quantityText = (EditText) findViewById(R.id.quantity_textview);
int value = Integer.parseInt(quantityText.getText().toString());
quantity=value;
Log.i("vl", "display: "+value);
}
//replace your method with this
public void submitOrder(View view) {
if(quantity==0)
{
display();
}
int price = quantity*5;
quantity=0;
displayPrice(price);
}
//if you get any problem ask me in a comment
String yourValue = quantityText.getText().toString(); //gets you the contents of edit text
tvTextView.setText(yourValue); //displays it in a textview..
Use quantity = Integer.parseInt(quantityText.getText().toString());
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.
i am facing this problem right now. i want to generate a receipt of food along with its price and total price (summation of all checked check box-the selected menu)
this is the code for the check box page where user need to checked on items that they would like to buy.
<RelativeLayout >
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<CheckBox
android:id="#+id/pakejC1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Beg" />
<CheckBox
android:id="#+id/pakejC2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Shoes" />
<ImageButton
android:id="#+id/gobutton"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignTop="#+id/homebtn"
android:layout_toRightOf="#+id/homebtn"
android:background="#drawable/gobutton"
android:onClick="goReceiptC" />
this is the code for the process
public class item extends Activity
{
CheckBox beg1, shoes1;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.item);
beg1 = (CheckBox) findViewById(R.id.pakejC1);
shoes1 = (CheckBox) findViewById(R.id.pakejC2);
}
public void goReceiptC(View v)
{
Intent intent = new Intent(v.getContext(), doReceiptC.class);
intent.putExtra("beg1", beg1.isChecked());
intent.putExtra("shoes1", shoes1.isChecked());
startActivityForResult(intent,0);
}
}
this is the process for the display receipt
public class doReceipt extends Activity
{
boolean beg1, shoes1;
TextView tvOutput1,tvOutput2;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.receipt);
tvOutput1 = (TextView) findViewById(R.id.textView1);
tvOutput2 = (TextView) findViewById(R.id.textView2);
Bundle data = this.getIntent().getExtras();
beg1=data.getBoolean("beg1");
shoes1=data.getBoolean("shoes1");
if(beg2==true)
{
tvOutput1.setText("Nasi Putih RM 1.00");
tvOutput1.setVisibility(View.VISIBLE);
// this is where i would like to display the price
//eg rm 1.00
}
else
{
tvOutput1.setVisibility(View.GONE);
}
if (shoes1==true)
{
tvOutput2.setText("shoes RM 1.50");
tvOutput2.setVisibility(View.VISIBLE);
// this is where i would like to display the price
//eg rm 1.50
}
else
{
tvOutput2.setVisibility(View.GONE);
}
** i want the total price for both checked item to be display in the receipt as total
this is the page for display the receipt
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textA"
android:layout_below="#+id/textA"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/textView1"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/textView1"
android:text="total price"
android:textAppearance="?android:attr/textAppearanceMedium" />
help me plz....
You are not very clear about from where are these values coming.
But what you can do is:
//global variables
float bagPrice = 1.0f, shoesPrice = 1.5f, total = 0f;
//your logic of getting values
if(beg2==true)
{
//do what you want in textviews
total += bagPrice;
}
else
{
//your code
}
if (shoes1==true)
{
//do what you want in textviews
total += shoesPrice;
}
else
{
//your code
}
Toast.makeText(getApplicationContext(), String.valueOf(total), Toast.LENGTH_SHORT).show(); //show total in TextView using String.valueOf(total)
Hope this helps.
You could also extend CheckBox and add a price float attribute and set its value in the constructor, then create a new method getPrice that return 0 or this.price depending of whether its checked or not.
Pseudo code
public class PriceCheckBox() extends CheckBox {
private float price;
public PriceCheckBox(float price) {
super():
this.price = price;
}
public float getPrice() {
if(isChecked()){
return this.price;
} else {
return 0;
}
}
//You could also add a setter here if you wish to change price later.
Then simply use PriceCheckBox instead of CheckBox and call getPrice() instead isChecked().
Using my onEditTextchanger. It works fine when the user inputs 100000, in the EditText box it shows $100,000.00 as the user types. Which is correct.
The problem is however if I try to display a numeric keyboard rather than a Qwerty keyboard. By adding in the XML I add android: inputType=”numberDecimal” I lose the formatting of $ and the, and the EditText displays like 100000.00. I have noticed this happens if I change the InputType to Number or Decimal as well. I have attached the code.
Any ideas? Again Thanks in advance for your help.
XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Number1"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/txta"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="0" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Number2" />
<EditText
android:id="#+id/txtb"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="0" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Number3" />
<TextView
android:id="#+id/txtc"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your Answer is"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/txtd"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/buttonCalc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calculate" />
Java
public class CalcTestActivity extends Activity {
private EditText txta;
private EditText txtb;
private TextView txtc;
private TextView txtd;
private double a = 0;
private double b = 0;
private double c = 0;
private double d = 0;
private Button buttonCalc;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initControls();
txta.addTextChangedListener(new CurrencyTextWatcher());
txtb.addTextChangedListener(new CurrencyTextWatcher());
}
private void initControls() {
txta = (EditText)findViewById(R.id.txta);
txtb = (EditText)findViewById(R.id.txtb);
txtc = (TextView)findViewById(R.id.txtc);
txtd = (TextView)findViewById(R.id.txtd);
buttonCalc = (Button)findViewById(R.id.buttonCalc);
buttonCalc.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {calculate(); }});}
private void calculate() {
a=Double.parseDouble(txta.getText().toString().replace("$", "").replace(",", ""));
b=Double.parseDouble(txtb.getText().toString().replace("$", "").replace(",", ""));
c=Math.round(a*.88);
txtc.setText(GlobalMoney.FormatValue(c));
d=Math.round((a*.87)+(b*.61)*(c*.25));
txtd.setText(GlobalMoney.FormatValue(d));
}
}
TextWatcher
import java.text.NumberFormat;
import android.text.Editable;
import android.text.TextWatcher;
public class CurrencyTextWatcher implements TextWatcher {
boolean mEditing;
public CurrencyTextWatcher() {
mEditing = false;
}
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
if(!mEditing) {
mEditing = true;
String digits = s.toString().replaceAll("\\D", "");
NumberFormat nf = NumberFormat.getCurrencyInstance();
try{
String formatted = nf.format(Double.parseDouble(digits)/100);
s.replace(0, s.length(), formatted);
} catch (NumberFormatException nfe) {
s.clear();
}
mEditing = false;
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
}
By default, inputType=”numberDecimal” doesn't accept any special characters except .(dot). May be you need to do some hack to make this work. There is an interesting SO discussion to hack in special character ','. You may try that to have $ symbol. Here is link.