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().
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());
I'm building a GPA calculator with android studio
What I have:
I have an edit text for credit unit and another for grade with different ID's
I have a method for the button
the app runs fine but when i input a value for the creditunit and a value for the grade, nothing happens when i click the button.
here is my xml
edit text for credit unit
<EditText
android:id="#+id/txt_credits"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="6dp"
android:layout_weight="1"
android:background="#drawable/border"
android:ems="4"
android:gravity="center"
android:hint="e.g. 0, 2, 3 "
android:inputType="textPersonName|number|numberDecimal" />
edit text for grade
EditText
android:id="#+id/txt_grade"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="6dp"
android:layout_weight="1"
android:background="#drawable/border"
android:ems="4"
android:gravity="center"
android:hint="e.g. A, B, C "
android:inputType="textCapCharacters"
android:paddingLeft="16dp" />
button
<Button
android:id="#+id/button2"
android:layout_marginBottom="6dp"
android:textAllCaps="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginTop="32dp"
android:onClick="calcGpa"
android:text="get gpa"
android:textAppearance="#style/Base.TextAppearance.AppCompat.Large"/>
here is my java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLayout = (LinearLayout) findViewById(R.id.linearLayout);
mEditCreditText = (EditText) findViewById(R.id.txt_credits);
mEditGradeText = (EditText) findViewById(R.id.txt_grade);
mButton = (Button) findViewById(R.id.button2);
mButton.setOnClickListener(onClick());
}
private View.OnClickListener onClick() {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
allCredits.add(mEditCreditText);
allGrades.add(mEditGradeText);
}
};
}
public int pointPerSubj(int number,String grade) {
int point;
if (grade.equalsIgnoreCase("A"))
point = 5;
else if (grade.equalsIgnoreCase("B"))
point = 4;
else if (grade.equalsIgnoreCase("C"))
point = 3;
else if (grade.equalsIgnoreCase("D"))
point = 2;
else
point = 0;
int perSubjectPoint = number * point;
return perSubjectPoint;
}
public void calcGpa (View v) {
gpa = perSubjectPoint/totalCredits;
display(gpa);
}
// display method
private void display(int number) {
TextView gpaTextView = (TextView) findViewById(R.id.gpa_text_view);
gpaTextView.setText("" + (number));
}
}
I don't have enough reputation to comment, else I would have asked for more code in the comments.
Your onClickListener adds your EditTexts to what I'm assuming are ArrayLists of EditTexts: allCredits and allGrades
In the first place, if you meant to insert the text, then those should be ArrayLists of strings, and you should be doing:
allCredits.add(mEditCreditText.getText().toString());
allGrades.add(mEditGradeText.getText().toString());
Also, your code does not indicate where any of your methods calcGpa and pointPerSubj are called.
I believe you are simply not calling the required methods to display
anything.
When I click "present" button the "percentage" does not change while the entered values changes. After the first click, the value of the "percentage" changes. The same problem occur when I press the "missed" button. After the first click, when I pressed "present" button increment function works and for "missed" button decrement function works.
I want that when "button b" is pressed it calculates the "percentage". when a user press "present" it increases the values of both "e1 (attended) and e2 (total)" from the previous entered values and then calculates the "percentage". For "missed" button it increases the value of e2 only and then calculates the percentage.
EditText e1,e2;
Button b,save;
TextView t;
String attended,total,mysum;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e1=(EditText) findViewById(R.id.editTextN1);
e2=(EditText) findViewById(R.id.editTextN2);
b=(Button) findViewById(R.id.buttoncalcsum);
save= (Button) findViewById(R.id.save);
t=(TextView) findViewById(R.id.textViewresult);
SharedPreferences pre=getSharedPreferences("data",Context.MODE_PRIVATE);
e1.setText(pre.getString("attended", ""));
e2.setText(pre.getString("total", ""));
t.setText(pre.getString("mysum", ""));
b.setOnClickListener(new OnClick());
}
public class OnClick implements OnClickListener
{
#Override
public void onClick(View v)
{
double n1 = Integer.parseInt(e1.getText().toString());
e1.setBackgroundColor(Color.CYAN);
double n2 = Integer.parseInt(e2.getText().toString());
e2.setBackgroundColor(Color.BLUE);
double mysum;
mysum=(n1/n2)*100;
if(mysum>65)
{ t.setText(String.format("%.2f", mysum));
t.setBackgroundColor(Color.GREEN);}
else
{ t.setText(String.format("%.2f", mysum));
t.setBackgroundColor(Color.RED);}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void execute(View v) {
SharedPreferences prefre=getSharedPreferences("data",Context.MODE_PRIVATE);
Editor editor=prefre.edit();
editor.putString("attended", e1.getText().toString());
editor.putString("total", e2.getText().toString());
editor.putString("mysum", t.getText().toString());
editor.commit();
finish(); }
public void increment(View v) {
int t1 = Integer.parseInt(e1.getText().toString());
e1.setText(String.valueOf(t1+1));
int t2 = Integer.parseInt(e2.getText().toString());
e2.setText(String.valueOf(t2+1));
double mysum;
mysum=((double)t1/t2)*100;
if(mysum>65)
{ t.setText(String.format("%.2f", mysum));
t.setBackgroundColor(Color.GREEN);}
else
{ t.setText(String.format("%.2f", mysum));
t.setBackgroundColor(Color.RED);}
}
public void decrement(View v) {
int p1 = Integer.parseInt(e1.getText().toString());
int p2 = Integer.parseInt(e2.getText().toString());
e2.setText(String.valueOf(p2+1));
double mysum;
mysum=((double)p1/p2)*100;
if(mysum>65)
{ t.setText(String.format("%.2f", mysum));
t.setBackgroundColor(Color.GREEN);}
else
{ t.setText(String.format("%.2f", mysum));
t.setBackgroundColor(Color.RED);}
}
and here is the activity_main.xml file
<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:background="#drawable/bg"
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.counter.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="90dp"
android:text="ATTENDED" />
<EditText
android:id="#+id/editTextN1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView1"
android:layout_alignBottom="#+id/textView1"
android:layout_marginLeft="42dp"
android:layout_toRightOf="#+id/textView1"
android:ems="10"
android:inputType="number"
android:hint="ENTER VALUE HERE"
android:gravity="center"/>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editTextN1"
android:layout_marginTop="39dp"
android:layout_toLeftOf="#+id/editTextN1"
android:text="TOTAL" />
<EditText
android:id="#+id/editTextN2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView2"
android:layout_alignBottom="#+id/textView2"
android:layout_alignLeft="#+id/editTextN1"
android:layout_alignRight="#+id/editTextN1"
android:ems="10"
android:inputType="number"
android:hint="ENTER VALUE HERE"
android:gravity="center" />
<Button
android:id="#+id/save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/buttoncalcsum"
android:layout_alignParentBottom="true"
android:onClick="execute"
android:text="SAVE" />
<Button
android:id="#+id/btnatnd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/save"
android:layout_alignRight="#+id/editTextN2"
android:onClick="increment"
android:text="PRESENT" />
<Button
android:id="#+id/btnmiss"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/save"
android:layout_alignParentLeft="true"
android:onClick="decrement"
android:text="MISSED" />
<Button
android:id="#+id/buttoncalcsum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/btnmiss"
android:text="CALCULATE" />
<TextView
android:id="#+id/textViewresult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/buttoncalcsum"
android:layout_marginTop="46dp"
android:layout_toLeftOf="#+id/btnatnd"
android:text="PERCENTAGE"
android:textAppearance="?android:attr/textAppearanceLarge" />
In increment()/decrement() function you update the values of Attended/Total TextViews, but you are then calculating the sum from old values.
Try to first update the values, e.g.:
public void increment(View v) {
...
int t1 = Integer.parseInt(e1.getText().toString());
e1.setText(String.valueOf(t1+1));
int t2 = Integer.parseInt(e2.getText().toString());
e2.setText(String.valueOf(t2+1));
t1++; t2++; // updating values here
....
mysum=((double)t1/t2)*100;
....
}
As far as I am understanding, you have not imported Buttons btnatnd and btnmiss. Also in the functions of increment() and decrement(), you are setting the text of TextView such that t1, t2 are increasing and p2 is decreasing. However the values of t1, t2 and p2 remain unchanged.
You should also use t1+=1;, t2+=1; and p2-=1;
Hope this helps !
AS Far as I understood , I think you want to calculate percentage , and sum and other functions and you are not getting the updated answer as you are using the Shared preferences.
So in this case I would suggest you two following methods:
1: When You calculate the percentage or any other thing (I am supposing that you are well in calculations and calculating it with any mistake) . You should make two different methods One for saving calculations in the shared preferences and the other to retrieve the last result. So when you calculate first call the save method and then call the retrieve method to retrieve values in text fields or where ever you want
2:This is more efficient way. You can make the receiver for any change in the values of of preferences and it will notify as when they are changed , so its up to you where you use those updates.
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.