Room annotation processor with Data binding - android

I have used Data binding in my existing code and now I am migrating to Room for persistence.
I have followed the steps mentioned in Florina's Blog for room
My Code builds fine without java code error or BR related error when I remove room dependency
annotationProcessor 'android.arch.persistence.room:compiler:1.0.0'
and its runs too, but gives Runtime exception saying database_Impl does not exists. As it couldn't generate that's file.
But after I put Annotation processor back, it give me
Error:(29, 37) error: cannot find symbol class BR
My gradle plugin used is com.android.tools.build:gradle:3.0.1
They both don't seem to work together
Steps taken so far:
Changed BaseObservable to Observable As suggested here
Updated Android Studio to 3.0.1
Tried using gradle latest plugin canary 6
Clear, Clear Cache also done
Has anyone used Room and Data binding together ?

After 4 days of efforts I finally made my code run properly.
Steps to solve the
Data binding error like
error: package com.packagename.databinding does not exist
error: cannot find symbol class CustomMainActivityBinding
The app gradle must have below code added in order to view more than 100 errors that come by default
allprojects {
gradle.projectsEvaluated {
tasks.withType(JavaCompile) {
options.compilerArgs << "-Xmaxerrs" << "4000"
options.compilerArgs << "-Xmaxwarns" << "4000"
}
}
}
Gradle dependencies for data binding and Room arch components
annotationProcessor 'com.android.databinding:compiler:3.0.1'
implementation 'android.arch.lifecycle:extensions:1.0.0'
implementation 'android.arch.persistence.room:runtime:1.0.0'
annotationProcessor 'android.arch.lifecycle:compiler:1.0.0'
annotationProcessor 'android.arch.persistence.room:compiler:1.0.0'
Note: Gradle plugin version is 3.0.1
I changed my all VMs to implement Observable and call
registry.notifyChange(this, BR.bar);
in case of notify change and also implement overridden methods
#Override
public void addOnPropertyChangedCallback(OnPropertyChangedCallback
callback) {
registry.add(callback);
}
#Override
public void removeOnPropertyChangedCallback(
OnPropertyChangedCallback callback) {
registry.remove(callback);
}
These things made my code Build, but it run without exceptions when I solved the Room query related errors. Which was the main reason, code was building but not running. These errors I could see when I Rebuid my project again.
UPDATE:
After Android studio 3.1.3, Message window is gone and now all build error appears under Build view. Although there is toggle available to get textview response of error, for data-binding errors it isn't sufficient.
Solution that helped me:
In Command promt/Terminal navigate to project root.
Run this command "./gradlew build --stacktrace" if Mac or ".\gradlew
build --stacktrace" if Windows.
Now search for "error:" tag and the compile time errors will show up.
I couldn't get these errors in IDE.

In my experience, the following reasons may cause the error:
Incorrect getter/setter (missing or incorrect name)
Incorrect return type in Dao
annotationProcessor or kapt issues
The default constructor is overridden (you need to keep the empty constructor for Room)

I faced this issue while adding room dependencies. Add this in the below way to resolve the error.
def roomVersion = "2.0.0-rc01"
implementation "android.arch.persistence.room:runtime:$roomVersion"
annotationProcessor "android.arch.persistence.room:runtime:$roomVersion"
annotationProcessor "android.arch.persistence.room:compiler:$roomVersion"

Related

Realm error when adding Compose library to the project

I am trying to add Jetpack Compose but the app crashes at launch when installed over a version without Compose with the following error logs:
E/[Koin]: Instance creation error : could not create instance for [Factory:'AppWidgetRealmDataSource']: io.realm.exceptions.RealmMigrationNeededException: Migration is required due to the following errors:
- Property 'MyFirstRealmTable.$stable' has been removed.
- Property 'MySecondRealmTable.$stable' has been removed.
- ...
- Property 'MyLastRealmTable.$stable' has been removed.
The app works just fine when it is installed for the first time.
The exception is thrown only if a previous version of the application without Compose was already installed.
Of course there were no changes in Realm tables in the version with Compose. So no Realm migration should be expected here.
The only thing I did is adding the Compose dependencies as stated in the Android docs :
buildFeatures {
compose true
}
composeOptions {
kotlinCompilerExtensionVersion '1.3.0'
}
dependencies {
implementation 'androidx.activity:activity-compose:1.5.1'
implementation 'androidx.compose.material:material:1.2.1'
implementation 'androidx.compose.animation:animation:1.2.1'
implementation 'androidx.compose.ui:ui-tooling:1.2.1'
implementation 'androidx.lifecycle:lifecycle-viewmodel-compose:2.5.1'
androidTestImplementation 'androidx.compose.ui:ui-test-junit4:1.2.1'
}
There is no error at compile time, only at run time.
Furthermore, when I remove compose true the app does not crash.
I really do not know what I am doing wrong and why a Realm error is thrown when I add Compose as the 2 libraries are not related at all.
I am using this for Realm: io.realm:realm-gradle-plugin:10.10.1.
Thanks

