Boolean in Retrofit - java

I have this json object that has a boolean data type. I'm trying to look or learn on how i set my boolean as a response for my retrofit builder. So basically i have this "status" that indicates true or false in my json object. How do i set the that status and declare that if the status is true the text color will be green or else it will be false. I'm still a beginner with this bear with me pls.

It's because response.body().getSoftware()[i].status is a boolean type. You can't use boolean as an input parameter in setText method - the signature of this method allows you to pass String or Int(string resource id).
To reach your goal try setting text color using this variable:
if (response.body().getSoftware()[i].status) {
softwareStatus.setTextColor(Color.GREEN);
} else {
softwareStatus.setTextColor(Color.RED);
}
softwareStatus.setText(response.body().getSoftware()[i].status.toString())
//or use softwareStatus.setText("" + response.body().getSoftware()[i].status) if status is primitive boolean and not object Boolean
Also, don't forget to set some text if it's not set in your XML layout.
UPD (to have all statuses in one coloured string):
for (int i = 0; i < response.body().getSoftware(); i++) {
String textToSet = "" + response.body().getSoftware()[i].status;
Spannable spannable = new SpannableString(textToSet);
ForegroundColorSpan fcs = new ForegroundColorSpan(response.body().getSoftware()[i].status ? Color.GREEN : Color.RED);
spannable.setSpan(fcs, 0, textToSet.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
softwareStatus.append(spannable);
softwareStatus.append("\n\n");
}

it says it cannot resolve method 'settext'(boolean)
You are getting this error because you are trying to pass a boolean value parameter to setText method, such signature of setText doesn't exist, hence it is giving you this error. You can read about setText here.
If you need to display true/false in your TextView you can do like,
setText(someBoolean + "");
or if you need to show something else based on true/false then you should check value in if condition and then do whatever you need to.
It seems like you are getting this error here
softwareStatus.setText(response.body().getSoftware()[i].status);
You can try like,
softwareStatus.setText(response.body().getSoftware()[i].status + "");

Related

Android EditText Symbol must remain at initial position

I have a text field where the start symbol is $ (could be euro or pound depending on an application setting). I need to make it so that if the user clicks before the symbol nothing will happen. In other words, the selection must remain after the symbol. I tried doing something like this but it seems wrong and it gave me an error:
billAmount.addTextChangedListener(new TextWatcher() {
//other methods
#Override
public void afterTextChanged(Editable s) {
billAmount.setText(currencySymbol + billAmount.getText().toString());
}
});
I was thinking of using an inputFilter but nothing I tried worked. I'm also not allowed to use a TextView right before the EditText.
First, in your code sample, the reason you are getting an error is because, as others have said, you are calling the setText method inside the afterTextChanged method. Calling setText is obviously changing the text which causes afterTextChanged to be called again. This results in the afterTextChanged being called continuously until there is eventually a stack overflow.
You have two issues: 1) You want to always keep the cursor positioned after the currency symbol, and 2) You want to make sure the currency symbol is never somehow removed.
The easiest way to solve #1 is to create a subclass of EditText and override the onSelectionChanged method.
public class MyEditText extends EditText {
// ...
#Override
public void onSelectionChanged(int selStart, int selEnd) {
super.onSelectionChanged(selStart, selEnd);
// Make sure the text's length is greater than zero.
// Then, if the cursor is at position zero...
if (getText().length() > 0 && selStart == 0) {
// ...move it over to position one.
setSelection(1, selEnd);
}
}
}
This will force the cursor to always go after the currency symbol even if the user attempts to move it before it. The check getText().length() > 0 is to ensure that the EditText contains at least one character, otherwise attempting to move the cursor will result in an Exception.
As for #2, there are a couple ways to go at it. You can attempt to use some instance variables inside your TextWatcher to keep track of when the text needs to be formatted, but that won't prevent the unnecessary method calls from actually happening, and it adds some unneeded complexity. I think it would be easier to simply use an InputFilter, which you can specify in your extended EditText's constructor.
public class MyEditText extends EditText {
public MyEditText(Context context) {
super(context);
// Set the EditText's input filter.
setFilters(new InputFilter[] { new InputFilter {
#Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
// If the currency symbol is about to be replaced...
if (dstart == 0)
// Add the currency symbol to the front of the source.
return currencySymbol + source;
// else
// Return null to indicate that the change is okay.
return null;
}
}});
}
// ...
}
In the filter method, the dest parameter represents the EditText's text, and the dstart and dend parameters represent the start and end positions of the portion of the text that is about to be replaced. Since the currency symbol should always be the first character, we know it is about to be replaced if dstart is zero, in which case we simply return the source (which represents the replacement text) with the currency symbol placed in front. Otherwise, we indicate that the change is okay by returning null.
I tested it, and it seems to work for what you need.
On a side note, although I understand that you're not "allowed" to use a TextView, I think it's worth reiterating that using one would provide a much better solution to this problem. One particularly useful solution being to have a hidden EditText contain the raw input from the user, and having the TextView on top of the EditText. You would use a TextWatcher to update the TextView with the properly formatted input from the EditText.
I guess you are getting StackOverFlowException.
try this
String oldValue="";//instace variable
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//bilamount always starts with your currency symbol
if (s != null && s.length() == 0) {
editText.setText("$");
editText.setSelection(1);
}
if (s != null && s.length() > 0) {
String billAmount = s.toString();
if (!oldValue.equals(billAmount)) {//minimize unnecessary setText() method call
oldValue= billAmount;
editText.setText(billAmount);
editText.setSelection(billAmount.length());
}
}
}
Note : your EditText first init with your currencySymbol i.e. billAmount.setText(currencySymbol);

