Found data binding error s

I am new in data binding and trying to bind recyclerview and getting following error. I am following a github repository. android.databinding.tool.util.LoggedErrorException: Found data binding

I am new in data binding and trying to bind recyclerview and getting following error. I am following a github repository.

android.databinding.tool.util.LoggedErrorException: Found data binding
errors.data binding error
msg:Cannot find the setter for
attribute ‘app:data’ with parameter type
java.util.List on
android.support.v7.widget.RecyclerView. file:D:AndroidAll
DemoTextAndImageSwitcherappsrcmainreslayoutactivity_list_data_binding.xml
loc:17:24 — 17:45 data binding error

view model file:

public class ListViewModel extends BaseObservable
{
    private Context context;
    public ListRecyclerAdapter listRecyclerAdapter;
    public List<User> userList;

    public ListViewModel(final Context context)
    {
        this.context = context;
        userList = new ArrayList<>();
        listRecyclerAdapter = new ListRecyclerAdapter(context, userList);
    }

    public void setUp()
    {
        populateData();
    }

    public void tearDown()
    {

    }

    @Bindable
    public List<User> getData()
    {
        return this.userList;
    }

    @Bindable
    public ListRecyclerAdapter getListRecyclerAdapter()
    {
        return this.listRecyclerAdapter;
    }

    private void populateData() {
        for (int i =0;i<=50;i++){
            userList.add(new User("Name("+i+")", "Mobile("+i+")", "Email("+i+")", "Address("+i+")"));
        }
        notifyPropertyChanged(BR.data);

    }
}

my xml file:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:app="http://schemas.android.com/apk/res-auto">
    <data>
        <variable
            name="listViewModel"
            type="com.example.admin.textandimageswitcher.ListViewModel"/>
    </data>
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".ListDataBindingActivity">
        <android.support.v7.widget.RecyclerView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:adapter="@{listViewModel.listRecyclerAdapter}"
            app:data="@{listViewModel.userList}"
            android:id="@+id/list_data_binding_recycler">
        </android.support.v7.widget.RecyclerView>
    </LinearLayout>
</layout>

Trying to figure out what is causing data binding errors when you compile your Android project? This post will save you a lot of time and frustration.

There is nothing worse than the compiler telling you something’s wrong in your project but not telling you where. If you are getting cryptic errors like error: cannot find symbol import, the following methods may help you figure out what is wrong.

1. View All of the Build Output

Android Studio has two different ways to view the build output. The default tree view tries to condense the build output into an easy-to-view hierarchy.

tree view of build output

Although this method allows you to quickly get to your first build error, it doesn’t help if your first build error is a failed import because of problems elsewhere in your code. The underlying issue is obscured, and you should look at the entire build output. To see all of the build output, press the Toggle View button.

build output from android studio

Here, you can see the real reason for my compile error. I was missing a variable definition called viewModel in my layout file.

2. Fall Back to the Old Data Binding Compiler Temporarily

Starting in version 3.2.1 of Android Studio, the second version of the data binding compiler was turned on by default. Version 2 drastically improved compile times by incrementally creating the binding classes.

The incremental build may also be the source of the problem when you have cryptic error messages. I have found that rolling back to the first version of the data binding compiler can help reveal the real reason your code is not compiling. Once you figure out what your compile error is, switch back to Version 2 to restore the speed of your compile.

To take care of this, in the gradle.properties file, add the setting android.databinding.enableV2=false to revert to the old compiler. You could leave this setting there and just toggle the Boolean from false to true when you want to go back and forth. I chose to comment it out when I don’t need it, just in case a Version 3 compiler comes along someday. The default setting is true.

#Uncomment this line to revert to the old compiler
android.databinding.enableV2=false

3. Invalidate Caches

Sometimes, you may not even have an error in your code, but Android Studio incorrectly says that you do. Some people in online communities have found that if they tell Android Studio to Invalidate Caches and Restart, it can fix the erroneous error. This option is located in the File menu. I find this helps when the data binding compiler is not generating my data binding classes like it should be.

I hope these tips can help you conquer your Android data binding error challenges.

I am learning databinding with mvvm but I am getting following errors I did not know what is the main problem.

DataBinderMapperImpl.java:9: error: cannot find symbol
import gahfy.net.databinding.ActivityPostListBindingImpl;
                            ^
  symbol:   class ActivityPostListBindingImpl
  location: package gahfy.net.databinding
