Android DataBinding showing merged string with null check not working - android

I need to have show merged string through data binding. I can able to show it by below code easily.
android:text='#{sentRequestItems.receiver.firstName + " " + sentRequestItems.receiver.lastName}'
But in some case their is possibility that last name getting null form API response so in that case i can not able to show last name with null check.
I am trying with below code.
android:text='#{sentRequestItems.receiver.firstName != null ? sentRequestItems.receiver.firstName : "" + " " + sentRequestItems.receiver.lastName != null ? sentRequestItems.receiver.lastName : ""}'
Here with this it is not showing last name when it is not null in API response.
<androidx.appcompat.widget.AppCompatTextView
android:id="#+id/txvContactName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_marginStart="#dimen/_8sdp"
android:layout_marginEnd="#dimen/_4sdp"
android:layout_toStartOf="#+id/ivCancelRequest"
android:fontFamily="#font/lato_bold"
android:text='#{sentRequestItems.receiver.firstName != null ? sentRequestItems.receiver.firstName : "" + " " + sentRequestItems.receiver.lastName != null ? sentRequestItems.receiver.lastName : ""}'
android:textColor="#color/black"
android:textSize="#dimen/_15ssp"
tools:text="John Donny">
Any help is greatly appreciated.

I think it's not a best idea to perform coding in xml, readability suffers.
I suggest you to create static method, something like
class Utils {
static String formatName(RequestItem sentRequestItems) {
return (sentRequestItems.receiver.firstName != null ?
sentRequestItems.receiver.firstName : "") + " " +
(sentRequestItems.receiver.lastName != null ? sentRequestItems.receiver.lastName : "")
}
}
It's simplier to debug.
Also, don't forget brackets. You code doesn't work, because if first comparison sentRequestItems.receiver.firstName != null succeeds, all expression just returns sentRequestItems.receiver.firstName.
then in import it in your xml and use, like
android:text="#{Utils.formatName(sentRequestItems)}"

You can use BindingAdapter.
In Kotlin.
Step 1
Create a class BindingAdapters where you will have all your binding adapters method.
Step 2: Create a function like below
#BindingAdapter("app:contact_name")
#JvmStatic
fun setContactName(tvContactName: TextView, sentRequest: SentRequestItems?) {
if(sentRequest.receiver!=null){
if(sentRequest.receiver.lastName.isNullOrEmpty()){
tvContactName.text=sentRequest.receiver.firstName
}else{
tvContactName.text="$sentRequest.receiver.firstName
$sentRequest.receiver.firstName"
}
}
}
Step 3: Add the attribute in your text view
app:contact_name="#{sentRequestItems}"

Related

Display formatted view model value

I have a TextInputEditText that I bind to a ViewModel MutableLiveData object, like so:
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/phone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:text="#={ viewModel.mPhoneNumber }"
android:textColorHint="#color/hint_color"/>
I also have a text watcher to format the edit text so that the phone number can display in the format XXX-XXX-XXXX while the user types it out.
However, I need the value in the view model to be without the dashes. As a test, I removed the textwatcher and I tried to use a converter to change the phone number to be with no spaces - but it just caused an infinite loop. And, I can't seem to be able to find proper documentation on how to do this. Code below:
#InverseMethod("StringToPhone")
public static String phoneToString(TextInputEditText view, String oldValue, String value) {
// Just a test for now
if (view.getText() != null && !view.getText().toString().equals(oldValue)) {
view.setText("BLA" + value);
}
return view.getText().toString();
}
public static String StringToPhone(TextInputEditText view, String oldValue, String value) {
// Was supposed to return input string with no spaces
return oldValue == null ? "" : oldValue.replace(" ", "");
}
with
android:text="#={ Converter.phoneToString(phone, viewModel.mPhoneNumber, viewModel.mPhoneNumber) }"
This caused an infinite loop. Does anyone have a proper example / documentation for how to use the converter? Am I using the complete wrong idea, perhaps this is not what the converter was intended to do?

How do i check if a Api response exists