android material design sample code giving missing resources errors

I am trying to run android material design same taken from below https://github.com/material-components/material-components-android
but getting these errors :
failed
:lib:packageDebugResources
tokens.xml
Can't determine type for tag '<macro name="m3_comp_bottom_app_bar_container_color">?attr/colorSurface</macro>'
tokens.xml
Can't determine type for tag '<macro name="m3_sys_color_dark_surface_tint">?attr/colorPrimary</macro>'
fab_tokens.xml
Can't determine type for tag '<macro name="m3_comp_fab_primary_container_color">?attr/colorPrimaryContainer</macro>'
tokens.xml
Can't determine type for tag '<macro name="m3_comp_switch_selected_icon_color">?attr/colorOnPrimaryContainer</macro>'
tokens.xml
Can't determine type for tag '<macro name="m3_sys_motion_path">linear</macro>'
tokens.xml
Can't determine type for tag '<macro name="m3_sys_shape_corner_full_family">rounded</macro>'
tokens.xml
Can't determine type for tag '<macro name="m3_ref_typeface_brand_regular">sans-serif</macro>'
/Users/mac/AndroidStudioProjects/material-components-android/lib/java/com/google/android/material/bottomappbar/res/values/tokens.xml: Error: Can't determine type for tag '<macro name="m3_comp_bottom_app_bar_container_color">?attr/colorSurface</macro>'
I got the same error when upgrade to this version
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.8.0-alpha01'
But working fine in
implementation 'androidx.appcompat:appcompat:1.4.1'
implementation 'com.google.android.material:material:1.6.0'
Problem is solve after using current version of android studio ( updated from 4.2 to 2021.2.1 and used recommended gradle plugin )
Got the below reply from github when i open defect for same
"The error message you attached says not recognizing resource tag, which requires AGP 7.2. You must use a version later than 1.7.0-alpha02, please make sure your app build with the minimum required plugin versions."
updating the Android Gradle plugin to 7.3.3 (gradle-7.3.3-bin.zip)
things will be ok.
Replace :
implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.7.0'
with:
implementation 'androidx.appcompat:appcompat:1.4.1'
implementation 'com.google.android.material:material:1.6.0'
in build.gradle(:app) file under dependencies { }
Try downgrading material design library in build.gradle(app).
I have changed
implementation 'com.google.android.material:material:1.7.0'
to
implementation 'com.google.android.material:material:1.6.0'
And this resolved my issue.
This issue should be relevant to people who dig deeper and do not directly work with these dependencies, as it works fine for building and running apps in Android Studio.
It seems that material 1.7.0 is using illegal tag <macro>, you can see it in multiple files when looking through their release changes, specifically the **/tokens.xmlfiles. I could not find any information about this tag in AGP documentation and the only references to it I found from this git repo was this part of the code
private fun parseMacro(
element: StartElement, eventReader: XMLEventReader, parsedResource: ParsedResource): Boolean {
...
// Macros can only be defined in the default config
val defaultConfig = ConfigDescription()
if (parsedResource.config != defaultConfig) {
logError(
blameSource(source, element.location),
"<macro> tags cannot be declared in configurations other than the default configuration")
return false
}
So I'm not really sure how did they work around it.
In the future it is possible that AGP will support this tag externally and include it in their documentation, but for now you'll have to use workarounds

Dagger not see my own generated dependency

I have an issue with Dagger and my own generated code.
Assumptions:
I need to generate my own dagger component for UI tests purpose
I have my own Gradle's module for annotation processing which provides dagger component with dependencies. Call this GeneratedTestCoreComponent. This class is generated correctly
GeneratedTestCoreComponent is built at \build\generated\source\kapt\debug\...
GeneratedTestCoreComponent is used in dagger component, smth like this
#Component(modules = [UiTestModule::class],
dependencies = [GeneratedTestCoreComponent::class])
interface TestUiComponent {}
My annotation processor module is correctly added to gradle
implementation project(path: ':processor')
kapt(name: 'processor')
The issue is. During compilation I get below error
TestUiComponent.java:6: error: cannot find symbol
#com.dagger.Component(modules = {com.xxx.xxx.UiTestModule.class}, dependencies = {GeneratedTestCoreComponent.class})
symbol: class GeneratedTestCoreComponent
TestUiComponent.java:8: error: [ComponentProcessor:MiscError] com.dagger.internal.codegen.ComponentProcessor was unable to process this interface because not all of its dependencies could be resolved. Check for compilation errors or a circular dependency with generated code.
public abstract interface TestUiComponent
Additional info.
When I copy GeneratedTestCoreComponent class from build directory to src (keeping the same package) and disable my processor, then everything works fine
Try changing kapt(name: 'processor') into kapt project(':processor')