error: [kapt] An exception occurred: android.databinding.tool.util.LoggedErrorException: Found data binding error(s):

[databinding] {"msg":"cannot find method getLoadingVisibility() in class gahfy.net.ui.post.PostListViewModel","file":"C:\Users\Edgar\Documents\MVVMPosts\app\src\main\res\layout\activity_post_list.xml","pos":[{"line0":22,"col0":37,"line1":22,"col1":68}]}

error: cannot find symbol
import gahfy.net.databinding.ActivityPostListBindingImpl;
                        ^

symbol: class ActivityPostListBindingImpl
location: package gahfy.net.databinding

cannot find method getLoadingVisibility() in class gahfy.net.ui.post.PostListViewModel

what I have tried invalidate cache restart and rebuild and clean project it did not helped at all

below activity_post_list.xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>

        <variable
            name="viewModel"
            type="gahfy.net.ui.post.PostListViewModel" />
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ProgressBar
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:mutableVisibility="@{viewModel.getLoadingVisibility()}" />

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/post_list"
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:adapter="@{viewModel.getPostListAdapter()}"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

below PostListActivity.kt

  import android.os.Bundle
import androidx.annotation.StringRes
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import gahfy.net.R

import com.google.android.material.snackbar.Snackbar;
import gahfy.net.databinding.ActivityPostListBinding

class PostListActivity: AppCompatActivity() {
    private lateinit var binding: ActivityPostListBinding
    private lateinit var viewModel: PostListViewModel
    private var errorSnackbar: Snackbar? = null

    override fun onCreate(savedInstanceState: Bundle?){
        super.onCreate(savedInstanceState)

        binding = DataBindingUtil.setContentView(this, R.layout.activity_post_list)
        binding.postList.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)

        viewModel = ViewModelProviders.of(this).get(PostListViewModel::class.java)
        viewModel.errorMessage.observe(this, Observer {
            errorMessage -> if(errorMessage != null) showError(errorMessage) else hideError()
        })
        binding.viewModel = viewModel
    }

    private fun showError(@StringRes errorMessage:Int){
        errorSnackbar = Snackbar.make(binding.root, errorMessage, Snackbar.LENGTH_INDEFINITE)
        errorSnackbar?.setAction(R.string.retry, viewModel.errorClickListener)
        errorSnackbar?.show()
    }

    private fun hideError(){
        errorSnackbar?.dismiss()
    }
}

below PostListViewModel.kt

class PostListViewModel:BaseViewModel(){
    @Inject
    lateinit var postApi: PostApi
    private val loadingVisibility: MutableLiveData<Int> = MutableLiveData()
    val errorMessage:MutableLiveData<Int> = MutableLiveData()
    val errorClickListener = View.OnClickListener { loadPosts() }
    private val postListAdapter: PostListAdapter = PostListAdapter()

    private lateinit var subscription: Disposable

    init{
        loadPosts()
    }

    private fun loadPosts(){
        subscription = postApi.getPosts()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe { onRetrievePostListStart() }
                .doOnTerminate { onRetrievePostListFinish() }
                .subscribe(
                        // Add result
                        { result -> onRetrievePostListSuccess(result) },
                        { onRetrievePostListError() }
                )
    }

    private fun onRetrievePostListStart(){
        loadingVisibility.value = View.VISIBLE
        errorMessage.value = null
    }

    private fun onRetrievePostListFinish(){
        loadingVisibility.value = View.GONE
    }

    private fun onRetrievePostListSuccess(postList:List<Post>){
        postListAdapter.updatePostList(postList)
    }

    private fun onRetrievePostListError(){
        errorMessage.value = R.string.post_error
    }

    override fun onCleared() {
        super.onCleared()
        subscription.dispose()
    }
}

below BindingAdapters.kt

@BindingAdapter("mutableText")
fun setMutableText(view: TextView, text: MutableLiveData<String>?) {
    val parentActivity:AppCompatActivity? = view.getParentActivity()
    if(parentActivity != null && text != null) {
        text.observe(parentActivity, Observer { value -> view.text = value?:""})
    }


    @BindingAdapter("mutableVisibility")
    fun setMutableVisibility(view: View,  visibility: MutableLiveData<Int>?) {
        val parentActivity:AppCompatActivity? = view.getParentActivity()
        if(parentActivity != null && visibility != null) {
            visibility.observe(parentActivity, Observer { value -> view.visibility = value?:View.VISIBLE})
        }
    }

    @BindingAdapter("adapter")
    fun setAdapter(view: RecyclerView, adapter: RecyclerView.Adapter<*>) {
        view.adapter = adapter
    }


}