EclipseRCP - Databind text with a constant value added at the end

I have a simple scale with a range of 0 - 100. I bound that to a label via WindowsBuilder. I want the text to display the numerical value on the scale and a % following that. How would I go about doing this?
The source code was generated by Windows Builder
protected DataBindingContext initDataBindings() {
DataBindingContext bindingContext = new DataBindingContext();
//
IObservableValue observeTextLblPercentObserveWidget = WidgetProperties.text().observe(lblPercent);
IObservableValue observeSelectionScaleObserveWidget = WidgetProperties.selection().observe(scale);
bindingContext.bindValue(observeTextLblPercentObserveWidget, observeSelectionScaleObserveWidget, null, null);
//
return bindingContext;
}
I don't know how you may do it in WindowsBuilder, but you need to add org.eclipse.core.databinding.conversion.IConverter.
Actually I think you'll need two converters (from model to text that appends "%" and one for reverse convertion to parse user input) and a validator.

Using Boolean True/False with JOptionPane.YES_NO_OPTION

I have a series of four yes/no choices in four separate dialog boxes, the cumulative results of which will lead to one of twelve separate links (e.g., Yes/Yes/Yes/No -> link A, Yes/No/No/Yes -> link B, etc). The branching logic uses boolean values.
Here's what I have so far...just the first dialog box and printing the results for validation.
public class OutageGuideSelector{
public static void main(String[] args){
boolean contactServerUp;
boolean vistaUp;
boolean stormOutage;
boolean vistaCSUp;
//
int contactServerEntry = JOptionPane.showConfirmDialog(null,
"Is the contact server up", "Please select",
JOptionPane.YES_NO_OPTION);
System.out.println("result from entry " + contactServerEntry);
if(contactServerEntry==1)
contactServerUp = true;
else
if(contactServerEntry==0)
contactServerUp = false;
/* System.out.println(contactServerUp); */
}}
Right now, the results of clicking YES reults in a 0 being returned, NO results in a 1. Is this normal, seems counterintuitive, and there's nothing at docs.oracle.java that shows a clear example of the output values except this which seems to suggest that the public static final int YES_NO_OPTION default in 0.
Additionally, the line System.out.println(contactServerUp); comes back with an error that the field contactServerUp might not have been initialized when I un-comment it, so I can't see if my convert-int-to-boolean is working.
First: It appears that JOptionPane method does not include any boolean returns...except getWantsInput() which returns the value of the wantsInput property...so I assume I'm already being the most efficient I can with this. I'd like to know if there's an easier way.
Second, what am I missing that prevents my console output statement from recognizing the contactServerUp? Where's my misplaced semicolon?
According to the javadoc, when one of the showXxxDialog methods returns an integer, the possible values are:
YES_OPTION
NO_OPTION
CANCEL_OPTION
OK_OPTION
CLOSED_OPTION
You should test against those constants:
contactServerUp = (contactServerEntry == JOptionPane.YES_OPTION);
The value returned by the the JOptionPane dialogs are values defined as constant fields in the class.
Although, indeed, one could assume that 0 means false and 1 means true, the values are more ids for the different buttons a dialog can have.
To know if the user pressed yes or no, you can compare the return value to the constant fields described here. For example, in your case :
contactServerUp = (contactServerEntry == JOptionPane.YES_OPTION);
Since a dialog a JOptionPane can have more than two possible 'answers' a boolean would be a poor representation. You are forgetting about the YES, NO and CANCEL option, or what about just a OK answer.
If it would have been written today, I suspect a Enum would have been used instead of an int.
As for the second question, the compiler does not allow access to uninitialized variables.
When you do the following, there is a chance that the variable might not be initialized:
if(contactServerEntry==1)
contactServerUp = true;
else
if(contactServerEntry==0)
contactServerUp = false;
What if, for example, contactServerEntry == JOptionPane.CLOSED_OPTION? In that case, your boolean value is never initialized.
You need to add an else clause at the end of your if-else chain, or initialize contactServerUp value to a default value in the beginning.

