if statement problems in android - java

I have a method that checks for a null value from an editText on a click of a button like so:
public void myClickHandler09(View chv){
if (text9.equals("")){
text9.setText("0");
}else{
converter(text9);
}}
The
converter(text9);
method is as shown:
public void converter(View view){
switch (view.getId()) {
case R.id.Button09:
RadioButton RadioButtons = (RadioButton) findViewById (R.id.RadioButton901);
float inputValue = Float.parseFloat(text9.getText().toString());
if (RadioButtons.isChecked()) {
text9.setText(String
.valueOf(convertRadioButtons(inputValue)));
}
break;
}}
private double convertRadiobuttons(float inputValue){
return inputValue * 6.4516;
}
The method is larger but here i've only called one radiobutton to shorten it.
Right now though the if statement seems to do absolutely nothing and so non of the rest of the code works. If i remove the method and rename
converter(View view){
to
myClickHandler09(View view){
then the code works and until you enter a null value into the EditText (then it crashes)
What am I doing wrong exactly here?
NOTE: the method name "myClickHandler09" is linked to the button as android:onClick in the xml

You need to do if("".equals(text9.getText().toString())) { ...
The toString() is there because the TextView will return a CharSequence which may or may not be a String.
Right now you are comparing the TextView itself to "", and not the String it is showing.
Edit - As far as the crash goes, you also want to catch the NumberFormatException that Float.parseFloat() throws.
float inputValue = 1.0f; // some default value, in case the user input is bad.
try {
inputValue = Float.parseFloat(text9.getText().toString());
} catch (NumberFormatException e) {
// possibly display a red flag next to the field
}

Why not try
if ("".equals(text9.getText())) {
} else {
}
You essentially have to do a getText() from a TextView and not equals a String with a TextView.

One thing I don't understand with your code is that you call:
converter(text9);
passing in the EditText, but by replacing converter(View view) with the function name myClickHandler09 (like so):
myClickHandler09(View view) {
the button being pressed with call this function (if you defined it in the xml layout onClick paramter).
So to match this behaviour with your current code, try this out:
public void myClickHandler09(View btnView){
if (text9.equals("")){
text9.setText("0");
} else {
converter(btnView);
}
}
I may have missed the point of you're post, but I think that is part of your issue. Also in stead of .equals("") I prefer (text9.toString().length() > 0) just seems a bit more logical, but that's me being a bit pedantic.

Related

How Do I Update TextView Result On App Launch

I am pulling data from a Website to my application. I want the TextView to display the result I want from the website immediately as the user launches the app. However html codes make the result look weird some times and I am trying to correct it. I have the codes that will do what I am trying to do. I just can't figure out how to get it to do everything automatically at app launch. It needs to pull the code from the website and if it receives any special symbols within the string I want it to correct it as soon as the app launches. Here is an example...
TextView tv = (TextView) findViewbyId(R.id.my_textview_result);
tv.setText(resultFromWebsite);
The result it pulled: You u0026 Me Forever!
The result I want: You & Me Forever! My app should correct that.
Here is my correction code...
public void symbolTextFilter(TextView myTv) {
String getData = tv.getText().toString();
if (getData.contains("u0026") {
String replace = getData.replace("u0026", "&");
myTv.setText(replace);
}
Now on my onCreate Method
TextView tv = (TextView) findViewbyId(R.id.my_textview_result);
tv.setText(resultFromWebsite);
symbolTextFilter(tv);
It will not make that correction. It will if I put the symbolTextFilter(tv) in a onClickListener button though. I don't want to assign the correction in a button. I want it automatically. My guess is, everything that I have in the onCreate is happening too fast for corrections to be made. How do I fix that? Thanks in advance!
Try this:
tv.setText(symbolTextFilter(resultFromWebsite))
You should use the method symbolTextFilter to handle the string only:
public void symbolTextFilter(String input) {
if (input.contains("u0026") {
return input.replace("u0026", "&");
} else {
return input
}
Nevermind, I got it! I'm not sure where the "\" came from because it wasn't in the original string that it pulled before the correction. I fixed it with this...
public String symbolTextFilter(String input) {
if (input.contains("u0026") {
return input.replace("\\" + "u0026", "&");
} else {
return input
}

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())

Else If textfield (Android)

I am creating a else if statement for a textfield i have on my view, i am using this code right now. But i'm running into a few errors
private EditText editText;
editText = findViewById(R.id.your_custom_id);
//then something like this
Sting text = editText.getText();
if(text.equals("foo") {
// do something
else if(text.equals("bar") {
// do something else
} else {
// something else
}
The errors consist of "Can't resolve symbol for 'sting' or 'equals'. 'Unknown class "editText" in the 'editText = findViewbyid...'. And the last one is 'Else without if' on the "else if(text.equals("bar")" code. How can i resolve this?
See Sting text = editText.getText(); This is totally incorrect.
There is no such thing as Sting it's String.Equal method apply on object types and String is an Object.
Also you need to use toString().
Use String text = editText.getText().toString();
you need to use editText = (EditText)findViewById(R.id.your_custom_id);
instead of editText = findViewById(R.id.your_custom_id);.

EditText text cannot be converted to int as there is no text there

Basically I need to check that the user input from inputET (an EditText) is equal to the integer, correctAnswer. The problem I'm getting is that "" (which is the text in the EditText field) cannot be converted to an int. Is there any other ways of achieving this or catching the error, I've tried the following code which to my understanding asks if the string in the EditText is not equal to "". Am i going the right way about this or is there an easier way?
// check the input
if (inputET.getText().toString() != "") {
if (correctAnswer == Integer.parseInt(inputET.getText()
.toString())) {
inputET.setText("");
newSum();
}
}
if the user inputs the same int as the correctAnswer integer then the EditText text is reset to "".
Thanks for any help.
try this:
if (!inputET.getText().toString().equals("")) {
if (correctAnswer == Integer.parseInt(inputET.getText()
.toString())) {
inputET.setText("");
newSum();
}
}
Used .equals() method for String comparison.
Based on your requirement I think using TextUtil class will be right way to go for checking the edittext is empty or not.
if(!TextUtils.isEmpty( inputET.getText().toString())){
if (correctAnswer == Integer.parseInt(inputET.getText()
.toString())) {
inputET.setText("");
newSum();
}
}
rather tha doing if (inputET.getText().toString() != "") have a try with
if (!inputET.getText().toString().equals(""))
print the "inputET.getText().toString()" to console and see what it returns. I would hope you need to check the following
String str = inputET.getText().toString()
if (null!=str && str.trim().equals("")) {
if(inputET.getText().toString()!=null&&!(inputET.getText().toString().isEmpty())){
//code for mot null
}else{
//code for null
}

Android: How to check/uncheck a RadioButton inside a RadioGroup programmatically in Java

I have to activities, MainActivity and settingsActivity. Because of that I'm using the methods onPause and onResume in the settingsActivity. So that the things I have done in the settingsActivity are saved after switching to MainActivity and back again.
settingsActivity:
Here I have a TextView (called "settings2") as a kind of variable and my three RadioButtons (radio0, radio1 and radio2) which are inside a RadioGroup.
After switching to the MainActivity my programe puts "0" in a file (which is saved on the sdcard) if radio0 was last checked. But if radio1 was last checked, it puts 1 in that file. And if radio2 was last checked, it puts 2 in that file.
I used this in the method onPause.
Then in the method onResume I read the text of that file and put it in the TextView "settings2".
After this code (still in onResume) I want to check/uncheck my RadioButtons. So if the text of the TextView "settings2" is "0" the RadioButton "radio0" shall be checked and the others not. If the text of this TextView is "1" the RadioButton "radio1" shall be checked and the others not. And if the text of this TextView is "2" the RadioButton "radio2" shall be checked and the others not.
To do this I used the following two codes but unfortunately they didn't work.
First code:
if (settings2.getText().equals("0")) {
radio0.setChecked(true);
radio1.setChecked(false);
radio2.setChecked(false);
} else if (settings2.getText().equals("1")) {
radio0.setChecked(false);
radio1.setChecked(true);
radio2.setChecked(false);
} else if (settings2.getText().equals("2")) {
radio0.setChecked(false);
radio1.setChecked(false);
radio2.setChecked(true);
}
Second code:
if (settings2.getText().equals("0")) {
radioGroup1.check(R.id.radio0);
} else if (settings2.getText().equals("1")) {
radioGroup1.check(R.id.radio1);
} else if (settings2.getText().equals("2")) {
radioGroup1.check(R.id.radio2);
}
Can someone help with this little problem please? I'm looking forward to your help!
Thanks in advance!
Here's the problem.
EditText et = ....
et.getText() // Does not return a string, it returns an Editable.
Try:
String str = et.getText().toString;
Then using str to do your comparisons.
Edit: See source code below on why u have to use Strings to compare. The default is to compare by reference, but Strings have overriden equals to compare based on string values. If you aren't using String u won't get matches.
public boolean More ...equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}
Are you sure the TextView text is either 0, 1, or 2? And for a setting like this, you should look into SharedPreferences! It is much easier to use and much faster too.
2nd thing you should do is instead of getting the settings2.getText().toString () you should do
int input = Integer.parseInt (settings2.getText().toString()
and then use
switch(input) {
case 0:
// code when text equals 0
break;
case 1:
// code when text equals 1
break;
case 2:
// code when text equals 2
break;
}
Look into this. . I'm on mobile at the moment
EDIT: Formatted text for better view.
EDIT 2 : SharedPreferences example
//get your app's Preference Manager
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); // If you are coding this in your Activity class, you have to use getDefaultSharedPreferences(this) instead!
public int getPrefs(String key) {
//get an Integer from the preferences
return prefs.getInt(key, defaultValue);
//defaultValue is in case a value for the given key is not found, for example, the user runs the app for the 1st time.
}
public void setPrefs() {
//You need a SharedPreference editor
SharedPreferences.Editor prefsEditor = prefs.edit();
//SharedPreference work with a key and its value
prefsEditor.putInt(key, value);
//You have to commit the preferences, or they don't get saved!
//If you want to use a save button, you can make the Editor variable into a Global var (class variable) and in your save button's onClick, just commit!
prefsEditor.commit();
}

Categories

Resources