I have a problem with a TextView showing letters instead of numbers.
I am trying to make a converter app.
Here is my code:
package com.rickhuisman.converter;
import android.icu.text.DecimalFormat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
public class LengthActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_length);
}
public void onClickConvertLength(View view) {
// variables
Spinner spinner1 = (Spinner)findViewById(R.id.spinner1Length);
Spinner spinner2 = (Spinner)findViewById(R.id.spinner2Length);
Button button = (Button)findViewById(R.id.convertButtonLength);
// spinner 1
String spinner1Value = String.valueOf(spinner1.getSelectedItem());
// spinner 2
String spinner2Value = String.valueOf(spinner2.getSelectedItem());
EditText inputChecker = (EditText)findViewById(R.id.InputLength);
TextView showText = (TextView)findViewById(R.id.showTextLength);
String inputCheckerText = inputChecker.getText().toString();
EditText input = (EditText)findViewById(R.id.InputLength);
// If input == 0
if(inputCheckerText.equals("")) {
inputCheckerLength();
}
// Millimeters && Millimeters
else if(spinner1Value.equals("Millimeters") && spinner2Value.equals("Millimeters")) {
// Get the input
Double formule = new Double(input.getText().toString());
methodLength(formule);
}
// Millimeters && Centimeters
else if(spinner1Value.equals("Millimeters") && spinner2Value.equals("Centimeters")) {
// Get the input
Double formule = new Double(input.getText().toString());
methodLength(formule);
}
}
// If the input == 0
public void inputCheckerLength() {
TextView showText = (TextView)findViewById(R.id.showTextLength);
CharSequence toastText = "Nothing to convert!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(this, toastText, duration);
toast.show();
}
// The method
public void methodLength(double formule) {
TextView showText = (TextView)findViewById(R.id.showTextLength);
showText.setText(Double.valueOf(formule).toString());
}
}
image of the code: Code
The problem is that if I put to many numbers in the EditText the TextView will show letters, is there a way I can make the TextView show the whole number and not letters?
Image of the problem:Image
Sorry for the bad English and thank you!
The problem is that you are using the Double.toString() method to output your double value, which uses the scientific notation format.
If you want to display the plain number you can use String.format() instead:
showText.setText(String.format("%.0f", formule));
In case you want to show decimals you can use e.g. %.2f for two decimals instead of %.0f.
Related
I am new to Android programming and tried to create a small App. I have a MainClass with one EditText and one TextField. EditText is for users to type in a number and the TextField shows the value of the input when clicking on the first button. The second button is for switching to the other class (MainClass2). Now i want to show the input number from EditText (that I defined as "number") in the next class MainClass2 in an empty TextField. I implemented an OnClickListener for the two different buttons mentioned in the MainClass (first screen). Since I only defined the input variable "number" when clicking the first button (cause "number" is then shown in the TextField as mentioned because it is only created via EditText when clicking the first button), "number" is not defined in the code of clicking the second button. Therefore I cant hand it over to the MainClass2 via Intent. Do you have any solutions for this? Thank you in advance. These are the codes for my Classes:
package com.example.teilnehmeranzahl;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
Button button2 = findViewById(R.id.button2);
Button one = (Button) findViewById(R.id.button);
one.setOnClickListener(this); // calling onClick() method
Button two = (Button) findViewById(R.id.button2);
two.setOnClickListener(this);
}
public void onClick(View v) {
// default method for handling onClick Events..
switch (v.getId()) {
case R.id.button:
EditText editText2 = findViewById(R.id.editText2);
String name2=editText2.getText().toString();
int number=Integer.parseInt(name2);
TextView textView = findViewById(R.id.textView);
textView.setText(String.valueOf(number));
Random randomizer = new Random();
int name = randomizer.nextInt(number+1);
TextView textView2 = findViewById(R.id.textView2);
if (name == 1 ) {
textView2.setText("Player 1");
}
if (name == 2 ) {
textView2.setText("Player 2");
}
break;
case R.id.button2:
Intent intent = new Intent(MainActivity.this,MainActivity2.class);
intent.putExtra("number",number); //here is the error cause number is not
defined, although it is..
startActivity(intent);
break;
default:
break;
}
}
}
And this is the code for MainClass2:
package com.example.teilnehmeranzahl;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity2 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
TextView textView3 = findViewById(R.id.textView3);
Intent intent = getIntent();
String number = intent.getStringExtra("number");
textView3.setText(number);
}
}
In case R.id.button2: you have not set the value of number. So it will give number undefined error. To solve this issue either you have to initialize number globally or get the value of number in case R.id.button2: also. Like
case R.id.button2:
EditText editText2 = findViewById(R.id.editText2);
String name2=editText2.getText().toString();
int number=Integer.parseInt(name2);
Intent intent =
new Intent(MainActivity.this,MainActivity2.class);
intent.putExtra("number",number);
startActivity(intent);
break;
I new. I have 2 editText and 1 TextView, 1 button. I want to sum from 2 input. Its success if I input all editText. But if I didn't input, the aplication stopped.
package panda.c;
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;
public class calculate extends Activity implements OnClickListener {
/** Called when the activity is first created. */
EditText input1,input2;
Button sum;
TextView total;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calcu);
input1 = (EditText) findViewById(R.id.input1);
input2 = (EditText) findViewById(R.id.input2);
total = (EditText) findViewById(R.id.total);
sum = (Button) findViewById(R.id.sum);
sum.setOnClickListener(this);
}
public void onClick(View v) {
int inputt1 = Integer.parseInt(input1.getText().toString());
int inputt2 = Integer.parseInt(input2.getText().toString());
switch (v.getId()) {
case R.id.sum:
sum.setText(Integer.toString(inputt1+inputt2));
break;
default:
break;
}}}
I didn't input anything. I just clicked sum, and then the program stopped. But if I input all editText, I clicked sum, Its work. why? I want if I do not input, and click sum, the application still run.
It's because if a field is left blank, Integer.parseInt() will fail. You should set a default value of 0 if the field is left blank so it won't force close.
Here's a simple solution to check if it's empty and use 0 as default:
int inputt1 = input1.getText().toString().equals("") ? 0 : Integer.parseInt(input1.getText().toString());
int inputt2 = input2.getText().toString().equals("") ? 0 : Integer.parseInt(input2.getText().toString());
Also, set android:inputType="number" to your EditText so you it will restrict input to numbers only.
Edit: Updated code to make it compatible to all API levels.
It's called a NullPointerException. You're trying to parse null to integer. You need to enclose the parsing statements in a try block and catch the NullPointerException and set some default value to inputt1 and inputt2 or notify the user to put some value with a Toast.
Correction
It's not a NullPointerException it's a NumberFormatException.
This is because you are using Integer.parseInt() and parsing "" inside it. This will definetly give you NumberFormat Exception.
Try this...
if(!(input1.getText().toString().trim().equals(""))){
inputt1 = Integer.parseInt(input1.getText().toString());
}
same for the other input as well..
Hope this helps,..
The code fragment in you OnClick() method could be the following:
int inputt1 = 0;
int inputt2 = 0;
try {
inputt1 = Integer.parseInt(input1.getText().toString());
inputt2 = Integer.parseInt(input2.getText().toString());
}
catch (NumberFormatException e) {
//notify the user here somehow or just leave empty
//or just return, if you don't want to sum default values
}
Well... here's a problem it looks like I'm not the first to experience looking through other questions, however I can't find one that's Android-specific (others are C++ or straight java with different scenarios).
I have a calculator that determines your fuel mileage needs with given user inputs. The thing I'm adding now is a "burnoff" aspect where you can calculate the weight lost over the course of the race. Before adding the weight/burnoff element, everything worked fine.
Now, everything calculates normally except the weight on the first click.
On the second click (and subsequent clicks) it calculates properly. I suspect it has something to do with the switch statement and its location, but I could be wrong.... and even if I'm not, I'm not sure how to change it.
Looking for help on getting it all functioning properly on the first click. Thanks!
EDIT: The non-exception Toast text I put in as a debugger to determine if it was a math issue or what in the code. It pops up with "0.0" on the first click, then either "6.2" or "6.6" on subsequent clicks.
package com.tomcat.performance;
import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;
public class Fuelsimple extends Activity implements OnCheckedChangeListener{
double fuelweight;
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
switch (checkedId){
case R.id.rbMethanol:
fuelweight = 6.6;
break;
case R.id.rbGasoline:
fuelweight = 6.2;
break;}
}
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.fuelsimple);
RadioGroup rgFuelType = ((RadioGroup) findViewById (R.id.rgFuelType));
rgFuelType.setOnCheckedChangeListener(this);
RadioButton rbMethanol = ((RadioButton) findViewById(R.id.rbMethanol));
RadioButton rbGasoline = ((RadioButton) findViewById(R.id.rbGasoline));
Button gen = ((Button) findViewById(R.id.submit));
gen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
EditText fuelUsed, pracLaps, featureLaps;
pracLaps = ((EditText) findViewById(R.id.pracLaps));
fuelUsed = ((EditText) findViewById(R.id.fuelUsed));
featureLaps = ((EditText) findViewById(R.id.featureLaps));
TextView textLPGValue, textFuelNeededValue, textBurnoffValue;
try{
double pracLapsVar = Double.parseDouble(pracLaps.getText().toString());
double fuelUsedVar = Double.parseDouble(fuelUsed.getText().toString());
double featureLapsVar = Double.parseDouble(featureLaps.getText().toString());
double efficiency = (pracLapsVar / fuelUsedVar);
double fuelNeeded = (featureLapsVar / efficiency);
double burnoff = (1.05 * (fuelNeeded * fuelweight));
Toast andJelly = Toast.makeText(Fuelsimple.this, String.valueOf(fuelweight), Toast.LENGTH_LONG);
andJelly.show();
textLPGValue = ((TextView) findViewById(R.id.textLPGValue));
textFuelNeededValue = ((TextView) findViewById(R.id.textFuelNeededValue));
textBurnoffValue = ((TextView) findViewById(R.id.textBurnoffValue));
textLPGValue.setText(String.valueOf(String.format("%.3f", efficiency)) + " laps per gallon");
textFuelNeededValue.setText(String.valueOf(String.format("%.3f", fuelNeeded)) + " gallons");
textBurnoffValue.setText(String.valueOf(String.format("%.2f", burnoff)) + " pounds");
} catch (NumberFormatException e) {Toast andEggs = Toast.makeText(Fuelsimple.this, "Please complete all fields and enter your fuel & lap info in decimals or whole numbers.", Toast.LENGTH_LONG); andEggs.show();}
catch (NullPointerException n) {Toast andEggs = Toast.makeText(Fuelsimple.this, "Please enter ALL lap and fuel data.", Toast.LENGTH_LONG);
andEggs.show();}
}}
);
}
public void onClick(View v) {
}
}
As far as I can tell, your variable fuelWeight is never initialized until a radio button is pressed. The simplest way to fix this would be to call setChecked(true) on either rbmethanol or rbGasoline after setting the listener, maybe right below where you initialize those variables. Doing it after setting the listener is important, because you want the switch statement to be resolved. Right now, before you press a radio button, fuelWeight, as with all numeric primitive data types, will be initialized to 0. This is probably the reason your first calculations are wrong.
You can also have a look at CheckChangeListener.It is called whenever the check state changes.
cbSave.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int visibility = isChecked ? View.VISIBLE : View.GONE;
findViewById(R.id.nameInstructions).setVisibility(visibility);
findViewById(R.id.name).setVisibility(visibility);
}
Describing the functionality of my application: I have put in a Relative Layout a TextView, an EditText and a button. All I am trying to do is: when the user writes something in the EditText and push the button, then the content of the EditText is appeared in the TextView(just like a chat-virtual chat). Everything works perfectly, but when the EditText is empty,and the button get pushed, an empty line is appeared in the TextView(and i don't want to..). Although I've tried to solve it using an if the empty line is still appearing in the TextView. I would be really greatfull, if you could help!!! Than you in advance!
Here is my code:
package teiath.android.appliacation;
import android.app.Activity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class M_chat extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/**Code for the scroll bars in the TextView. */
final TextView tv = (TextView)findViewById(R.id.TEXT_VIEW);
tv.setMovementMethod(new ScrollingMovementMethod());//for the scroll bars
/** Code for the scroll bars in the EditText. */
final EditText wr = (EditText)findViewById(R.id.EDIT_TEXT);
wr.setMovementMethod(new ScrollingMovementMethod());//for the scroll bars
final Button button = (Button) findViewById(R.id.btn1);//find the button by id in main.xml
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
String wrcontent = wr.getText().toString();//gets the text of the EditText and put it in "tvcontent" variable.
String tvcontent = tv.getText().toString();//gets the text of the textView and put it in "tvcontent" variable.
if (wrcontent!="")//if the EditText is not empty
{
//check if the TextView is empty or not
if (tvcontent!="")//If it is not empty...
{
tv.setText(tvcontent + "\n" + wrcontent);//add its current(TextView's text) text, new line and the text of the EditText as the new text of TextView.
//tv.setVisibility(0);//makes visible the textView with the cloud1.png background
wr.setText("");//set the text of the Edit Text as empty
//wrcontent = "";
}
else//if the TextView is empty...
{
tv.setText(wrcontent);//add the text of the editText as the new text of the TextView
wr.setText("");
}
}
/**if (wrcontent=="")
{
}*/
//finish();
}
});
}
}
Don't use !="" for String comparison. To check for empty text, use something like
if ( wrcontent != null && wrcontent.trim().length() == 0 ) {
Better yet, include Guava libraries in your code.
I want to program a function that the toast exist when there is nothing
in the "edittext" box (id / password), but it dosen't work.
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.content.Intent;
import android.widget.EditText;
import android.widget.Toast;
import android.view.View.OnClickListener;
import android.text.Editable;
public class Test extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button1 = (Button) findViewById(R.id.button1);
EditText id = (EditText) findViewById(R.id.id);
EditText pwd = (EditText) findViewById(R.id.pwd);
Editable Str_id;
Editable Str_pwd;
Str_id = id.getText();
Str_pwd = pwd.getText();
button1.setOnClickListener(new Button.OnClickListener()
{
public void onClick(View v){
if(Str_id==null || Str_pwd == null){
Toast.makeText(Test.this, "Please Enter User ID / Password", Toast.LENGTH_LONG).show();
}
});
}
}
move the following lines inside onClick and try:
Str_id = id.getText();
Str_pwd = pwd.getText();
EDIT: Move
Editable Str_id;
Editable Str_pwd;
Str_id = id.getText();
Str_pwd = pwd.getText();
inside onClick().
I do not recommend toasting a message that a field is required. You're better off just giving the EditText focus, this focus tells the user that this field is required. Its less information on the screen and its subtle, which is important. You don't want to disturb the user too much.
The idea is...
When the submit button is clicked, check the EditTexts if any of them are empty, notify the user through requesting focus, also make sure your UI tells them before hand that the fields required. The hint of the EditText works well for this.