Сообщение об ошибке

Found data binding error(s):

[databinding] {"msg":"Could not find accessor com.dubhe.room.entity.User.name","file":"app\src\main\res\layout\activity_add_user.xml","pos":[{"line0":31,"col0":28,"line1":31,"col1":36}]}

Мой макет XML

<?xml version = "1.0" encoding = "utf-8"?>
<layout xmlns:android = "http://schemas.android.com/apk/res/android"
    xmlns:app = "http://schemas.android.com/apk/res-auto">

    <data>

        <import
            alias = "user"
            type = "com.dubhe.room.entity.User" />

        <variable
            name = "add"
            type = "android.view.View.OnClickListener" />

    </data>

    <LinearLayout
        android:layout_width = "match_parent"
        android:layout_height = "match_parent"
        android:orientation = "vertical">

        <androidx.appcompat.widget.Toolbar
            android:layout_width = "match_parent"
            android:layout_height = "wrap_content"
            app:title = "addUser" />

        <EditText
            android:id = "@+id/editUserName"
            android:layout_width = "match_parent"
            android:layout_height = "wrap_content"
            android:hint = "name"
            android:text = "@{user.name}" />     <-error in this line.

        <EditText
            android:id = "@+id/editUserAge"
            android:layout_width = "match_parent"
            android:layout_height = "wrap_content"
            android:hint = "age"
            android:inputType = "number"
            android:text = "@{user.age}" />

        <Button
            android:id = "@+id/btn"
            android:layout_width = "wrap_content"
            android:layout_height = "wrap_content"
            android:onClick = "@{add}"
            android:text = "Add" />

    </LinearLayout>
</layout>

Моя сущность — это класс данных котлина.

@Entity(tableName = "user")
data class User(
    @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "user_id") var id: Int = 0,
    @ColumnInfo(name = "user_name")var name: String = "",
    @ColumnInfo(name = "user_age")var age: Int = 0,
    @Ignore var isChecked: Boolean = false
)

Build.gradle в каталоге app.

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.2"

    defaultConfig {
        applicationId "com.dubhe.databinding"
        minSdkVersion 23
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    dataBinding {
        enabled = true
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility 1.8
        targetCompatibility 1.8
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'com.google.android.material:material:1.1.0-alpha08'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
//    implementation 'com.android.support:support-vector-drawable:29.0.0'
    implementation 'androidx.core:core-ktx:1.0.2'
    implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

    //Room
    implementation 'android.arch.persistence.room:runtime:2.1.4'

    //BaseRecyclerViewAdapter
    implementation 'com.github.CymChad:BaseRecyclerViewAdapterHelper:2.9.46'

    annotationProcessor 'android.arch.persistence.room:compiler:2.1.4'

    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9'

}

Независимо от того, очищаю ли я и перестраиваю или делаю недействительными кеши, я не могу скомпилировать.

Сообщение об ошибке

Found data binding error(s):

[databinding] {"msg":"Could not find accessor com.dubhe.room.entity.User.name","file":"app\src\main\res\layout\activity_add_user.xml","pos":[{"line0":31,"col0":28,"line1":31,"col1":36}]}

Мой макет XML

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>

        <import
            alias="user"
            type="com.dubhe.room.entity.User" />

        <variable
            name="add"
            type="android.view.View.OnClickListener" />

    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <androidx.appcompat.widget.Toolbar
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:title="addUser" />

        <EditText
            android:id="@+id/editUserName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="name"
            android:text="@{user.name}" />     <-error in this line.

        <EditText
            android:id="@+id/editUserAge"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="age"
            android:inputType="number"
            android:text="@{user.age}" />

        <Button
            android:id="@+id/btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="@{add}"
            android:text="Add" />

    </LinearLayout>
</layout>

Моя сущность — это класс данных котлина.

@Entity(tableName = "user")
data class User(
    @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "user_id") var id: Int = 0,
    @ColumnInfo(name = "user_name")var name: String = "",
    @ColumnInfo(name = "user_age")var age: Int = 0,
    @Ignore var isChecked: Boolean = false
)

