All of sudden I start getting this error, and I am not getting idea why if anyone just let me know where this error is, will be enough helpful. As much I am able to get is this because of new update of android studio.
Detailed summary of error I am getting.
Task :app:kaptDebugKotlin
ANTLR Tool version 4.5.3 used for code generation does not match the current runtime version 4.7.1ANTLR Runtime version 4.5.3 used for parser compilation does not match the current runtime version 4.7.1ANTLR Tool version 4.5.3 used for code generation does not match the current runtime version 4.7.1ANTLR Runtime version 4.5.3 used for parser compilation does not match the current runtime version 4.7.1C:\Users\shubh\Downloads\MarginCalculator\app\build\generated\source\kapt\debug\com\kotlin_developer\margincalculator\DataBinderMapperImpl.java:10: error: cannot find symbol
import com.kotlin_developer.margincalculator.databinding.FragmentCalculatorScreenBindingImpl;
symbol: class FragmentCalculatorScreenBindingImpl
Task :app:kaptDebugKotlin FAILED
location: package com.kotlin_developer.margincalculator.databinding
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:kaptDebugKotlin'.
> A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptExecution
> java.lang.reflect.InvocationTargetException (no error message)
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 17s
29 actionable tasks: 27 executed, 2 up-to-date
Android Studio's UI was just hiding the error...
when the error occurred, it highlighted the item in the list view, and showed an unhelpful message in the terminal view.
to find the real error, select the root item in the list view so that Android Studio would display the whole build output in the terminal view, then scroll to find error.
Maybe I am a bit late for the answer but, anyways, I was getting the same error. The build failure can be caused by some error that Android Studio fails to point out probably due the the project size being very large.
Here is the easy way to point out the exact error.
In Android studio go to Analyze menu and click on Inspect Code; check whole project, click OK and wait for the inspection to finish.
Now you will see a tab that will point all the errors, warnings etc and you can now resolve the real issue.
The way to find out what the underlying issue is, is to run the following command :
./gradlew assembleDebug --stacktrace
Change
implementation "android.arch.persistence.room:runtime:1.1.1"
kapt "android.arch.persistence.room:compiler:1.1.1"
To
(updated 4 - September-2021)
implementation "androidx.room:room-runtime:2.3.0"
annotationProcessor "androidx.room:room-compiler:2.3.0"
I started getting this after upgrading my Android Studio to Arctic Fox(2020.3.1).
I resolved it by updating my JDK version from 1.8 to Embedded JDK.
To change the JDK:
Open your project in Android Studio and select File > Settings... > Build, Execution, Deployment > Build Tools > Gradle
On Mac: Android Studio > Preferences... > Build, Execution, Deployment > Build Tools > Gradle.
Under Gradle JDK, choose the Embedded JDK option.
As mentioned here
Click on --stacktrace on the terminal to see the error in details. You can find it here:
M1 Chip Solution
If you have a MacBook Pro chances are that adding kapt "org.xerial:sqlite-jdbc:3.34.0" before the room-compiler will solve your problem.
kapt "org.xerial:sqlite-jdbc:3.36.0" // Only for computer with M1 CPU
implementation("androidx.room:room-ktx:$room_version")
kapt "androidx.room:room-compiler:$room_version"
See more here.
I got the same issue, so I tried to get more information, by doing
gradle->app->Tasks->Build->assemble
After this I got exact error saying "Error while annotation processing".
I checked my recently tweaked DAO class and found that one of the method return type was not defined.
//Before
#Query("SELECT countryName FROM country_table WHERE countryCode= :code")
fun getCountryNameForCode(code: String)
//After
#Query("SELECT countryName FROM country_table WHERE countryCode= :code")
fun getCountryNameForCode(code: String): String
I had the same error for a while then I started checking the other packages I came to know that I've made a typo mistake in my database code. So,
"Go through your database and other activity class files u may find some mistakes there."
After a lot of pain, I decided to try annotationProcessor instead of kapt hoping it may at least show an error message or anything that can help me locate the source. But fortunately (or unfortunately; because of the wasted time), it was built successfully without any errors.
It's mostly a bug in kapt itself. So, try this solution and it may help.
For me, a bunch of reference errors and an error in the XML expressions with DataBinding produced this error.
I have deleted a <variable/> in a layout file, because I thought, I don't need it anymore. I forgot that I had the variable referenced in the layout file.
After building the project, this produced an error, where it was not possible to import the BindingImpl class, because it does not exist and this error was only shown as a warning parallel to the above KaptExecution error.
After searching for a while, I found this error and resolved it. Then, a bunch of reference errors where shown, because I renamed something and it did not rename it in the Fragment files. After resolving these errors too, the build finished for me without errors or warnings.
Okay, this issue also occurs if you are using Android Studio 4.1.2.
So, what you have to do is:
Download jdk 11 (Search and download)
In Android Studio, go to File -> Project Structure -> Jdk Location -> Change to the path of the Jdk you just downloaded.
try to build your project with
kapt.use.worker.api=false
in your gradle.properties settings file
Reference: https://youtrack.jetbrains.com/issue/KT-40750
The same problem for me here. In my case, the reason is that I've forgot a #Module annotation in one of my dagger module.
To find the real problem of such an AS alert, it's necessary going deep: the messagge in the title it's only the final one, the 1 or more causes of the error are shown selecting the root element on the left, that shows you the exact problems, check my printscreen below :
I had the same problem. In my case the problem was about Database. i had to change this line of code
#Database(entities = [SearchedLocation::class, FavoriteLocation::class], version = 1)
I added another table in Database but forgot to add table in the line above.
I had the same problem. Let me walk you through the example on how I ended up to the problem and the way I resolved it perhaps you can get a bigger picture.
Before resolving
#Entity(tableName = "modules")
data class Module
(
#PrimaryKey val id: Int,
val name: String
)
#Entity(tableName = "sessions")
data class Session
(
#PrimaryKey(autoGenerate = true) var id: Int,
#ColumnInfo(name = "module_id") val moduleId: Int,
#ColumnInfo(name = "start_time") val startTime: String,
#ColumnInfo(name = "end_time") val endTime: String
)
data class ModuleSession
(
#Embedded val module: Module,
#Relation(
parentColumn = "id",
entityColumn = "module_id"
)
val sessions: List<Session>,
#ColumnInfo(name = "is_updated") val isUpdated: Boolean = false // The problem
)
In the DAO
#Transaction
#Query("SELECT * FROM modules")
abstract suspend fun getModuleSession(): List<ModuleSession>
The error I got was
A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptExecution
So I dug deeper and found the below message
The columns returned by the query does not have the fields [isUpdated] in com.gmanix.oncampusprototype.Persistence.ModuleSession even though they are annotated as non-null or primitive. Columns returned by the query: [id,name]
public abstract java.lang.Object getModuleSession(#org.jetbrains.annotations.NotNull()
I removed the field IsUpdated from the POJO ModuleSession and added it to the session table
After changes
#Entity(tableName = "sessions")
data class Session
(
#PrimaryKey(autoGenerate = true) var id: Int,
#ColumnInfo(name = "module_id") val moduleId: Int,
#ColumnInfo(name = "start_time") val startTime: String,
#ColumnInfo(name = "end_time") val endTime: String,
#ColumnInfo(name = "is_updated") val isUpdated: Boolean = false
)
data class ModuleSession
(
#Embedded val module: Module,
#Relation(
parentColumn = "id",
entityColumn = "module_id"
)
val sessions: List<Session>
)
On the other hand crosscheck if there is any field on the SELECT statement that is a suspect causing issues or you can annotate it with #Ignore
However you can post your code if you're still not comfortable.
I hope that might help
In my case I forget adding #PrimaryKey in Entity class.
In my case I got this error when moving from jcenter() to mavenCentral(), one of my dependencies was available only on jcenter() and not mavenCentral().
So i submitted issue to the owner for the same on github and will wait to remove jcenter() until its moved.
I got the same problem when I added ROOM to my App(Kotlin).
I had a hard time finding out what was wrong and finally figured out that i was using the following for adding ROOM to my app.
//room
implementation 'android.arch.persistence.room:runtime:1.1.1'
kapt "android.arch.persistence.room:compiler:1.1.1"
So i changed the above two lines with the following and got rid of the pain.
def room_version = "2.2.6"
implementation "androidx.room:room-runtime:$room_version"
kapt "androidx.room:room-compiler:$room_version"
Hit the up button if it helped you :D
If you have upgraded to classpath 'com.android.tools.build:gradle:4.0.0'
Replace it previous version
dependencies {
classpath 'com.android.tools.build:gradle:3.6.3'
}
And Change gradle-wrapper.properties
distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4- all.zip`
In my case, I used room and one of my databasDao methods has an unused parameter and unfortunately android studio doesn't warn me correctly
This problem also happens if you installed new kotlin plugin (1.4.20-release-Studio4.1-1) and have dagger (kapt 'com.google.dagger:dagger-compiler:2.30'). In such a case one solution might be replacing deprecated plugin: 'kotlin-android-extensions' with view binding (https://developer.android.com/topic/libraries/view-binding)
Looks like there is an issue with room library and apple M1 chips.
Update your room lib version to 2.4.0-alpha03 or above and resync project.
Worked for me!
In my case there were older dependencies which needed an upgradation,
So you can follow this :
1.FILE -> PROJECT STRUCTURE ->
2.Go to SUGGESSIONS ->
3.Under the WARNING SECTION Android Studio will show you which dependencies
needs to be upgraded->
4.Just upgrade it directly from there ->
5.CLICK APPLY->
It will work now!
Thanks!
In my case I was using Coroutines but I forget to add Kotlin Extensions and Coroutines support for Room
def room_version = "2.2.6"
implementation "androidx.room:room-ktx:$room_version"
In my case adding new fragments always resulted in this error popping up, I investigated my commit changes on git and it turns out that Android keeps auto-updating the gradle plugin whenever I create a new Fragment despite not giving it permissions to do so, so I had to rollback to my original gradle-plugin version inside the project level's build.gradle file:
from
classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.7.0'
to
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.21"
Monitor your git changes to figure out what Android is doing to your gradle files that's causing it to crash.
Shout Out to #Rene Spies' answer above, I also got this error while working with databinding. It turns out the build engine doesn't like it when you put the #Bindable annotation on a field in the primary constructor of a data class in Kotlin.
So never do the following,
data class MyAwesomePojo(
#Bindable
var firstname: String,
var lastname: String
)
instead what you need to do is
data class MyCorrectAwesomePojo(
var lastname: String
):{
#get:Bindable
var firstname: String
set(value){
field = value
}
}
Bonus: remember to check for same values before setting value to field if you are trying to use two-way binding like me to prevent infinite looping of setting and getting.
In my case it was because I was not implementing Observable in my ViewModel. I added an EditText to the constraint layout with android:text="#={addProductViewModel.inputProductName}"
Once I implemented Observable in my ViewModel class the error was gone
ViewModel
class AddProductViewModel (
private val repository: ProductRepository,
private val context: Context
): ViewModel(), Observable {
#Bindable
val inputProductName = MutableLiveData<String>()
fun addProduct() {
//inputProductName.value
}
override fun removeOnPropertyChangedCallback(callback: Observable.OnPropertyChangedCallback?) {
TODO("Not yet implemented")
}
override fun addOnPropertyChangedCallback(callback: Observable.OnPropertyChangedCallback?) {
TODO("Not yet implemented")
}
}
Complete example for MVVM Databinding using Fragments
Layout - add_product.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android" >
<data class=".AddProductBinding">
<variable
name="addProductViewModel"
type="com.rao.iremind.AddProductViewModel" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="#+id/editTextTextProductName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Product name"
android:inputType="textPersonName"
android:text="#={addProductViewModel.inputProductName}"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
AddProductFragment
class AddProductFragment: Fragment() {
private lateinit var binding: AddProductBinding
private lateinit var addProductViewModel: AddProductViewModel
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = DataBindingUtil.inflate(inflater, R.layout.add_product, container, false)
val dao = SubscriberDatabase.getInstance(requireActivity().applicationContext).productDAO
val repository = ProductRepository(dao)
val factory = AddProductViewModelFactory(repository, requireActivity().applicationContext)
addProductViewModel = ViewModelProvider(this, factory).get(AddProductViewModel::class.java)
binding.addProductViewModel = addProductViewModel
binding.lifecycleOwner = this
val view = binding.root
return view
}
}
AddProductViewModel
class AddProductViewModel (
private val repository: ProductRepository,
private val context: Context
): ViewModel(), Observable {
#Bindable
val inputProductName = MutableLiveData<String>()
fun addProduct() {
//inputProductName.value
}
override fun removeOnPropertyChangedCallback(callback: Observable.OnPropertyChangedCallback?) {
TODO("Not yet implemented")
}
override fun addOnPropertyChangedCallback(callback: Observable.OnPropertyChangedCallback?) {
TODO("Not yet implemented")
}
}
Hope this helps
R
In My Case: Issue resolved
Steps:
Remove viewModel variable - In XML.
<variable
name="viewModel"
type="com.xx.AppViewModel" / >
Removed all viewModel binding references - In XML.
android:text="#{viewModel.simName}"
Removed viewModel instance reference to the binding mapping - In Activity
binding.viewModel = viewModel
Clean project and recompile.
Add viewModel variable - In XML & Build project.
< variable
name="viewModel"
type="com.xx.AppViewModel" / >
Add viewModel instance reference to the binding mapping - In Activity & Build project
binding.viewModel = viewModel
Add all viewModel binding references - In XML & Build project..
android:text="#{viewModel.simName}"
It will work now.
-- I hope it will work for you also.
I had same problem with Room and i was not using viewBinding.
I Fixed it with using exportSchema to false in my database class.
#Database(entities = [ModelClass::class], version = 1, exportSchema = false)
abstract class ModelDatabase: RoomDatabase() {}
Remember: exportScehma could be vary according to your use case, generally it stays false so i put it to false.
In my case I have changed globally one variable UserManager to NetWorkManager and everywhere where there were UserManager classes they turned to be NetworkManager.
Because I'm using Hilt, I had to build the project again.
I cleaned the Project and Kotlin showed where the errors were.
Related
[Using Gradle 4.0.0], I try to implement local storage by room in Android Kotlin in Andriod Studio 4.
When I try to build project, i meet an error in build console
A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptExecution
Image:
Gradle:
apply plugin: 'kotlin-kapt'
implementation "androidx.room:room-runtime:$room_version"
kapt "androidx.room:room-compiler:$room_version"
Please kindly help to show the solution for me
Android Studio's UI was just hiding the error...
when the error occurred, it highlighted the item in the list view, and showed an unhelpful message in the terminal view.
to find the real error, select the root item in the list view so that Android Studio would display the whole build output in the terminal view, then scroll to find error.
The error is show by the kapt in your project, and to show full error message you will have to add these to your gradle.properties file.
kapt.use.worker.api=false
kapt.incremental.apt=false
After that run your app again, and try to read from the detailed error.
Verify your DAO, make sure everything is where it is supposed to be.
4/5 when I get this error, I find out I miswrote/forgot something somewhere with the dao
I was getting the same error, when i was trying to retrieve all the columns from db with return type of LiveData array list(Dao file), eg: return type was -
LiveData<ArrayList<Book>>
And when i change ArrayList to list like this: LiveData<List<Book>>
Although i'm not sure about the cause or reason for the error,
the above chnages worked for me
also,
If you are using coroutines, check the room dependency for room-ktx
If you have Hilt in your project with Kotlin, make sure you have annotated your module class with:
#Module
#InstallIn(SingletonComponent::class)
I was getting an error because I haven't mentioned the my DAO() class
#Database(entities = [Products::class], version = 1, exportSchema = false)
abstract class LocalDatabase : RoomDatabase(){
abstract fun productDao(): ProductDao() // I missed this line
companion object{
#Volatile
private var INSTANCE :LocalDatabase ?=null
fun getDatabase(context: Context):LocalDatabase{
val tempInstance = INSTANCE
if (tempInstance != null)
return tempInstance
synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
LocalDatabase::class.java,
"Zenex"
).build()
INSTANCE = instance
return instance
}
}
}
override fun createOpenHelper(config: DatabaseConfiguration?): SupportSQLiteOpenHelper {
TODO("Not yet implemented")
}
override fun createInvalidationTracker(): InvalidationTracker {
TODO("Not yet implemented")
}
override fun clearAllTables() {
}
}
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.
I implemented Jacoco in my Android project using the following tutorial https://proandroiddev.com/unified-code-coverage-for-android-revisited-44789c9b722f to cater for test coverage in the kotlin classes.
For some unknown reason, it's not reporting coverage for static methods declared under the Companion block.
class Meh {
companion object {
fun test () {
// logic to test
}
}
However if I convert the class to an instance rather than a singleton that I am able to see the coverage completely fine.
Has anyone came across this problem ? and what did you do ?
following tutorial https://proandroiddev.com/unified-code-coverage-for-android-revisited-44789c9b722f
after cloning of example from the same tutorial in its state as of today (HEAD commit)
git clone https://github.com/rafaeltoledo/unified-code-coverage-android.git
cd unified-code-coverage-android
git checkout kotlin-coverage
addition of companion object into MainActivity
class MainActivity : AppCompatActivity() {
+ companion object {
+ fun executed() {
+ }
+
+ fun notExecuted() {
+ }
+ }
+
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
+ executed()
start of virtual device Pixel XL with API 28 and target Android 9.0 (Google APIs) in freshly downloaded Android Studio 3.2.1
and execution of
./gradlew jacocoTestReport
following report is produced in directory app/build/reports/jacoco/jacocoTestReport/html/ as expected
Given the amount of factors that influence result (such as versions of all involved components - Android SDK, Device, Kotlin compiler, Gradle, JaCoCo, etc, etc), attempts to guess what is different in your case are IMO counterproductive, and so that the best advice - is to perform very careful comparison of differences between your setup and above example.
Update
As was figured out during comparison by #HeWhoProtects , problem was in
exclusion of **/*$*
that refers to exclusion of class files from analysis. Single source file can compile into multiple class files, e.g. in case of nested classes in Java and exactly in case of companion in Kotlin and in both cases name of class and class file will contain $.
I found the the cause of the problem but not sure why it caused it yet, my excludes rules includes more rules than the one in the tutorial above, in different jacoco tutorial for ignoring autogenerated files, it was suggested to include '**/*$*' as rule, as soon as I removed it, it showed coverage for static methods in kotlin.
My understanding of Jacoco that these rules ignore files and will not show it in the report, and before I made the change, it was showing that this class is covered in the test coverage.... is it weird or am I missing a fundamental thing about how kotlin generates methods or how jacoco excludes rules work ?
Anyway I hope this helps..
I am currently trying to write a custom lint check that I am working on. I have created a separate java project and included it as a jar.
My problem is that no matter what, it seems that my custom check is not being run when analyzing my code base.
I've included a registry
class MyIssueRegistry : IssueRegistry() {
override val issues: List<Issue>
get() = listOf(MyIssues.ISSUE_PATTERN)
}
And a detector
class MyIssueDetector : Detector(), Detector.UastScanner {
override fun getApplicableUastTypes() = listOf(UClass::class.java)
override fun createUastHandler(context: JavaContext) =
MyIssueDetector(context)
class MyIssueDetector(private val context: JavaContext) : UElementHandler() {
override fun visitClass(node: UClass) {
context.report(MyIssues.ISSUE_PATTERN, context.getNameLocation(node), "This is just a test")
}
}
}
I've also added attributes("Lint-Registry-v2": "com.pathto.lint.MyIssueRegistry") to my java project's gradle and included it in my app gradle as lintChecks project(":lint")
AFAIK this topic- My code should be throwing a warning everytime it reads a class, but the lint check is not being ran. Is there a step I am missing?
first, check your lint.jar is placed on the right path. my path is ~/.android/lint/lint.jar.
then execute command '$ANDROID_HOME/tools/bin/lint --show | grep 'your issue name'' to check your custom lint is attached or not.
and then you can put some log to your custom lint implementation just like using "System.out.println()"
hope this can help u.
I'm trying to use AndroidAnnotations #SharefPref within kotlin, but Iget following error
org.androidannotations.annotations.sharedpreferences.Pref can only be used on an element that extends org.androidannotations.api.sharedpreferences.SharedPreferencesHelper
What am I doing wrong?
//Interface
#SharedPref(SharedPref.Scope.APPLICATION_DEFAULT)
open interface MyPreferences {
#DefaultInt(-1)
fun someIntValue():Int
}
//Fragment
#Pref
lateinit open var sharedPref:CongressPreferences_
//usage within fragment
val get: Int = sharedPref.selectedEventId().get()
This is due to a bug in the Kotlin annotation processor.
To fix this, you must add correctErrorTypes = true to your kapt block.
kapt {
correctErrorTypes = true
}
Also make sure you are using the latest Kotlin version (as of this moment: 1.1.3).
I just wanna extend on #WonderCsabo 's answer.
His answer almost saved me, but not fully.
After adding this to my app label build gradle.
kapt {
correctErrorTypes = true
}
I wasn't able to run my app.
Then I closed my android studio and then run Android studio again as administrator.
Voila! it works like charm.
Thank you #WonderCsabo