Get boolean from a JTextField

I am trying to take the values from the text fields below to use with parent.addNewRoom(roomNo,roomEnSuite); but roomEnSuite is a Boolean value in the parent class. What is the correct procedure to get a Boolean from a JTextField?
public void actionPerformed( ActionEvent ae)
{
String item = ae.getActionCommand();
if ( item.equals("Confirm"))
{
String roomNo = nameJTextField.getText();
String roomEnSuiteS = idJTextField.getText();
parent.addNewRoom(roomNo,roomEnSuite);
this.dispose();
}
else if ( item.equals("Cancel"))
{
parent.resetButtons();
this.dispose();
}
}
To give a full answer from my above comments:
Handling boolean input using a JTextField would not be a good way to go about things as there are many variations the user could type yes/no/true/false, etc. mispelling?
Using a JRadioButton (for single answers) or JCheckbox (for multiple answers) would be a better way to go about handling true or false input. I would suggest a JRadioButton as you wouldn't want the user checking true and false.
http://docs.oracle.com/javase/tutorial/uiswing/components/button.html
Assuming the user entered the string true or false, you can turn it into a boolean with:
boolean value = Boolean.parseBoolean(idJTextField.getText());
A JTextField is meant to provide Strings. So unless you want the user to type true or false in the textfield (or whatever string you will parse to a boolean), there are better options available
a JCheckBox, which is typically used for toggle settings, like true-false
JRadioButtons (one for each setting, so two in this case)
And here a link to the corresponding Swing tutorial with examples on how to use these buttons
But if you really want to got with a textfield, then you should get the text from it and parse it by using for example Boolean.valueOf
As long as the value entered is always going to be true or false you can get a Boolean using;
boolean value = Boolean.parseBoolean(enSuiteJTextField.getText());

GWT telephone number masking

Does anyone know how to go about creating field that would perform telephone number format masking, like here (___) ___-____:
http://www.smartclient.com/smartgwt/showcase/#form_masking
A better approach would be to let the user type whatever they want: "789-555-1234" or "(789) 555-1234" or "7895551234" and then when the field loses focus decide if what they typed can be a phone number. If so you can reformat it as "(789) 555-1234". There are several related questions about how to do that sort of thing with regular expressions; just be sure your regex accepts the format you're changing the user's input to, otherwise it will be really annoying to edit.
As an example, look what happens when you type ".5" into the left margin field in Microsoft's standard page setup dialog: when you tab out it changes it to "0.5".
UPDATE: Here's sample code in GWT to illustrate. For the sake of this example, assume there's an element called "phoneContainer" to put the text box in. GWT doesn't give you the full java.util.regex package, but it gives enough to do this:
private void reformatPhone(TextBox phoneField) {
String text = phoneField.getText();
text = text.replaceAll("\\D+", "");
if (text.length() == 10) {
phoneField.setText("(" + text.substring(0, 3) + ") " + text.substring(3, 6) + "-" + text.substring(6, 10));
}
}
public void onModuleLoad() {
final TextBox phoneField = new TextBox();
RootPanel.get("phoneContainer").add(phoneField);
phoneField.addBlurHandler(new BlurHandler(){
public void onBlur(BlurEvent event) {
reformatPhone(phoneField);
}
});
}
It looks like you'd want to create your own widget that extends the GWT input box and has a default value set to the mask you want. Then you handle the onKeypress event and update the field as needed (making sure to set the cursor position to the correct location).

Categories