Build.gradle в каталоге app.

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.2"

    defaultConfig {
        applicationId "com.dubhe.databinding"
        minSdkVersion 23
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    dataBinding {
        enabled = true
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility 1.8
        targetCompatibility 1.8
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'com.google.android.material:material:1.1.0-alpha08'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
//    implementation 'com.android.support:support-vector-drawable:29.0.0'
    implementation 'androidx.core:core-ktx:1.0.2'
    implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

    //Room
    implementation 'android.arch.persistence.room:runtime:2.1.4'

    //BaseRecyclerViewAdapter
    implementation 'com.github.CymChad:BaseRecyclerViewAdapterHelper:2.9.46'

    annotationProcessor 'android.arch.persistence.room:compiler:2.1.4'

    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9'

}

Независимо от того, очищаю ли я и перестраиваю или делаю недействительными кеши, я не могу скомпилировать.

1 ответ

Лучший ответ

Вы используете import вместо variable:

Этот:

<import alias="user" type="com.dubhe.room.entity.User" />

Должно быть это:

<variable name="user" type="com.dubhe.room.entity.User" />


0

Héctor
7 Апр 2021 в 13:20

Содержание

  1. Atomic Spin
  2. Atomic Object’s blog on everything we find fascinating.
  3. Three Methods for Solving Android Data Binding Errors
  4. 1. View All of the Build Output
  5. 2. Fall Back to the Old Data Binding Compiler Temporarily
  6. 3. Invalidate Caches
  7. XAML data binding diagnostics
  8. XAML Binding Failures tool window
  9. Supported platforms

Atomic Spin

Atomic Object’s blog on everything we find fascinating.

Three Methods for Solving Android Data Binding Errors

Trying to figure out what is causing data binding errors when you compile your Android project? This post will save you a lot of time and frustration.

There is nothing worse than the compiler telling you something’s wrong in your project but not telling you where. If you are getting cryptic errors like error: cannot find symbol import , the following methods may help you figure out what is wrong.

1. View All of the Build Output

Android Studio has two different ways to view the build output. The default tree view tries to condense the build output into an easy-to-view hierarchy.

Although this method allows you to quickly get to your first build error, it doesn’t help if your first build error is a failed import because of problems elsewhere in your code. The underlying issue is obscured, and you should look at the entire build output. To see all of the build output, press the Toggle View button.

Here, you can see the real reason for my compile error. I was missing a variable definition called viewModel in my layout file.

2. Fall Back to the Old Data Binding Compiler Temporarily

Starting in version 3.2.1 of Android Studio, the second version of the data binding compiler was turned on by default. Version 2 drastically improved compile times by incrementally creating the binding classes.

The incremental build may also be the source of the problem when you have cryptic error messages. I have found that rolling back to the first version of the data binding compiler can help reveal the real reason your code is not compiling. Once you figure out what your compile error is, switch back to Version 2 to restore the speed of your compile.

To take care of this, in the gradle.properties file, add the setting android.databinding.enableV2=false to revert to the old compiler. You could leave this setting there and just toggle the Boolean from false to true when you want to go back and forth. I chose to comment it out when I don’t need it, just in case a Version 3 compiler comes along someday. The default setting is true.

#Uncomment this line to revert to the old compiler
android.databinding.enableV2=false

3. Invalidate Caches

Sometimes, you may not even have an error in your code, but Android Studio incorrectly says that you do. Some people in online communities have found that if they tell Android Studio to Invalidate Caches and Restart , it can fix the erroneous error. This option is located in the File menu. I find this helps when the data binding compiler is not generating my data binding classes like it should be.

I hope these tips can help you conquer your Android data binding error challenges.

Источник

XAML data binding diagnostics

Applies to: Visual Studio Visual Studio for Mac Visual Studio Code

Developers who work on XAML projects often have to detect and resolve XAML data binding failures in their applications. Now there are tools within Visual Studio 2019 version 16.8 or later and Visual Studio 2022 to help find these annoying data binding failures while you debug your application. Examples of common binding failures are as follows:

  • Binding to a property name that doesn’t exist:
  • Binding to a value of the wrong type, like binding to a Boolean when an enumeration is required: Visibility=»«

Because these bindings are computed at runtime by using reflection, the XAML editor isn’t always able to catch them, and your build will still succeed. The failure happens only at runtime.

XAML data binding is explained in these articles:

Binding failures have always been written to the debug output window in Visual Studio. But it’s easy to miss the binding failures within debug output since it contains other debugging information that scrolls binding failures out of view. Here’s an example of a WPF binding failure within the debug output window:

The binding failure might be hundreds of lines off the top of the window, and the text doesn’t tell you exactly which binding had the failure, so you need to think about it and search.

Now, with the XAML Binding Failures tool window, you can clearly see which bindings have failed, along with relevant data for each failure, such as the file location within XAML. Plus, there are many useful features for investigating the failures by searching, sorting, and even opening the XAML editor with focus set on the failed binding.

Double-clicking those rows opens the source XAML for the binding, as shown in the following image:

The XAML Binding Failures tool window is available during debugging. To open it, go to Debug > Windows > XAML Binding Failures.

Or, select the Binding failures button in the application toolbar. The number next to the icon shows how many binding failures are shown in the tool window.

When there are no binding failures in the tool window, the icon shows as gray without a number next to it. This is helpful while running your application. If you see the icon turn red with a number, click it to quickly jump to the tool window to see what binding failures occurred. There’s no need to keep an eye on the Visual Studio tool windows. When a binding fails the icon will tell you right away.

A similar icon also appears in the Live Visual Tree tool window.

The following is a description of all components of the XAML Binding Failures tool window.

  • The toolbar at the top contains buttons as follows:
    • Clear the list of failures: This is useful if you’re about to show a new page in your app and want to see if any binding failures show up. When you start a new debugging session, the list is automatically cleared.
    • Delete selected rows: If a failure has been fixed or isn’t relevant, you can delete it from the list. Deleted rows will show up again if the binding fails again.
    • Clear all filters: If there are any filters on the list, such as searching for text, then this button will clear them and show the full list.
    • Combine Duplicates: Often the same binding will fail many times in a row when it is within an item template. When the Combine Duplicates button is selected (with an outline around it) then all duplicate failures are shown as a single row. The Count column will show how many times the failure occurred.
  • The Search Binding Failures box in the top corner lets you filter the failures to only those that contain specific text.
  • The table columns, in order, show:
    • An icon that shows if the row is for an error or warning.
    • An icon that shows angle brackets <> if navigating to the failed in XAML is supported. See the Supported Platforms section.
    • Data Context: This is the type name for the binding’s source object
      • See Binding.Source
    • Binding Path: This is the property path for the binding
      • See Binding.Path
    • Target: This is the type and property name where the binding’s value will be set.
      • See BindingExpressionBase.Target and BindingExpressionBase.TargetProperty
    • Target Type: This is the expected type of the binding’s target property.
      • See BindingExpressionBase.TargetProperty
    • Description: This column contains more information about what exactly failed for the binding.
    • File, Line, and Project: If known, this is the location in XAML where the binding is defined.
  • Right-clicking a row or multiple selected rows will show a context menu, with standard options for showing/hiding columns or grouping them. Other options are as follows:
    • Copy all the text from a row or just a single column to the clipboard.
    • Copy Original Error will copy the text that appeared in the debug output window.
    • View Source will go to the binding source in XAML for one selected row.
    • Reset Columns will undo all changes to column visibility and sorting, getting you back quickly to what was originally shown.

To sort the list, click any column header. To sort again by an extra column, hold down the Shift key and click another column header. To select which columns are displayed and which are hidden, choose Show Columns from the shortcut menu. To change the order in which columns are displayed, drag any column header to the left or right.

After you double-click a row or press Enter to navigation to the source, you can press F8 or Shift+F8 to move down or up through the list of binding failures. This is like other panes in Visual Studio that show a list.

Supported platforms

Most XAML platforms are supported if binding failures are written to debug output. Some platforms supply extra source information to the debugger that allows navigating to the source.

Platform Supported Navigate to source supported
WPF .NET Framework Yes No
WPF .NET 5.0 RC2+ Yes Yes
UWP Yes No
WinUI3 desktop Yes No
MAUI (Multi-platform App UI) Yes No
Xamarin 4.5.0.266-pre3+ Yes Yes
Xamarin before 4.5.0.266-pre3 No No

The XAML Hot Reload option must be enabled in Visual Studio for navigating to source to work. This option is in the Tools > Options > Debugging dialog:

Navigating to source only works for bindings defined in XAML source files, not if they’re created through code. You can clearly see which rows support navigating to the source. If there’s no angle bracket icon in the second column, then navigating to source isn’t supported, such as with the highlighted row in the following screenshot:

For WPF in .NET Framework, data binding failures must be shown in the debug output for the XAML Binding Failures pane to detect and show them. The option for this is in the Tools > Options > Debugging > Output Window > WPF Trace Settings dialog. If the setting is either Off or Critical, then data binding errors aren’t written to debug output and can’t be detected. With WPF in .NET 5, .NET 6, and later the data binding output setting doesn’t affect the failure list.

Источник

16 ответов

Хорошо, так что те, кто задается вопросом, как я это исправил. Решение довольно простое, но, вероятно, вам это не понравится.

Мне пришлось переместить все мои классы, которые использовались при связывании данных в корневом пакете проекта, и после того, как он снова начал работать.

Marian Pavel
03 апр. 2018, в 08:14

Поделиться

После обновления до Android Studio 3.2 эта строка работает для меня. В моем проекте есть как Java, так и код Kotlin (компилятор).

Добавьте к вашему gradle.properties следующее: android.databinding.enableV2 = false

Причина:

Связывание данных V2

Data Binding V2 теперь включен по умолчанию и совместим с V1. Это означает, что если у вас есть зависимости библиотек, которые вы скомпилировали с помощью V1, вы можете использовать их с проектами с использованием Data Binding V2. Однако обратите внимание, что проекты, использующие V1, не могут потреблять зависимости, которые были скомпилированы с помощью V2.

source (Release Note): https://developer.android.com/studio/releases/

Xavier
28 сен. 2018, в 07:22

Поделиться

Это может быть не самый полезный ответ, но в моем случае это было вызвано совершенно несвязанной проблемой в моем коде.

Я получал 51 error: cannot find symbol: DataBindingComponent ошибки error: cannot find symbol: DataBindingComponent (в каждом отдельном классе Data Binding), и я потратил годы, удаляя изменения в свой код XML и ViewModel, пытаясь найти причину этого.

Проблема на самом деле заключалась в недействительном изменении. Я сделал модель комнаты. Я предполагаю, что ошибка в Комнате могла быть запутана всеми ошибками привязки данных, но журналы Debug/Scan в терминале не указывали на это.

Поэтому, если вы столкнулись с этой проблемой, просмотрите все последние коды, даже, казалось бы, несвязанные изменения.

Редактировать: см. Это сообщение https://stackoverflow.com/questions/50755768/android-databinding-swallows-errors-from-other-compilers об этих ошибках привязки данных, запутывающих другие проблемы с kapt (например, Room/Dagger)

Squimon
27 сен. 2018, в 02:04

Поделиться

если вы используете kotlin на Android 3.2, замените distriburl на эту строку

distributionUrl=https://services.gradle.org/distributions/gradle-4.6-all.zip

и вас попросят изменить версию инструментария сборки на соответствующую версию. как только вы это сделаете, удалите эту строку из файла build.gradle на уровне приложения

kapt 'com.android.databinding:compiler:3.0.1

и построить проект. это сработало для меня.

slenderm4n
25 сен. 2018, в 11:14

Поделиться

Вам нужно изменить три вещи при обновлении с Android Studio 3.0.1 до 3.1.0. Это указано ниже

1) Вам нужно изменить в свойствах gradle.wrapper в дистрибутиве Url. Ваш URL должен быть distribUrl = https://services.gradle.org/distributions/gradle-4.4-all.zip

