Good evening, I have a problem with binding and editable.
binding.editText.text = String.format("%02d", picker.hour - 12) + " : " +
String.format("%02d", picker.minute) + "PM"
I know ".text" requires a editable, but how do i cast it?
I tried all type of normal casting but it seems not to be working.
The error disappears if i delete the "="
Casting is the wrong word to describe it. Casting is promising the compiler that the object already is of another type. And a String is not an Editable, so casting it would cause a crash with ClassCastException. The correct question would be how to convert the String to an Editable.
But you don't need to anyway. The text property expects an Editable, but there is also a setText function that accepts any CharSequence, which includes String.
binding.editText.setText(
String.format("%02d", picker.hour - 12) + " : " + String.format("%02d", picker.minute) + "PM"
)
And a tip, you can use format as an extension function to make it more concise.
binding.editText.setText(
"%02d".format(picker.hour - 12) + " : " + "%02d".format(picker.minute) + "PM"
)
And you can use string template format to make the concatenation more concise, too:
binding.editText.setText("${"%02d".format(picker.hour - 12)}:${"%02d".format(picker.minute)}PM")
Related
I have an app which downloads some files from internet. The source file name is dynamically generated depending on user selection. I use following method to create source file name. Note that fileId is an integer (1-99).
final String fileName = "file_" + String.format("%02d", fileId) + "_download.jpg";
The issue is I have seen some users are unable to download files (and of course they leave 1 start ratings :( ). When I check my server log I see some download requests came with file names like file_??_download.jpg. It looks like String.format() has returned ?? instead of two digit number.
I searched everywhere and could not find a solution for this. Can anybody tell me what's wrong with this code? I could not even re-produce this error on any of my devices.
Thanks!
You have to do it instead:
final String fileName = "file_" + String.format("%d", fileId) + "_download.jpg";
or
final String fileName = "file_" + fileId + "_download.jpg";
if you really want only the two last digits, do it:
int formattedFileId = fileId % 100;
final String fileName = "file_" + (formattedFileId < 10 ? '0' : '') + String.format("%d", formattedFileId) + "_download.jpg";
or
int formattedFileId = fileId % 100;
final String fileName = "file_" + (formattedFileId < 10 ? '0' : '') + formattedFileId + "_download.jpg";
String.format will use the digits for the default locale which are not necessarily 0-9. Use the version that permits setting a locale, and pass in Locale.ROOT.
String.format(Locale.ROOT, "%02d", fileId)
sumTextView.setText(Integer.toString(a) + " + " + Integer.toString(b));
This Line show warning you see in pic..
Use String.format();
sumTextView.setText(String.format("%1$d + %2$d", a, b));
With this you can format a string correctly with multiple variables, no matter whether they are strings or integers. This example takes the value of variable a and replaces the placeholder %1$d with it. Same goes for the other variable.
take an string copy whole line in it, then show string in setText
String str = (Integer.toString(a) + " + " + Integer.toString(a));
sumTextView.setText(str);
1. The First String Says that do not concate string with setText property.
String txt = String.valueOf(a) + " + " + String.valueOf(b);
sumTextView.setText(str);
2. Second warning says that your program have possibility to crash or genearte an exception in case if value of a or b is null or not an integer.
So check condition if(a!=null and b!=null) then display text in if condition.
I have some moment in time in UTC timestamp. I create a DateTime object from it, and then try to enrich it with "(today)" or "(tomorrow)" explanation if it is so:
DateTime dateTimeUtc = new DateTime(this.timeUtc, DateTimeZone.UTC);
DateTimeFormatter dateTimeFormatter = DateTimeFormat.mediumDate();
String resultingString = dateTimeUtc.withZone(DateTimeZone.forTimeZone(TimeZone.getDefault()))
.toString(dateTimeFormatter);
if(dateTimeUtc.getDayOfYear() == DateTime.now(DateTimeZone.UTC).getDayOfYear()) {
resultingString += " (" + context.getResources().getString(R.string.today_caption) + ")";
} else if(dateTimeUtc.getDayOfYear() == DateTime.now(DateTimeZone.UTC).plusDays(1).getDayOfYear()) {
resultingString += " (" + context.getResources().getString(R.string.tomorrow_caption) + ")";
}
But - surprisingly - my app does a TimeZone conversion somewhere. Device is set for eastern europian time (GMT+3 currently) and it works like this: 2 june 2:59 AM is treated like today (0_o) 2 june 3:01 is already a tomorrow.
Can someone point to an error?
P. S.: if there's a better way to qualify DateTime as 'today' or 'tomorrow' - I would be great to see any ideas.
Since no answer provided, I'll post workaround of my own. Though still have no idea why comparison of two UTC-zoned timestamp'ed days of year gives user's timezone offset.
Here's the code that works correctly for me:
if(dateTimeUtc.withZone(userZone).getDayOfYear() == DateTime.now(DateTimeZone.UTC).withZone(userZone)
.getDayOfYear()) {
resultingString += " (" + context.getResources().getString(R.string.today_caption) + ")";
} else if(dateTimeUtc.withZone(userZone).getDayOfYear() == DateTime.now(DateTimeZone.UTC).withZone(userZone)
.plusDays(1).getDayOfYear()) {
resultingString += " (" + context.getResources().getString(R.string.tomorrow_caption) + ")";
}
this produces correct check if given day is in interval from now till start of tomorrow or from start of tomorrow till start of the day after.
Trying to set a TextView, to a certain message containing a variable.
for Example
tvOddEven.setText("You have entered:", odd, "% of numbers");
odd is an int variable
it's giving me an error, that I can't use those parameters.
ideas?
tvOddEven.setText("You have entered:" + odd + "% of numbers");
Try this:
tvOddEven.setText("You have entered:" + String.valueOf(odd) + "% of numbers");
Since odd is not a String you need to convert it to string.
I need to display multiple lines of text in an Alert Dialog. If I use multiple setMessage() methods, only the last setMessage is displayed, as shown below.
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Statistics:");
alertDialog.setMessage("No. of attempts: " + counter);
alertDialog.setMessage("No. of wins: " + counterpos);
alertDialog.setMessage("No. of losses: " + counterneg);
Is there a way to create a new line for each of these in the dialog? Like using \n in System.print.out(); method.
Thanks!
You can do something like this
String alert1 = "No. of attempts: " + counter;
String alert2 = "No. of wins: " + counterpos;
String alert3 = "No. of losses: " + counterneg;
alertDialog.setMessage(alert1 +"\n"+ alert2 +"\n"+ alert3);
You could just create one string of everything you want to show and add "\n" where you'd like the line breaks to be.
alertDialog.setMessage("No. of attempts: " + counter + "\n" +
"No. of wins: " + counterpos + "\n" +
"No. of losses: " + counterneg);
Or even better to use a StringBuilder:
StringBuilder sb = new StringBuilder();
sb.append("No. of attempts: " + counter);
sb.append("\n");
sb.append("No. of wins: " + counterpos);
sb.append("\n");
sb.append("No. of losses: " + counterneg);
alertDialog.setMessage(sb.toString());
And the best way to do it would be to extract the static texts into a string resource (in the strings.xml file). Use the %d (or %s if you want to insert strings rather than ints) to get the dynamic values in the right places:
<string name="alert_message">No. of attempts: %1$d\nNo. of wins: %2$d\nNo. of losses: %3$d</string>
And then in code:
String message = getString(R.string.alert_message, counter, counterpos, counterneg);
alertDialog.setMessage(message);
You can also insert newlines directly in the strings.xml file:
<string name="my_string_text">This would revert your progress.\n\n Are you sure you want to proceed?</string>
Kotlin simplifies the solution by:
chaining the calls of the set methods
using interpolated strings
as follows:
"AlertDialog.Builder
This Builder object to allow for chaining of calls to set methods
"
(https://developer.android.com/reference/android/app/AlertDialog.Builder)
fun alertDemo() {
var counter: Int = 5
var counterpos: Int = 2
var counterneg: Int = 3
val builder = AlertDialog.Builder(this)
.setTitle("Statistics:")
.setMessage("""
|number of
|
|attempts: $counter
|wins: $counterpos
|losses: $counterneg
""".trimMargin())
.show()
}
I had prepared a screen-shot of the result, but as I am new here, I appear to have learned that uploading screenshots may be restricted to higher level community peers. Or did I miss something? Thank you for enlighting (perhaps not only) myself :)
The screenshot comes in a nice format without showing the bars.
PS:
For the minimalists, due to chaining, we could even eliminate the redundant "val builder ="