I have quite a simple application. However, after I clik on the button, app crashes. Tried to debug it and the problem seems to be in first 3 row of the onClick method. Once I tried to get there values manually, not via those edit boxes, everything went smoothly. Any ideas please?
public class MainActivity extends AppCompatActivity {
EditText editText_pocetKM;
EditText editText_spotreba;
EditText editText_cenaPHM;
TextView textView_spotrebaO;
TextView textView_cenaO;
DecimalFormat df = new DecimalFormat("0.00##");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText_pocetKM = (EditText) findViewById(R.id.editText1_pocetKM);
editText_spotreba = (EditText) findViewById(R.id.editText_Spotreba);
editText_cenaPHM = (EditText) findViewById(R.id.editText1_cenaPHM);
textView_spotrebaO = (TextView) findViewById(R.id.textView_spotrebaO);
textView_cenaO = (TextView) findViewById(R.id.textView_cenaO);
}
public void onClick(View v) {
Double pocetKm = Double.parseDouble(editText_pocetKM.getText().toString());
Double spotreba = Double.parseDouble(editText_spotreba.getText().toString());
Double cenaPHM = Double.parseDouble(editText_cenaPHM.getText().toString());
Double spotrebaO = spotreba * pocetKm / 100;
Double cenaO = spotrebaO * cenaPHM;
textView_cenaO.setText("Cena za spotřebované palivo bude "+ df.format(cenaO) + " Kč");
textView_spotrebaO.setText("Celkem bude spotřebováno "+ df.format(spotrebaO) + " litrů paliva");
}
}
You didn't provide the logcat of your crash report. If the logcat was provided we could be certain of your exact problem. But anyway, as you've got rid of your crash by removing the first three lines of your onClick function, I suppose you're setting invalid inputs in your EditText.
You're parsing the text entered in the EditText to double which will fail if the input is not a valid double string. For example, it'll parse 11.01 fine when it'll throw an exception while parsing Hello.
So to check if the application is crashing for a parsing error, you might consider surrounding them with a try/catch block like this.
try {
Double pocetKm = Double.parseDouble(editText_pocetKM.getText().toString());
Double spotreba = Double.parseDouble(editText_spotreba.getText().toString());
Double cenaPHM = Double.parseDouble(editText_cenaPHM.getText().toString());
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "Parsing error", Toast.LENGTH_LONG).show();
}
Related
I'm working on my first project in Android Studio and I got stuck in "how to display different variables in one textView". to be more clear I'm working on an app that requires the user to enter the gender. each gender has its own calculation method. so I want to display the result calculation the user do in the main interface and In one TextView. I've tried many times to do it but the result is "0.0"
I added another textView and assigned each calculation method to one textview I was able to display the two results.
public class Main_Interface extends AppCompatActivity implements View.OnClickListener{
private TextView results;
//private TextView fResults;//this is the second textview that I created.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main__interface);
results = (TextView)findViewById(R.id.results);
if(results.getText().toString().equals("0.0")) {
results.setVisibility(View.INVISIBLE);
}
//fResults = (TextView)findViewById(R.id.fResults);
// if(fResults.getText().toString().equals("0.0")){
// fResults.setVisibility(View.INVISIBLE );
// }
calculateMale();
calculateFemale();
}
public void calculateMale(){
SharedPreferences s = getSharedPreferences("data", Context.MODE_PRIVATE);
double weight = s.getFloat("weight",0.0f);
double height = s.getFloat("height",0.0f);
int age = s.getInt("theDate", 0);
double results2 = 66+(13.7*weight)+(5*height)-(6.8*age);
results.setText(""+results2);
public void calculateFemale(){
SharedPreferences s1 = getSharedPreferences("data", Context.MODE_PRIVATE);
double fWeight = s1.getFloat("fWeight",0.0f);
double fHeight = s1.getFloat("fHeight",0.0f);
int Fage = s1.getInt("theDate", 0);
double results3 = 655 + (9.6 * fWeight) + (1.8 * fHeight) - (4.7 *Fage)
;
fResults.setText(""+results3);
SharedPreferences.Editor editor = s1.edit();
editor.putFloat("results", (float) results3);
editor.commit();
}
}
displaying the calculation in one textview.
You Are calling these two methods before checking these two methods
calculateMale();
calculateFemale();
in onCreate() {
//do this
calculateMale();
calculateFemale();
//Then check the result to make results visible or invisible.
results = (TextView)findViewById(R.id.results);
if(results.getText().toString().equals("0.0")) {
results.setVisibility(View.INVISIBLE);
}
}
You just need to make it clear when the function is being called. What actually happening here is you are checking textView's value even before calculating your required values. So it is throwing 0.0.
Simply call calculateMale(); calculateFemale(); before checking textView's value.
You are printing results before calling the two function. Try this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main__interface);
results = (TextView)findViewById(R.id.results);
calculateMale();
calculateFemale();
if(results.getText().toString().equals("0.0")) {
results.setVisibility(View.INVISIBLE);
}
}
Return the result from calculateMale() and calculateFemale() methods:
String calculateMale = calculateMale();
String calculateFemale = calculateFemale();
results = (TextView)findViewById(R.id.results);
String result = calculateMale.concat(calculateFemale);
if (result.length() >= 0) {
results.setText(result);
} else {
results.setVisibility(View.INVISIBLE);
}
This question already has answers here:
java.lang.numberformatexception: invalid double: " "
(6 answers)
Closed 8 years ago.
When I try running my Android App, I get an error saying: java.lang.NumberFormatException: Invalid double: "". This is my code:
public class MainActivity extends Activity {
double score;
EditText gpa;
EditText sat;
EditText act;
Button calc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gpa = (EditText) findViewById(R.id.gpa);
String gpaString = gpa.getText().toString();
final double gpaDouble = Double.parseDouble(gpaString);
sat = (EditText) findViewById(R.id.sat);
String satString = sat.getText().toString();
final int satInt = Integer.parseInt(satString);
act = (EditText) findViewById(R.id.act);
String actString = act.getText().toString();
final int actInt = Integer.parseInt(actString);
calc = (Button) findViewById(R.id.calc);
calc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(actInt/36>satInt/2400){
score = (0.6*gpaDouble*25)+(0.4*(actInt/36)*100);
}else{
score = (0.6*gpaDouble*25)+(0.4*(satInt/2400)*100);
}
}
});
}
}
I essentially want to get numbers from three EditTexts, make one of them into a double and the other two into ints. Then I would use these variables to set the value for another double variable. I am not getting errors before I run the app. I feel that when the EditText field is blank, it will not parse correctly, but I am unsure how to solve this. What is the problem?
Invalid double: "".
you are parsing onCreate() value without putting any default value so the exception
final double gpaDouble = Double.parseDouble(gpaString);
because "" (empty String is not Double)
I have a pretty basic EditText that I pull data from as a double via a button.
It's value does not appear to change - if I use android:text="2", and pull the value, it comes up as 2. But if I leave it blank, type in it, and try to pull the value, it comes up blank or null.
The Problem: (since I suppose it hasn't been clear enough) when I launch my app, type "3" into the EditText, and press my button that calls String b = input.getText().toString(); and outputs b in a Toast and mathematical equation, it is blank and the equation calls an invalid input (my try/catch). The EditText supposedly never has a value.
<EditText
android:id="#+id/input"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_weight=".3"
android:hint="-->"
android:inputType="number"
android:maxLines="1"
android:textColor="#ffffff" />
...
Spinner spinner1, spinner2; //class space
EditText res, input;
Button btnSubmit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setContentView(R.layout.fragment_math);
spinner1 = (Spinner)findViewById(R.id.unit_a);
spinner2 = (Spinner) findViewById(R.id.unit_b);
btnSubmit = (Button) findViewById(R.id.btnSubmit);
res = (EditText) findViewById(R.id.result);
input = (EditText) findViewById(R.id.input);
...
public void convert(View view) {
int operation = 0;
double cm = 0;
String a;
Toast.makeText(MainActivity.this, MainActivity.this.input.getText().toString(), Toast.LENGTH_LONG).show();
if(operation == 0) {
//CM TO IN
try {
cm = Double.parseDouble(MainActivity.this.input.getEditableText().toString());
}catch(NumberFormatException nfe) {
Toast.makeText(MainActivity.this, "Invalid input! (" + MainActivity.this.input.getText().toString() + ")", Toast.LENGTH_LONG).show();
}
a = Double.toString(cmToIn(cm));
res.setText(a + "dfsdf", TextView.BufferType.EDITABLE); //same as below
}else if(operation == 1) {
//etc.
}else {
res.setText("Something went wrong! :("); //temp, completely dysfunctional
}
}
Edit: I apologize, the Toast I had for a while was incorrect because I managed to Ctrl + Z back to a dumb mistake before copying. Sorry. Fixed. Problem still occuring though.
You must be calling method Convert (which is responsible for retrieving edittext text as I could see from code) in onClick of a button. (And not in onCreate)
Then this should work fine.
Toast.makeText(MainActivity.this, MainActivity.this.input.getText().toString(), Toast.LENGTH_LONG).show();
Hope it helps.
input.getEditableText() returns an Editable object.
Use input.getText().toString() to return a String for the Toast to display.
More info: https://developer.android.com/reference/android/widget/EditText.html
public class AndroidTranslate extends Activity {
EditText MyInputText;
Button MyTranslateButton;
TextView MyOutputText;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MyInputText = (EditText)findViewById(R.id.InputText);
MyTranslateButton = (Button)findViewById(R.id.TranslateButton);
MyOutputText = (TextView)findViewById(R.id.OutputText);
MyTranslateButton.setOnClickListener(MyTranslateButtonOnClickListener);
}
private Button.OnClickListener MyTranslateButtonOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String InputString;
String OutputString = null;
InputString = MyInputText.getText().toString();
try {
GoogleAPI.setHttpReferrer("http:\\www.google.com");
GoogleAPI.setKey(" API KEY");
OutputString = Translate.DEFAULT.execute(InputString,Language.ENGLISH, Language.HINDI);
} catch (Exception ex) {
ex.printStackTrace();
OutputString = "Error";
}
Typeface customF = Typeface.createFromAsset(getAssets(), "akshar.ttf");
//final TextView textV = (TextView) findViewById(...);
MyOutputText.setTypeface(customF);
MyOutputText.setText(OutputString);
}
};
}
this code is running but not showing proper output like
if my input is "aap kaise ho" it gives output = "आप कैसे हो "
BUT
wen i give input only "a" or "abc" then output should be "अ" or "अबक" but it is not showing output like this. for "a" it shows "एक"
can ane one please help to solve this issue
Thanks
It doesn't seem to be a Android or technical problem but rather the way google translate 'a':
http://translate.google.com/?hl=nl&tab=wT#en|hi|a
I think you are using translation API while trying to achieve transliteration in your code.
It won't show "अ" for "a" because in hindi "a" means "एक". The only way is to achieve this is multiple translation of a word but Right now there is no multiple translation support for a word in google translate api. You can achieve this by a web service which is currently used by google translate in web interface.
http://translate.google.com/translate_a/t?client=t&text=a&hl=en&sl=en&tl=hi&multires=1&otf=2&pc=0&sc=1
You may not receive desired output from this.
when clicking on the button it does nothing ,,,after testing I concluded the problem is with the equal method statment ,,,the whole issue is when comparing string array to string any solutions?
EditText coderead = (EditText)findViewById(R.id.editText1);
Button go = (Button)findViewById(R.id.button1);
final String mn=coderead.getText().toString();
final String code[] = {"m1","n2"};
final double pointx[] ={23.666666,65.22222};
final double pointy[] ={31.55555,29.665544};
go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent transfercode = new Intent(getApplicationContext(), FeenbezabtActivity.class);
for (int i=0; i<code.length; i++) {
if(code[i].equals(mn)) {
transfercode.putExtra("lat2", pointx[i]);
transfercode.putExtra("long", pointy[i]);
startActivity(transfercode);
}
else{Toast.makeText(getBaseContext(), "code not found", 5000);}
}
}
});
Your mn variable should be read after your button has been clicked.
Button go = (Button) findViewById(R.id.button1);
final String code[] = {"m1", "n2"};
final double pointx[] = {23.666666, 65.22222};
final double pointy[] = {31.55555, 29.665544};
go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent transfercode = new Intent(getApplicationContext(), FeenbezabtActivity.class);
// mn should be read after the button click!
EditText coderead = (EditText) findViewById(R.id.editText1);
final String mn = coderead.getText().toString();
for (int i = 0; i < code.length; i++) {
if (code[i].equals(mn)) {
transfercode.putExtra("lat2", pointx[i]);
transfercode.putExtra("long", pointy[i]);
startActivity(transfercode);
} else {
Toast.makeText(getBaseContext(), "code not found", 5000);
}
}
}
});
So if I understand your code correctly you are trying to respond to a button click and take the text that has been input and do something based on that?
You are setting the value of mn at the time you are creating the button, rather than when the button is pressed. At that time the text will be empty (or null). You should move the code to get the value of the entered text to within the onClickListener.
Should your "code not found" message happen outside the for loop?
What do you mean by nothing happens? Do you get a Toast message or not? Did you make sure that no error is being generated? If you are not getting the Toast Message and you have no errors, then make sure the intent is correct. I would recommend you debug the code from the line of Intent transfercode = new Intent(getApplicationContext(), FeenbezabtActivity.class);
Then, report what is happening back here.
Something I don't get. With these two lines:
final String mn=coderead.getText().toString();
final String code[] = {"m1","n2"};
Why don't you just compute the (final) index to code right then and there, vs waiting until onClick?