Изображение 125719 К Изображение 125720

2) Необходимо обновить зависимость привязки данных в файле gradle файла уровня от kapt ‘com.android.databinding: compiler: 3.0.1’ to kapt ‘com.android.databinding: compiler: 3.1.0’

Изображение 125721

И если вы разрабатываете, используя kotlin, тогда,

3) Третье и последнее, что нужно обновить плагин kotlin gradle в classpath «org.jetbrains.kotlin: kotlin-gradle-plugin: 1.2.30» to classpath «org.jetbrains.kotlin: kotlin-gradle-plugin: 1.2.31 « в зависимости от уровня градиента уровня проекта. Также вы можете обновить версию градиента сборки, как показано на рисунке ниже.

Изображение 125722

ведь все вышеописанный шаг просто строит сборку и перестраивает проект. Надеюсь, он будет работать, чтобы решить вашу проблему.

Спасибо!! Счастливое кодирование!

Sagar Kacha
27 март 2018, в 15:14

Поделиться

Чтобы исправить эту ошибку в Java-проекте, вы откатите откат для поддержки LibraryVersion — 27.0.2 из 27.1.0 работает с AndroidStudio 3.1 и com.android.tools.build:gradle:3.1.0

Ожидание исправления в Google

Alex_297
29 март 2018, в 17:03

