Change value of TextView in Android - java

I would like to change a TextView as a user adds things to a cart. The initial value is 0.00 and as the user adds items, this is added to the value. I have an AlertDialog that pops up when clicking a button that allows the user to choose an item.
My issue is a java.lang.StringToReal.invalidReal error. I think that I may not be getting the value of the TextVeiw properly but am not totally sure.
Thanks to anyone looking at this.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(R.string.pickItem);
builder.setItems(R.array.items, new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
CartItems ci = new CartItems();
ci.setItem(which);
ci.setPrice(which);
cart.add(ci);
totalPriceTV = (TextView)findViewById(R.id.textView2);
double totalPrice = Double.parseDouble(totalPriceTV.toString());
totalPrice += ci.getPrice();
String newTotal = new Double(totalPrice).toString();
totalPriceTV.setText(newTotal);
}
});
builder.create();
builder.show();
}
});
}

In this line
double totalPrice = Double.parseDouble(totalPriceTV.toString());
Change totalPriceTV.toString() to totalPriceTV.getText().toString() and try again.

In order to change the text of a TextView in Android just use the ordinary geters and setters:
TextView.getText();
TextView.setText("text");
Since you deal with numbers i suggest you to use DecimalFormat when parsing a double to string. You can easily define the format of the number (i.e the number of digits after comma or the separator characters)
DecimalFormat df = new DecimalFormat("###,###.00");
String price = df.parse(someDouble);
textView.setText(price);
For these numbers: 234123.2341234 12.341123 the DecimalFormat would give you the following result:
234,123.23 and 12.34

Taken from page: http://developer.android.com/reference/android/view/View.html#toString()
Added in API level 1
Returns a string containing a concise, human-readable description of this object. Subclasses are encouraged to override this method and provide an implementation that takes into account the object's type and data. The default implementation is equivalent to the following expression:
getClass().getName() + '#' + Integer.toHexString(hashCode())
As a result you should use getText();
ie:
totalPriceTV.getText()

Just use totalPriceTV.setText(""+totalPrice);
or
totalPriceTV.setText(String.valueOf(totalPrice));

Related

Android Java Decimal Format - Zero is hidden after decimal point

In my app, i want to be able to format numbers to string (with commas) in a TextView e.g 123456.000 to 123,456.000. But the problem is when i type zero (0) as the last number after the decimal point, it shows nothing until i type another number. For example, if i type 123456.000, i get 123,456. The zeros doesn't show until i type another number like "1" then i get 123,456.0001. Please how do i make zeros show as last number after decimal point? Below are some sample codes.
I apologise for the clumsiness of the code. I manually typed it with my phone.
TextView txtView;
boolean NumberClicked = false;
String number = "";
// format pattern
DecimalFormat formatter = new DecimalFormat("#,###.#########");
// input dot (decimal point)
dot.setOnClickListener (new View.OnClickLstener() {
public void onClick(View view) {
if (!txtView.getText.toString.contains(".") {
input(".");}}});
// input zero (0)
zero.setOnClickListener (new View.OnClickLstener() {
public void onClick(View view) {
input("0");
}});
// input one (1)
one.setOnClickListener (new
View.OnClickLstener() {
public void onClick(View view) {
input("1");}});
// input method
public void input (String view) {
if (!numberClicked) {
number = view;
numberClicked = true;
} else {
number = number + view;
}
// print the entered numbers to
//the TextView after formatting
if (!number.endsWith(".")) { txtView.setText(formatter.format(Double.parseDouble(number)));}}
enter code here
You may try this code snippet:
DecimalFormat df = new DecimalFormat("#,##0.0#");
df.setMinimumFractionDigits(3);
String value = df.format(123456.000);
Output: 123,456.000
For more info pls click here.
Try with:
String.format("%,.03f", 123456.000)

How Delete Last number of a float in android (java)

I am building a calculator app and everything is working properly but I don't know the code for backspace.
public class MainActivity extends AppCompatActivity {
// UI Elements
private TextView num_input;
private TextView num_input;
private ImageButton num_backspace;
private float input, input2 ;
boolean Addition, Subtract, Multiplication, Division, mRemainder, decimal, add_sub;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initializing
num_input = findViewById(R.id.num_input);
num_output = findViewById(R.id.num_output);
num_backspace = findViewById(R.id.num_backspace);
num_backspace.setOnClickListener(new View.OnClickListener() {
#Override
//TODO: the backslash code goes here.
});
}
}
I tried doing this👇🏻
num_backspace.setOnClickListener(new View.OnClickListener() {
#Override
input = Float.parseFloat(num_input.getText() + "");
String sample_input = Float.toString(input);
sample_input = sample_input.substring(0,sample_input.length() - 1);
});
Some help would be great!
thanks in advance
It's better to store input as a String, not float. Because before you start doing mathematical calculations it's just a String input, and "backspace" means basically removing one character, it's not a mathematical operation. So, provided input is a String, backspace code will be:
input = input(0, input.length() - 1);
num_input.setText(input);
And before doing calculations convert your String input into float via
float operand = Float.parseFloat(input);
Put this code inside your setOnClickListener
String value = num_input.getText().toString();
if (value != null && value.length() > 0 ) {
value = value.substring(0, value.length() - 1);
}
num_input.setText(value);
How this is usually done is getting the current value (entered number) in the TextView, remove the last character from the string and writing it back to the TextView.

How do simple calculating with multiplication only

