android / codelab-android-databinding Goto Github PK
View Code? Open in Web Editor NEWLicense: Apache License 2.0
License: Apache License 2.0
On page 7 we modify popularity from type Popularity
to LiveData<Popularity>
, which causes the build to fail because the PlainOldActivitySolution2
and 3 depend on the older type. The solution ViewModels should connect to a separate solution PlainOldActivity
that we do not touch, thereby preventing the issue.
You can now run the app. You'll see that your name has replaced Ada's.
Where come "Ada" from??
(I'm using downloaded Zip project)
Not high priority as I was incorporating the tutorial into an existing project, not using the base project.
However, Step 7 fails with an error similar to:
Error:Execution failed for task ':app:compileDebugJavaWithJavac'. java.lang.RuntimeException: Found data binding errors. ****/ data binding error ****msg:Cannot find the setter for attribute 'app:hideIfZero'
The solution is adding apply plugin: 'kotlin-kapt'
to the build.gradle
, but this is not mentioned anywhere.
We're going to clean up our layout a bit before we do that."
Hi found this from the google codelabs. Very informative tutorial but i want to know of the tutorial is available in Java also?
I ran into this error when I ran the startup project in the emulator.
2019-07-27 19:37:17.492 7228-7228/com.example.android.databinding.basicsample E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.databinding.basicsample, PID: 7228
java.lang.NoClassDefFoundError: Failed resolution of: Lkotlin/KotlinPackage;
at com.example.android.databinding.basicsample.ui.PlainOldActivity.getAssociatedColor(PlainOldActivity.kt:92)
at com.example.android.databinding.basicsample.ui.PlainOldActivity.updateLikes(PlainOldActivity.kt:82)
at com.example.android.databinding.basicsample.ui.PlainOldActivity.onCreate(PlainOldActivity.kt:50)
at android.app.Activity.performCreate(Activity.java:7802)
at android.app.Activity.performCreate(Activity.java:7791)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3243)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3407)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7343)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:933)
Caused by: java.lang.ClassNotFoundException: Didn't find class "kotlin.KotlinPackage" on path: DexPathList[[zip file "/data/app/com.example.android.databinding.basicsample-EppE11Fq0IMoJt8HZjhWEw==/base.apk"],nativeLibraryDirectories=[/data/app/com.example.android.databinding.basicsample-EppE11Fq0IMoJt8HZjhWEw==/lib/x86, /system/lib, /system/product/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:196)
at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at com.example.android.databinding.basicsample.ui.PlainOldActivity.getAssociatedColor(PlainOldActivity.kt:92)
at com.example.android.databinding.basicsample.ui.PlainOldActivity.updateLikes(PlainOldActivity.kt:82)
at com.example.android.databinding.basicsample.ui.PlainOldActivity.onCreate(PlainOldActivity.kt:50)
at android.app.Activity.performCreate(Activity.java:7802)
at android.app.Activity.performCreate(Activity.java:7791)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3243)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3407)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7343)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:933)
build.gradle - app
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
android {
compileSdkVersion rootProject.compileSdkVersion
defaultConfig {
applicationId "com.example.android.databinding.basicsample"
minSdkVersion rootProject.minSdkVersion
targetSdkVersion rootProject.targetSdkVersion
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables.useSupportLibrary = true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
dataBinding {
enabled true
}
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlinVersion"
implementation "androidx.appcompat:appcompat:$appCompatVersion"
implementation "androidx.constraintlayout:constraintlayout:$constraintLayoutVersion"
implementation "androidx.lifecycle:lifecycle-extensions:$archLifecycleVersion"
testİmplementation "junit:junit:$junitVersion"
testİmplementation "org.hamcrest:hamcrest-all:$hamcrestVersion"
androidTestİmplementation "androidx.test:runner:$androidXTestVersion"
androidTestİmplementation "androidx.test.ext:junit:$runnerExtVersion"
androidTestİmplementation "androidx.test:rules:$androidXTestVersion"
androidTestİmplementation "androidx.test.espresso:espresso-core:$espressoVersion"
}
build.gradle - Project
buildscript {
ext.kotlin_version = '1.3.30'
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.4.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
ext {
// SDK and tools
compileSdkVersion = 28
minSdkVersion = 21
targetSdkVersion = 28
// App dependencies
androidXTestVersion = '1.1.1'
constraintLayoutVersion = '1.1.3'
espressoVersion = '3.1.0-alpha4'
gradleVersion = '3.3.1'
junitVersion = '4.12'
hamcrestVersion = '1.3'
kotlinVersion = '1.3.21'
runnerExtVersion = '1.1.0'
rulesVersion = '1.0.1'
appCompatVersion = '1.0.2'
supportLibraryVersion = '1.0.2'
archLifecycleVersion = '2.1.0-alpha04'
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
In lesson 7 "Observing data" Transformations link opens android.arch docs. Not the androidx.
Need to change the ViewModelProviders with ViewModelProvider as the first one is deprecated.
I'm using project from downloaded zip.
I changed SimpleViewModel.kt and PlainOldActivity and after done page 7, compile error occurs.
SimpleViewModel's members changed to LiveData, but both PlainOldActivitySolution2 and
PlainOldActivitySolution3 using SimpleViewModel's too, so they can't be compiled.
We shouldn't change SimpleViewModel class, create SimpleNewViewModel class (or other) copying from SimpleViewModel, and edit it.
Please notify it to reader.
"As you can see, a LiveData's value is set with the value property, and you can make one LiveData depend on another using Transformations. This mechanism allows the library to update the UI when the value changes."
Should redirect to here
I am trying to setup two way binding for TextInputEditText with Float variable.
Here is the entire content of my DataBindingAdapters class.
object DataBindingAdapters {
@BindingAdapter("android:text")
@JvmStatic
fun setText(view: TextInputEditText, value: Float) {
if(value != view.text.toString().toFloat()) {
view.setText(value.toString())
}
}
@InverseBindingAdapter(attribute = "android:text")
fun getText(view: TextInputEditText): Float {
return view.text.toString().toFloat()
}
}
But I am getting:
error: expected
float callbackArg_0 = mBindingComponent.null.getText(inputFieldSize);
The generated code tries to assign the result of the expression to an int
variable before calling the binding adapter method, which fails with error: incompatible types: possible lossy conversion from long to int
. This should be changed to a long
variable. Here is some code that reproduces this issue.
<View
android:layout_width="match_parent"
android:layout_height="match_parent"
app:animateVisibility="@{viewModel.isVisible}"
app:animationDelay="@{viewModel.isVisible ? 500L : 0L}"
@BindingAdapter("animateVisibility", "animationDelay")
fun View.setAnimatedVisibility(visible: Boolean?, animationDelay: Long?) {
if (animationDelay != null && animationDelay > 0) {
GlobalScope.launch(Dispatchers.Main) {
delay(animationDelay)
setAnimatedVisibility(visible, null)
}
return
}
visibility = View.VISIBLE
val targetAlpha = if (visible == true) 1f else 0f
SpringAnimation(this, DynamicAnimation.ALPHA, targetAlpha).apply {
spring.dampingRatio = SpringForce.DAMPING_RATIO_NO_BOUNCY
addEndListener { _, _, _, _ ->
if (visible != true) {
visibility = View.GONE
}
}
start()
}
}
How to use databinding in android 10 framework compile ?
it seems framework/databinding was removed in some android release version.
is it possible to use databinding in makefile or blueprint build system ?
BindingAdapters.kt
and BindingConverters.kt
in utils
package seem unused and my project works fine after removing theme. Do they still contribute to the project?
I believe that there is no such thing as PlainActivitySolutionBinding in the project.
when i use '&' in my comment, my Android Studio warns "cannot resolve symbol xxx";
example:
// foo.xml
<! --comment with & -->
<LinearLayout id="+id/foo" ...>
// java code:
FooBinding b = DataBindingUtil.setContentView(this, R.layout.foo);
b.foo.setOnClickListener(this); // warning: cannot resolve symbol foo
thx!
"As you can see, a LiveData's value has to be set with setValue()", 'setValue()' is never used in the example code or in the code available in the repo
There are multiple ways to implement observability. You can use observable classes, observable fields, or, the preferred way, LiveData. The full documentation on that is here.
We're going to use ObservableFields as they are simpler.
...
Replace
...
with the new LiveDatas:
Should be a BuildFeature now:
buildFeatures {
dataBinding true
}
I was following the code lab in a different project.
There is no mention you need to apply the Kotlin kapt plugin for Binding Adapters to work.
apply plugin: 'kotlin-kapt' kotlin-kapt
Hi,
Found issue in codelab.
Line binding.lifecycleOwner = this
missed in PlainOldActivity on step 7 (or earlier)
Had to update Gradle version to 6.7.1 and reimport project
Similar to: https://stackoverflow.com/questions/64366729/android-studio-no-build-variant-found-error
We're going to use ObservableFields as they are simpler.
You should update to LiveData from ObservableFields.
I guess that this CodeLab was written before LiveData.
Error thrown while building:
e: java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException
JDK:
openjdk 14.0.2 2020-07-14
OpenJDK Runtime Environment (build 14.0.2+12-Ubuntu-120.04)
OpenJDK 64-Bit Server VM (build 14.0.2+12-Ubuntu-120.04, mixed mode, sharing)
Android Studio version: 4.2 RC1
OS: Ubuntu 20.04.2 LTS
No changes were made to the project. Simply cloning and trying to build as instructed by the Code Lab.
In step 5 the PlainActivitySolutionBinding class is mentioned, but its actually missing from the project's code.
There are multiple ways to implement observability. You can use observable classes, observable fields, or, the preferred way, LiveData. The full documentation on that is here.
We're going to use ObservableFields as they are simpler
But in the next example, Live data is used. So I think there should be changes like this.
We're going to use LiveData as they are simpler.
The example defines the binding adapter:
@BindingAdapter(value = ["app:progressScaled", "android:max"], requireAll = true)
fun setProgress(progressBar: ProgressBar, likes: Int, max: Int) {
progressBar.progress = (likes * max / 5).coerceAtMost(max)
}
If you try to use it like so:
<ProgressBar
android:id="@+id/progressBar"
tools:progressBackgroundTint="@android:color/darker_gray"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="@+id/like_button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="@+id/like_button"
app:layout_constraintEnd_toEndOf="@+id/like_button"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
app:layout_constraintHorizontal_bias="0.5"
app:hideIfZero="@{viewmodel.likes}"
app:progressScaled="@{viewmodel.likes}"
app:progressTint="@{viewmodel.popularity}"
/>
you get the following from a clean build:
.../android-databinding/app/build/generated/source/kapt/debug/com/example/android/databinding/basicsample/DataBinderMapperImpl.java:9: error: cannot find symbol
import com.example.android.databinding.basicsample.databinding.PlainActivityBindingImpl;
^
symbol: class PlainActivityBindingImpl
location: package com.example.android.databinding.basicsample.databinding
Quick, what it the problem? The required attribute android:max
is not present! In contrast if you include android:max
by leave off app:progressScaled
the build succeeds and the binding is simply not applied.
I only changed the project by updated dependencies (including gradle) to current versions.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.