Поделиться

У меня была такая же проблема, как и @Marian Pavel, где мой проект не мог скомпилировать компоненты привязки данных, если бы у меня не был класс, используемый в привязке данных в корневой папке.

Я исправил проблему, выполнив следующие действия:

Android Studio: 3.2.1 стабильная

**project build.gradle**
classpath 'com.android.tools.build:gradle:3.2.1'

**module build.gradle**
apply plugin: 'kotlin-kapt'
kapt "androidx.databinding:databinding-compiler:3.2.1"

**gradle.properties**
android.databinding.enableV2=false

ddy214
05 дек. 2018, в 04:16

Поделиться

Non из этих решений работал для меня, так что я узнал его ошибку в версии 3.2 beta 4 android studio:

buildscript {

repositories {
...
}
dependencies {
    //classpath "com.android.tools.build:gradle:3.2.0-beta04"  // buggy databinding
    classpath "com.android.tools.build:gradle:3.1.3" // working
}}

после этого я синхронизирую, перестраиваю и запускаю правильно

Kebab Krabby
26 июль 2018, в 10:00

Поделиться

Добавление этих строк в класс.properties помогло мне сохранить проблему

android.enableExperimentalFeatureDatabinding = true
android.databinding.enableV2=true

Moses Gitau
04 апр. 2018, в 11:20