i have problem with my simple calculate with only multiplication from the edittext where the user input the numbers. When user click result button, numbers that user input from edittext do multiplication and show result in textview.
input = (EditText)findViewById(R.id.input);
output1 = (TextView)findViewById(R.id.output_one);
output2 = (TextView)findViewById(R.id.output_two);
output3 = (TextView)findViewById(R.id.output_three);
result = (Button)findViewById(R.id.result);
result.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
output1.setText(input.getText()*"2");
output2.setText(input.getText()*"3");
output3.setText(input.getText()*"4");
}
}
(input.getText()*"") showing red underline. It said 'Operator * cannot be applied to android.text.editable, java.lang.String' .
Anyone can fill my code? I m beginners :)
String can not be calculated, you need to convert into numbers in the operation, you can try:
Integer.valueOf ("")
make sure the user inputs a number, use
android:inputType="number"
in the EditText attributes.
input = (EditText)findViewById(R.id.input);
output1 = (TextView)findViewById(R.id.output_one);
output2 = (TextView)findViewById(R.id.output_two);
output3 = (TextView)findViewById(R.id.output_three);
result = (Button)findViewById(R.id.result);
result.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// storing the EditText value in a variable.
// do it in the onClick method only.
int inputVal = Integer.parseInt(input.getText().toString());
output1.setText(inputVal * 2);
output2.setText(inputVal * 3);
output3.setText(inputVal * 4);
}
}
input => EditText
When you use input.getText() you get object of Editable class.
If you want to get its value, you have to convert Editable to String, using input.getText().toString().
Now you want to multiply the value, So you have to convert String to Integer(or relevant dataType), by Integer.parseInt(input.getText().toString()) and then multiply with your value.
Now you want to assign this updated value to TextView, use String.valueOf().
So finally your code should be:
int inputVal = Integer.parseInt(input.getText().toString());
output1.setText(String.valueOf(inputVal * 2));
output2.setText(String.valueOf(inputVal * 3));
output3.setText(String.valueOf(inputVal * 4));
use this
output1.setText(Integer.valueOf(input.getText().trim())*Integer.valueOf("2"));
output2.setText(Integer.valueOf(input.getText().trim())*Integer.valueOf("3"));
output3.setText(Integer.valueOf(input.getText().trim())*Integer.valueOf("4"));
You are trying to multiply strings. You should transform the string into numbers before multipling them.
result.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try{
int inputInt = Integer.parseInt(input.getText());
int inputInt_times2 = 2*inputInt;
int inputInt_times3 = 3*inputInt;
int inputInt_times4 = 4*inputInt;
output1.setText(inputInt_times2+"");
output2.setText(inputInt_times3+"");
output3.setText(inputInt_times4+"");
}catch(Exception e){
//handle the exception here
}
}
}
the (+"") that I added in the setText was to transform the int to String again.

Parsing issue android widget to int

Need help parsing, I have tried "porting" my dice roller project to Android using Android Studio, I have most of the controller values replaced with their android widget counterparts, one problem, I am not sure how to properly parse widget values to an Int. I have marked them with aligned left comments below.
modifier is an EditText
result is a TextView
I have tried many combinations and this is the most recent.
The one that worked when it was pure java was .getValue().toString().trim() but I cannot use .getValue why is this?
public void onStart()
{
super.onStart();
percentile.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick (View v)
{
{
//issue is here
int total = Nat20_core.roll10(cumulative.isChecked(),
Integer.parseInt (String.valueOf(modifier)),
Integer.parseInt(String.valueOf(result)));
//end issue
result.setText(String.valueOf(total));
}
}
});
}
I have also tried this in a previous program as
set
This is because there is no .getValue() method for EditText and TextView widget.
For EditText, you can use getText() which returns an Editable. So, you need to get the string from it using toString(). So, you will need to use:
modifier.getText().toString();
For TextView, you can use getText() which returns a CharSequence. You also need to get the string from it using toString(). So, you can use the above line too:
result.getText().toString();
Now, you need to convert the following code:
int total = Nat20_core.roll10(cumulative.isChecked(),
Integer.parseInt (String.valueOf(modifier)),
Integer.parseInt(String.valueOf(result)));
to:
int total = Nat20_core.roll10(cumulative.isChecked(),
Integer.parseInt (modifier.getText().toString()),
Integer.parseInt(result.getText().toString()));
In EditText and TextView, the "value" is "text":
Integer.parseInt(modifier.getText().toString())

how do you call a value entered in a UI to your java class?

Making a simple app for my android.
in my xml interface there is a text box in which the user will input a number (for example: 10). the id of this text box is "input1"
how do I call the value of input1 in java and then perform a calculation on it?
For example...
suppose input1 = x
x + 5 or x*2
and for that matter, how do I have the resulting value appear as constantly updated text output in a specified place on the UI?
In the Activity where you are using this layout XML, you would do this:
private EditText input;
private EditText result;
public void onCreate(Bundle b) {
setContentView(R.layout.my_activity);
// Extract the text fields from the XML layout
input = (EditText) findById(R.id.input1);
result = (EditText) findById(R.id.result);
// Perform calculation when input text changes
input.addKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keycode, KeyEvent keyevent) {
if (keyevent.getAction() == KeyEvent.ACTION_UP) {
doCalculation();
}
return false;
}
});
}
private void doCalculation() {
// Get entered input value
String strValue = input.getText().toString;
// Perform a hard-coded calculation
int result = Integer.parseInt(strValue) * 2;
// Update the UI with the result
result.setText("Result: "+ result);
}
Note that the above includes no error handling: it assumes that you have restricted the input1 text field to allow the input of integer numbers only.
In your XML you can also set android:inputType="number" to only allow numbers as entries.

Categories

Resources