Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call static method with data binding?

I want to call my Util class method in layout.xml file like

<TextView
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="@{PreferenceUtil.getSavedUser().fullName}"/>

I have imported PreferenceUtil

<import type="com.amelio.utils.PreferenceUtil"/>

And PreferenceUtil.class has some methods.

public class PreferenceUtil {

    public static LoginResponse getSavedUser() {
        SharedPreferences sf = Amelio.getInstance().getSharedPreferences(PREF, Context.MODE_PRIVATE);
        String userJson = sf.getString(PREF_USER_DATA, null);
        if (userJson == null || userJson.equals("")) {
            return null;
        }
        return new Gson().fromJson(userJson, LoginResponse.class);
    }
}

Issue

    Found data binding errors.
****/ data binding error ****msg:cannot find method getSavedUser() in class com.amelio.utils.PreferenceUtil
file:D:\Khemraj\_AndroidStudioWorkspace_\amelioFinal\app\src\main\res\layout\activity_cart.xml
loc:94:40 - 94:68
****\ data binding error ****

Is this even possible, also suggest if this is recommended or not.

like image 767
Khemraj Sharma Avatar asked May 11 '18 13:05

Khemraj Sharma


2 Answers

I hope you must have found the answer in case if you are still struggling then find the answer below.

    <data>
      <import type="com.amelio.utils.PreferenceUtil"/>
 </data>


<TextView
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text='@{PreferenceUtil.getSavedUser()}' />

Please make sure your LoginResponse is marked public to access the values.

like image 51
DHRUV SINGH Avatar answered Oct 12 '22 18:10

DHRUV SINGH


in case you haven't found the answer yet:
you need to import the object type and cast it to that type like this:

<data>
  <import type="com.amelio.utils.PreferenceUtil"/>
  <import type="yourdirectory.LoginResponse"/>

</data>


<TextView
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text='@{((LoginResponse)(PreferenceUtil.getSavedUser()).fullName}' />
like image 28
Zahra Sdg Avatar answered Oct 12 '22 20:10

Zahra Sdg