Search code examples
androidjsonxmlstringandroid-contentprovider

Set text inside xml layout from JSON file


I'm searching for a way to do this. I' have a JSON file inside may project, for example mystrings.json, that is like this:

{
"ErrorCodes.1": "Hai superato il tempo limite",
"ErrorCodes.2": "Hai superato il tempo limite"
}

i want to use this json in this way:

<TextView
  android:text="@ErrorCodes.1"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"/>

There is a way to accomplish? I'm searching but without results. Thanks in advance.


Solution

  • You can perform this with use of Data Binding

    1. Parse your JSON file and set it inside model class(i.e. UserModel, ErrorModel etc).
    2. Bind that model class to xml file

      <data>
        <variable name="user" type="com.example.User"/>
      </data>
      
    3. Set values in TextView

      <TextView android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="@{user.error}"/>
      
    4. Perform binding in your Activity

      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          MainActivityBinding binding = DataBindingUtil.setContentView(this, R.layout.main_activity);
          User user = get your model class here;
          binding.setUser(user);
      }
      

    Here are some tutorials of Data Binding, you can refer those.

    Working with Data Binding Android by Ravi Rupareliya
    DataBinding: how to develop Android apps faster
    No More findViewById by George Mount
    Develop apps faster using Data Binding – Part 1 by Chintan Rathod