Note: Failed to read get kotlin metadata for [Ljava.lang.Object;#79d6c4df

I keep getting this error.
I am working on a project and in the middle of development, I decided to migrate to Android X.
I get the error below:
Note: Failed to read get kotlin metadata for [Ljava.lang.Object;#79d6c4df
There is the same error in a entity file and 4 of the same error in the respective DAO as well.
Here is the code of DAO:
#Dao
public interface FlockDao{
#Query("SELECT * FROM flock_table")
LiveData<List<Flock>> getAllFlocks();
#Query("SELECT * FROM flock_table WHERE fid IN (:flockIds) LIMIT 1")
Flock loadFlockById(int[] flockIds);
#Insert
void insert(Flock flock);
#Update
void update(Flock flock);
#Delete
void delete(Flock flock);
}
And my entity is:
#Entity
public class Flock{
#PrimaryKey(autoGenerate = true)
private int fid;
#ColumnInfo(name = "user_id")
private int uid;
#ColumnInfo(name = "name")
private String name;
#ColumnInfo(name = "capacity")
private int capacity;
#ColumnInfo(name = "type")
private String type;
#ColumnInfo(name = "arrived")
private Date arrived;
.....rest of the code is omitted, there are constructor, setters and getters
}
I updated my Room depency to 2.1.0-alpha05 and got the same problem. Returning to 2.1.0-alpha04 solved mine.
implementation 'androidx.room:room-runtime:2.1.0-alpha04'
annotationProcessor 'androidx.room:room-compiler:2.1.0-alpha04'
UPDATE
If you really want to use Room version 2.1.0-alpha05, add the following depency to your project repository:
maven { url 'https://kotlin.bintray.com/kotlinx/' }
Reference: AndroidX Room Release Notes
UPDATE
I tried 2.1.0-alpha06.
implementation 'androidx.room:room-runtime:2.1.0-alpha06'
annotationProcessor 'androidx.room:room-compiler:2.1.0-alpha06'
Then I add the depency to my project repository,
maven { url 'https://kotlin.bintray.com/kotlinx/' }
There was na error but it compiled. I tested my app in real device for weeks and there wasn’t any issue running my app. My Room database is working fine.
I solved this issue by downgrading to:
implementation 'androidx.room:room-runtime:2.1.0-alpha04'
annotationProcessor 'androidx.room:room-compiler:2.1.0-alpha04'
Solved!
//Downgraded to alpha04.
implementation 'androidx.room:room-runtime:2.1.0-alpha04'
annotationProcessor 'androidx.room:room-compiler:2.1.0-alpha04'
// Other dependencies are..
implementation 'androidx.lifecycle:lifecycle-extensions:2.1.0-alpha03'
implementation 'androidx.lifecycle:lifecycle-viewmodel:2.1.0-alpha03'
implementation 'androidx.lifecycle:lifecycle-livedata:2.1.0-alpha03'
annotationProcessor 'androidx.lifecycle:lifecycle-compiler:2.1.0-alpha03'
// Removed this from project level gradle.
maven { url "https://kotlin.bintray.com/kotlinx/" }
Don't forget to Clean & Rebuild the project after these changes
Like most errors that have something to do with Room, the error message that pops up the most is most unlikely to be your problem. For me it helped to raise the max Error count by adding :
gradle.projectsEvaluated {
tasks.withType(JavaCompile) {
options.compilerArgs << "-Xmaxerrs" << "1000"
}
}
and then executing the gradle task:
:app compileDebugJavaWithJavac
Then you will get a large list of errors, in your case the
Note: Failed to read get kotlin metadata for [Ljava.lang.Object;#79d6c4df
But somewhere in that list are your real errors like a wrong query or something like that.
Fix those errors and rebuild the project, that works most of the time, but sometimes you have to invalidate the cache and restart Android Studio.
Invalidate caches and restart solved my problem. My room version is 2.1.0-alpha06 and I have also add the following dependency to my project repository:
maven { url 'https://kotlin.bintray.com/kotlinx/' }
I got the same error, I updated the room libraries, but issue not fixed,
then I did below steps, ... after that problem solved,
Step 1: Check #DataBase class in your project and check all tables (entities) are inserted
Step 2: Increment version number
Step 3: Add ".fallbackToDestructiveMigration()" before .build().
Don't forget to Clean & Rebuild the project after these changes
As I was typing this answer, I was notified of 2.1.0-alpha07. It resolved all errors. Going back to 2.1.0-alpha06 broke the build again.
It turns out the new version resolved the errors for me.
Before trying to resolve the error, try updating Android Studio first. After updating Gradle, all dependencies, and AS from 3.3.2 to 3.4, I found errors I haven't encountered before, like
error: Room cannot pick a constructor since multiple constructors are suitable. Try to annotate unwanted constructors with #Ignore.
error: Cannot find setter for field.
There are multiple good constructors and Room will pick the no-arg constructor. You can use the #Ignore annotation to eliminate unwanted constructors.
error: Not sure how to convert a Cursor to this method's return type.
Once I fixed them, the build was successful and the app ran. I didn't need to add any additional maven repos mentioned in the accepted answer.
Adding import androidx.room.Dao; and then re-importing it did the trick for me.
I solved by adding this to build.gradle (Module)
androidTestImplementation "androidx.arch.core:coretesting:$rootProject.archLifecycleVersion"
In my build.gradle(Project)
ext {
roomVersion = '2.1.0-alpha06'
archLifecycleVersion = '2.0.0'
}
Just change room_version in your gradle_module file in dependency block and change other room associated libraries you need. Use https://developer.android.com/jetpack/androidx/releases/room#2.2.0-alpha01 as an example. Try to use latest stable version of room.
I have the same error and i used version 2.1.x-alpha
and after updated to 2.2.3
the new version reported the error correctly and it was that one of my entities didn't have primary key
I came across the same problem and fixed it by override the equals & hashCode methods of the object.
A possible solution for your case:
#Override
public int hashCode() { return (27 * fid + (name!= null ? name.hashCode() : 0)); }
And
#Override
public boolean equals(#Nullable Object obj) {
if (this == obj) return true;
if (!(obj instanceof Flock)) return false;
Flock flock = (Flock) obj;
if(fid != flock.fid) return false;
return name != null ? name.equals(flock.name) : flock.name == null;
}
you will also need find a solution for the Date usage in Room, Room doesn't have a build in solution for a Date variable.

NanoHTTPD - unable to add gradle dependency

I am trying to add NanoHTTPD to my Android project.
As mentioned in README.md, I added
dependencies {
runtime(
[group: 'org.nanohttpd', name: 'nanohttpd', version: '2.3.1'],
)
}
it is giving error:
Could not find method runtime() for arguments [{group=org.nanohttpd, name=nanohttpd, version=2.3.1}] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.
I also tried adding
repositories {
mavenCentral()
}
mentioned elsewhere, but same error.
I tried the usual way:
implementation 'org.nanohttpd.nanohttpd:2.3.1'
it gives error:
Failed to resolve: org.nanohttpd.nanohttpd:2.3.1:
I am using Android Studio 3.2.1
There seem to be so many people happily using it in Android. What am I missing?
In your gradle file, separate group and artifact ids with a : instead of .. That is, replace
implementation 'org.nanohttpd.nanohttpd:2.3.1'
with
implementation 'org.nanohttpd:nanohttpd:2.3.1'

Categories

Resources