I keep getting a null pointer exception i want to see if the response exists and if so println it out.
if (responsePlace.result.opening_hours.weekday_text.isNotEmpty() ){
println("The response for place time " + responsePlace.result.opening_hours.weekday_text[0].toString())}
you can try this :
responsePlace.let
{
when(it.isSuccessful) {
true -> println(""The response for place time " + it.result.opening_hours.weekday_text[0].toString()")
false -> println("something went wrong!")
}
Use the handy isNullOrEmpty() method in kotlin.
So your method will look like
if (!responsePlace.result.opening_hours.weekday_text.isNullOrEmpty()){
println("The response for place time " + responsePlace.result.opening_hours.weekday_text[0].toString())}
take care of the '!' negation at the start of the condition
You must check which object is null or better to post log trace.
you may use Kotlin safe call which will prevent NPE.
if(responsePlace?.result?.opening_hours.weekday_text.isNullOrEmpty())
println("The response for place time " + responsePlace.result.opening_hours.weekday_text[0].toString())

Looking for explanation with a Kotlin non-null assertion error in Android app?

I am new to Kotlin and I am writing an Android application but I receive the following compiler warning depicted in the screenshot.
My question about this particular error pertains to the following lines:
if (months?.toInt() == 1) { monthsText = "1 Mo " }
if (months?.toInt() > 1) { monthsText = String.format("%d Mos ", months) }
The first line with == compiles fine but > 1 produces the null assertion. I have added a screenshot of the error and a code snippet. BTW, if there is a better way to code that it may be helpful in my understanding of the issue.
If I add the !! as noted in the error, it compiles and runs, but if the months var is null, which it may be the app crashes.
I don't really understand why == would be different than >
The database I am getting this data from has the "yearsMonthsExperience" stored as "1205" (YYMM).
val yearsMonths= (markerData.mMarkerUser!!["yearsMonthsExperience"] as? String)?.padStart(4, '0')
val years = yearsMonths?.take(2)?.toInt()
val months = yearsMonths?.takeLast(2)?.toInt()
var yearsText = ""
if (years != null && years == 1) { yearsText = "1 Yr " }
if (years != null && years > 1) { yearsText = String.format("%d Yrs ", years) }
var monthsText = ""
if (months?.toInt() == 1) { monthsText = "1 Mo " }
if (months?.toInt() > 1) { monthsText = String.format("%d Mos ", months) }
mInfoView.lbYearsExperience.text = String.format("%s%s Exp.", yearsText, monthsText)
Thanks in advance for any explanation or help.
> is an overriden operator. It is only syntactic sugar.
So your if statement actually looks like this: months?.toInt().compareTo(1)
To make it work you need to give it a default value something like this: months?.toInt()?:0 > 1.
You can read more about operator overloading here: https://kotlinlang.org/docs/reference/operator-overloading.html

android: check if the string not only white spaces

How can I check if a string contains anything other than whitespace?
This code didn't work:
String string = " \n\n\t\t ";
if(string.length()==0) doSomething();
since spaces and new lines have values.
Can anyone tell me how can I do it?
Note: minSDKVersion = 5
Regards :)
Try this:
if (string.trim().length() == 0) { /* all white space */ }
Alternatively, you can use a regular expression:
if (string.matches("\\w*")) { . . . }
try:
if (string == null || TextUtils.isEmpty(string.trim()) doSomething();
You can use trim to remove whitespace from both ends of the string. Then compare with the empty string.
Kotlin:
The below code takes the string, trims all of the letters down, and checks to see if the result is white space by using .isEmpty().
val str = " "
if (str.trim().isEmpty()) {
// white space only
} else {
// this string has actual characters/letters in it
}
Try: it works
if (txt.getText().toString().trim().matches(" ")){
Toast.makeText(getApplicationContext(), "You did not select any text"
, Toast.LENGTH_LONG).show();
}
else{
}

result of if condition that check text of textView

there are some problem in result of if condition that check the text of textView
this is the code for more explain
times.xml
<TextView
android:id="#+id/tiMinutesView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="--"
android:textColor="#3134E8" />
TimesActivity.java
TextView minView;
minView = (TextView) v.findViewById(R.id.tiMinutesView);
if (minView.getText().toString().trim() != "--") {
Toast.makeText(TimesActivity.this,
"OK",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(TimesActivity.this,
"NO", Toast.LENGTH_LONG)
.show();
}
Now it is supposed to return false and display NO because it is equal "--" actually, but it returns true and display OK
What is the problem ???
Always use equals() method for String value comparison.
if (!minView.getText().toString().trim().equals("--")) {
....
}
== is used for comparing the object references. equals() is the one used for value comparisons.
P.S:- There are like a zillion questions here # SO, which explain this in more detail. Do refer them for more clarity.
You're on Java dude, so change the relevant line to:
if (minView.getText().toString().trim().equals("--"))
{
//write your code here.
}...
always compare string using equals() of the string value/object.
if(!minView.getText().toString().trim().equals("--")){
}....
this will compare the value and minView.getText().toString().trim() != "--" this will compare the two string object
use this
if (!minView.getText().toString().trim().equals("--")
instread of using
if (minView.getText().toString().trim() != "--")

Categories

Resources