Поделиться

ПЕРВЫЙ ВСЕ 1…………………………

  1. Build Make Project для создания создать класс после добавления
  2. // привязка приватного lateinit var binding: ActivityLoginBinding
  3. в действующем представлении //setContentView(R.layout.activity_login) binding = DataBindingUtil.setContentView(this @LoginActivity, R.layout.activity_login)

Yudi karma
28 март 2019, в 04:21

Поделиться

Это может показаться странным, но я потратил несколько часов на ошибку, и после проверки в моих последних изменениях я обнаружил, что это связано с ошибкой в базе данных Room.

Я объявил один из интерфейсов Dao, но забыл его анонимность с помощью @Dao.

После исправления ошибки привязки данных была исправлена.

Я думаю, это ошибка студии Android.

Ifta
19 окт. 2018, в 11:11

Поделиться

Проверьте свои XML файлы, если вы используете привязку данных. Я потерял один час сегодня, потому что я переименовал один класс, и Android Studio решила внести изменения в мои xml файлы. Например, у меня был класс с именем LiveGameModel, и я переименовал его в LiveGameView, и AS решила внести изменения в xml файлы, которые не связаны с этим представлением. Я знаю, эта ошибка не имеет смысла.

Nestor Lara
20 авг. 2018, в 18:10

Поделиться

Это очень сложная ошибка с андроид-студией и привязкой данных! Я должен был протестировать все предлагаемые решения и еще несколько дней в течение всего дня, чтобы, наконец, сделать компиляцию данных.

Поэтому мне пришлось отключить все настройки databindind в файле gradle.properties, просто прокомментировать эти строки или удалить их:

android.databinding.enableV2 = true
android.enableExperimentalFeatureDatabinding = true

удалить buildToolsVersion из build.gradle и иметь следующие версии sdk:

compileSdkVersion 27
defaultConfig {
    minSdkVersion 21
    targetSdkVersion 27
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}

Плюс еще пара чистых/перестроить недействительные кеши и перезапустить, и это ПОЛНОСТЬЮ скомпилировано. Инженеры AS отлично справляются с созданием ошибок!

Sergio
23 июнь 2018, в 17:49

Поделиться

У меня была такая же проблема. Исправлено, добавив google() в Project build.gradle

allprojects {
    repositories {
        jcenter()
        **google()**
    }
}

убедитесь, что вы добавили во все проекты

sami qaiser
08 апр. 2018, в 16:56

Поделиться

Я получил эту ошибку после внесения некоторых изменений в классы Room Entity. Поэтому я чувствую, что эта ошибка как-то связана с библиотекой комнаты. Попробуйте отменить изменения в классах и сущностях комнаты или прокомментировать их, чтобы увидеть, исправлена ли ошибка.

В моем случае ошибка появилась, потому что я возвращал int из методов вставки и обновления. Эти методы не должны ничего возвращать. Так что удаление return исправило ошибку.

@Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insert(student: Student):Int

в

@Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insert(student: Student)

Mohsen Hameed
22 март 2019, в 08:51

Поделиться

У меня была такая же проблема. Я отключил привязку данных в свойствах градиента, и это сработало. dataBinding.enabled = false

AbuBakar Sohail
01 апр. 2018, в 23:11

Поделиться

Ещё вопросы

  • 1Динамический вызов Autofac с инъекцией функций и зависимостей
  • 0Лучший анализатор XML с поддержкой запросов / ответов SOAP
  • 0Предотвратить проверку подлинности known_hosts
  • 0Проблема с добавлением двух полиномов, построенных как связанный список c ++
  • 1Как создать сервис Google API с помощью google-auth?
  • 0Динамически переключать панель инструментов с флажком для нескольких идентификаторов?
  • 0Определенный порядок по полю в ng-repeat
  • 0Сброс фильтров столбцов HTML-таблицы по клику
  • 1NodeJs — Выполнение запроса ‘GET’ в цикле while с модулем запроса
  • 1Обновление данных в datagridview и графическом окне одновременно C #
  • 1реагировать родной — Как использовать состояние в конструкторе
  • 1RuntimeError: потоки могут быть запущены только один раз, когда веб-сервер Python Tkinter
  • 1Несколько обещаний JavaScript, приводящих к нулю
  • 1C # Пользовательский тип данных с «выбором»
  • 0MySQL вставка не вставляя предполагаемое значение
  • 0Проверка наличия элемента в стеке
  • 0Как получить AngularJS Форма запроса после отправки запроса
  • 1Как использовать Two ListView на одном экране?
  • 0Фильтр модели backgridjs не скрывает несопоставленные строки
  • 1Избегайте выполнения блоков встроенного кода в ASP.NET
  • 0Как я могу проверить разметку HTML с помощью JavaScript, а затем показать ее предварительный просмотр?
  • 0Блокировка объекта таким образом, что свойства должны быть определены прежде, чем они будут назначены
  • 0производительность mysql MEDIUMTEXT
  • 0Удаление всех идентификаторов в шаблоне HTML
  • 0Javascript добавить ссылку на изображения, которые переключаются по коду
  • 1vcalendar vs icalendar
  • 1Примените тему «Диалог» для Android и правильно определите ее размер
  • 0AWS RDS — автоматическое резервное копирование и снимок с таблицами MyISAM
  • 0PHP / MySQL, обнаруживающий изменение ценового столбца в таблице
  • 0MySQL 5.7.20 — SELECT FOUND_ROWS () возвращает неверный результат
  • 1Проверка JavaScript для Google Forms / Google Sheet
  • 0Как получить доступ к имени пользователя из ng-repeat
  • 0Подход TCP на платформе iOS
  • 0перезагрузка не работает в ионном приложении
  • 0Центрируйте текст вертикально в контейнере с жидкостью
  • 0использование $ (this) для получения атрибута data не возвращает фактический результат
  • 0Подзапрос MySQL в select со ссылкой на внешнее поле
  • 1JS перемещает изображение по экрану и загружает другое в конце
  • 0Область действия ng-click на динамически создаваемой кнопке, не работающей на Google Map
  • 1Отслеживание, когда произошло x событий
  • 0CSS элементы div, наложенные, когда они не должны быть закрыты
  • 0Проверить наличие нового контента с помощью JS / PHP / MySQL?
  • 0Как открыть соединение с MySQL DataBase на другом ПК? [Дубликат]
  • 0Невозможно предоставить событие href или onclick на div
  • 0Как получить доступ к данным из других классов частного внутреннего класса?
  • 0Выполнить несколько команд в функции ShellExecute (C ++)
  • 1Используя HTML5 canvas, как создать бесконечный цикл с временным интервалом
  • 1Редактирование сообщений с использованием discord.js не работает
  • 0если условие внутри программы не работает
  • 0JQuery: нажмите класс реакции

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Found crash report file как исправить
  • Found a number with a magnitude greater than 10 307 как исправить
  • Found 302 error
  • Fossilized error это
  • Fossilized error перевод

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии