I am trying to implement room database, I have gone through steps on Official Website, and 'AppDatabase.java' file is like this:
import android.content.Context;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
#Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
public static AppDatabase instance;
public static synchronized AppDatabase getInstance(Context context){
if (instance==null){
instance = Room.databaseBuilder(context.getApplicationContext(),
AppDatabase.class, "app_database").fallbackToDestructiveMigration().build();
}
return instance;
}
}
And dependencies I have used for room:
// Room Database
def room_version = "2.4.2"
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"
// optional - RxJava2 support for Room
implementation "androidx.room:room-rxjava2:$room_version"
// optional - RxJava3 support for Room
implementation "androidx.room:room-rxjava3:$room_version"
// optional - Guava support for Room, including Optional and ListenableFuture
implementation "androidx.room:room-guava:$room_version"
// optional - Test helpers
testImplementation "androidx.room:room-testing:$room_version"
// optional - Paging 3 Integration
implementation "androidx.room:room-paging:2.5.0-alpha02"
// Room Database
It returns 2 errors here:
onCreate(SupportSQLiteDatabase) in <anonymous com.example.testdb1.room.AppDatabase_Impl$1> cannot override onCreate(SupportSQLiteDatabase) in Delegate
attempting to assign weaker access privileges; was public
onValidateSchema(SupportSQLiteDatabase) in <anonymous com.example.testdb1.room.AppDatabase_Impl$1> cannot override onValidateSchema(SupportSQLiteDatabase) in Delegate
attempting to assign weaker access privileges; was public
It was working before the 'Chipmunk' version (was working in 'Bumblebee'), but it started throwing these errors.
What is going on here?
To fix this error for Jetpack Compose and Paging 3 you only need to use only this libraries
//ROOM
implementation "androidx.room:room-runtime:2.4.2"
kapt "androidx.room:room-compiler:2.4.2"
implementation "androidx.room:room-ktx:2.4.2"
implementation "androidx.room:room-paging:2.4.2"
// Paging 3.0
implementation 'androidx.paging:paging-compose:1.0.0-alpha15'
By Никандрова Елизавета's answer, I have found that the source of the problem was one of the optional implementations that I have added from official website.
These dependencies was enough to run my code:
def room_version = "2.4.2"
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"
Well, I have just encountered this problem too, seems that you are copying the code from the official guidance.
It seems to be the problem of "androidx.room:room-paging:2.5.0-alpha02" so the solution is to replace it with the latest stable version(2.4.2 currently) or just use the variable room_version
And you can check the latest version on: https://androidx.tech/artifacts/room/room-paging/
So you just need to replace it with the following code to solve this problem
dependencies {
def room_version = "2.4.2"
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"
// optional - RxJava2 support for Room
implementation "androidx.room:room-rxjava2:$room_version"
// optional - RxJava3 support for Room
implementation "androidx.room:room-rxjava3:$room_version"
// optional - Guava support for Room, including Optional and ListenableFuture
implementation "androidx.room:room-guava:$room_version"
// optional - Test helpers
testImplementation "androidx.room:room-testing:$room_version"
// optional - Paging 3 Integration
implementation "androidx.room:room-paging:$room_version"
}
I got this error because I used
implementation 'androidx.work:work-runtime-ktx:2.8.0-rc01'
with
implementation 'androidx.room:room-runtime:2.4.3'
kapt 'androidx.room:room-compiler:2.4.3'
and library
androidx.work:work-runtime-ktx:2.8.0-rc01
is dependent on
androidx.room:room-common:2.5.0-rc01
so I finished with two same libraries but with different versions
androidx.room:room-common:2.5.0-rc01
androidx.room:room-common:2.4.3
after switching back to
androidx.work:work-runtime:2.7.1
error was gone.
I tried to comment every dependency one by one; changed version one by one at a time.
def roomVersion = "2.4.1"
// //def roomVersion = "2.4.3"
// //noinspection GradleDependency
// kapt "androidx.room:room-compiler:$roomVersion"
// //noinspection GradleDependency
implementation "androidx.room:room-runtime:$roomVersion"
// //noinspection GradleDependency
implementation "androidx.room:room-ktx:$roomVersion"
It occurred to me that:
// kapt "androidx.room:room-compiler:$roomVersion"
above comment was responsible to generate the following exception:
Caused by: java.lang.RuntimeException: Cannot find implementation
for com.safehaven.data.di.AppDatabase. AppDatabase_Impl does not exist
Hence this library that is commented is responsible in the generation of this file AppDatabase_Impl where this error is coming.
So now this library is to be dealt with.
Secondly the Delegate class that is used in RoomOpenHelper
has these codes:
#Suppress("DEPRECATION")
open fun onValidateSchema(db: SupportSQLiteDatabase): ValidationResult {
validateMigration(db)
return ValidationResult(true, null)
}
and
override fun onCreate(db: SupportSQLiteDatabase) {
val isEmptyDatabase = hasEmptySchema(db)
delegate.createAllTables(db)
if (!isEmptyDatabase) {
// A 0 version pre-populated database goes through the create path because the
// framework's SQLiteOpenHelper thinks the database was just created from scratch. If we
// find the database not to be empty, then it is a pre-populated, we must validate it to
// see if its suitable for usage.
val result = delegate.onValidateSchema(db)
if (!result.isValid) {
throw IllegalStateException(
"Pre-packaged database has an invalid schema: ${result.expectedFoundMsg}"
)
}
}
updateIdentity(db)
delegate.onCreate(db)
}
clearly both are public, while in SupportSQLiteOpenHelper.Callback _openCallback class that instantiates with this abstract class in AppDatabase_Impl class, exposes these methods with protected access modifier which lowers the visibility of the overridden methods.
Hence causing error.
This should be fixed.
Surprisingly I got this error a week ago. It was resolved by using one of the answer (here, in the same question) as method (I am clueless, how it did), it has surfaced again and now not going away.
For this very reason I recommend at least myself, not to use Room Database. I will move to ORMLite or SQLite database as before.
Increasing room version fixed it for me
implementation "androidx.room:room-runtime:2.5.0-rc01"
I had same errors and I could solve issues doing as below in build.gradle(app).
In 'plugins' block, below code was added;
id 'kotlin-kapt'
In 'dependencies' block, below codes were added;
def room_version = "2.4.2"
implementation "androidx.room:room-ktx:$room_version"
implementation "androidx.room:room-runtime:$room_version"
kapt "androidx.room:room-compiler:$room_version"
I removed the code -
def room_version = "2.4.3"
implementation "androidx.room:room-ktx:$room_version"
kapt "androidx.room:room-compiler:$room_version"
and replace with this one -
def room_version = "2.4.3"
implementation "androidx.room:room-runtime:$room_version"
implementation "androidx.room:room-ktx:$room_version"
I had same error after upgrading to compileSdk 33 using
implementation 'androidx.room:room-runtime:2.4.3'
kapt 'androidx.room:room-compiler:2.4.3'
I found that after the upgrade there is an implicit dependency to 2.5.0-beta01:
so I just upgraded to 2.5.0-beta01
implementation 'androidx.room:room-runtime:2.5.0-beta01'
kapt 'androidx.room:room-compiler:2.5.0-beta01'
and the error was gone
I am trying to implement architecture component in my application, but when I am to add lifecycleowner to my viewmodel inside my fragment with getActivity() its show message
Cannot resolve method of android.support.v4.app.FragmentActivity
This is my code:
viewModel = ViewModelProviders.of(getActivity()).get(MyViewModel.class);
viewModel.setToken(token);
viewModel.getRecent().observe(getActivity(), new Observer<List<Recent>>() {
#Override
public void onChanged(List<Recent> recent) {
adapter.setData(recent);
}
});
My fragment is derived from android.support.v4.app.Fragment
and MyActivity is extends AppCompatActivity
and this is my Gradle file:
def paging_version = "2.1.0"
def lifecycle_version = "2.0.0"
def room_version = "2.1.0-alpha04"
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"
implementation "androidx.paging:paging-runtime:$paging_version"
implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"
How do I solve this problem? thanks in advance.
Problem
In androidx.lifecycle.ViewModelProviders.of(FragmentActivity), they accept androidx.fragment.app.FragmentActivity, not android.support.v4.app.FragmentActivity.
Solution
Migrate entire project to AndroidX using Migrate to AndroidX which introduced from Android Studio 3.2. You can found information in this page
Change dependencies version to support library version. Dependencies version can be found this page
dependencies {
def lifecycle_version = "1.1.1"
// ViewModel and LiveData
implementation "android.arch.lifecycle:extensions:$lifecycle_version"
// alternatively - just ViewModel
implementation "android.arch.lifecycle:viewmodel:$lifecycle_version" // For Kotlin use viewmodel-ktx
// alternatively - just LiveData
implementation "android.arch.lifecycle:livedata:$lifecycle_version"
// alternatively - Lifecycles only (no ViewModel or LiveData).
// Support library depends on this lightweight import
implementation "android.arch.lifecycle:runtime:$lifecycle_version"
annotationProcessor "android.arch.lifecycle:compiler:$lifecycle_version" // For Kotlin use kapt instead of annotationProcessor
// alternately - if using Java8, use the following instead of compiler
implementation "android.arch.lifecycle:common-java8:$lifecycle_version"
// optional - ReactiveStreams support for LiveData
implementation "android.arch.lifecycle:reactivestreams:$lifecycle_version"
// optional - Test helpers for LiveData
testImplementation "android.arch.core:core-testing:$lifecycle_version"
}
My app database class
#Database(entities = {Detail.class}, version = Constant.DATABASE_VERSION)
public abstract class AppDatabase extends RoomDatabase {
private static AppDatabase INSTANCE;
public abstract FavoritesDao favoritesDao();
public static AppDatabase getAppDatabase(Context context) {
if (INSTANCE == null) {
INSTANCE =
Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, Constant.DATABASE).allowMainThreadQueries().build();
//Room.inMemoryDatabaseBuilder(context.getApplicationContext(),AppDatabase.class).allowMainThreadQueries().build();
}
return INSTANCE;
}
public static void destroyInstance() {
INSTANCE = null;
}
}
Gradle lib:
compile "android.arch.persistence.room:runtime:+"
annotationProcessor "android.arch.persistence.room:compiler:+"
And when i ask for instance it will give this error, AppDatabase_Impl does not exist
in my application class
public class APp extends Application {
private boolean appRunning = false;
#Override
public void onCreate() {
super.onCreate();
AppDatabase.getAppDatabase(this); //--AppDatabase_Impl does not exist
}
}
For those working with Kotlin, try changing annotationProcessor to kapt in the apps build.gradle
for example:
// Extensions = ViewModel + LiveData
implementation "android.arch.lifecycle:extensions:1.1.0"
kapt "android.arch.lifecycle:compiler:1.1.0"
// Room
implementation "android.arch.persistence.room:runtime:1.0.0"
kapt "android.arch.persistence.room:compiler:1.0.0"
also remember to add this plugin
apply plugin: 'kotlin-kapt'
to the top of the app level build.gradle file and do a clean and rebuild (according to https://codelabs.developers.google.com/codelabs/android-room-with-a-view/#6)
In Android Studio, if you get errors when you paste code or during the build process, select Build >Clean Project. Then select Build > Rebuild Project, and then build again.
UPDATE
If you have migrated to androidx
def room_version = "2.3.0" // check latest version from docs
implementation "androidx.room:room-runtime:$room_version"
kapt "androidx.room:room-compiler:$room_version"
UPDATE 2 (since July 2021)
def room_version = "2.3.0" // check latest version from docs
implementation "androidx.room:room-ktx:$room_version"
kapt "androidx.room:room-compiler:$room_version"
Just use
apply plugin: 'kotlin-kapt'
in app build.gradle
And keep both in dependencies
annotationProcessor "android.arch.persistence.room:compiler:$rootProject.roomVersion"
kapt "android.arch.persistence.room:compiler:$rootProject.roomVersion"
EDIT
In newer version don't need to add both dependencies at a time
Just use, hope it will work.
kapt 'android.arch.persistence.room:compiler:1.1.1'
I had this error when I missed
#Database(entity="{<model.class>})
Ensure that the entity model specified in the annotation above refers to the particular model class and also ensure that the necessary annotation:
#Entity(tableName = "<table_name>" ...)
is properly defined and you'd be good
if you are using kotlin classes to implement database then
use
apply plugin: 'kotlin-kapt'
and
kapt "android.arch.persistence.room:compiler:1.1.1"
in your gradle file, it will work.
For Kotlin Developers
Use this:
implementation "android.arch.persistence.room:runtime:1.0.0"
kapt "android.arch.persistence.room:compiler:1.0.0"
And add apply plugin: 'kotlin-kapt' to the top of the app level build.gradle.
For Java Developers
implementation "android.arch.persistence.room:runtime:1.0.0"
annotationProcessor "android.arch.persistence.room:compiler:1.0.0"
It is not just about updating your dependencies. Make sure all your Room dependencies have the same version.
implementation 'android.arch.persistence.room:rxjava2:1.1.0-alpha2'
implementation 'android.arch.persistence.room:runtime:1.1.0-alpha2'
annotationProcessor "android.arch.persistence.room:compiler:1.1.0-alpha2"
In the sample snippet above, all my Room dependencies have the same version 1.1.0-alpha2
Agreed with the above answers
The solution is as below. Change annotationProcessor to kapt as below
// annotationProcessor "androidx.room:room-compiler:$room_version"
implementation "androidx.room:room-runtime:$room_version"
kapt "androidx.room:room-compiler:$room_version"
I meet with the problem, because I forget #Dao annotation
#Dao
public interface SearchHistoryDao {
#Query("SELECT * FROM search_history")
List<SearchHistory> getAll();
#Insert
void insertAll(SearchHistory... histories);
#Delete()
void delete(SearchHistory history);
}
Room Official tutorial
make sure to add correct dependency for room in build.gradle
ext {
roomVersion = '2.1.0-alpha06'
}
// Room components
implementation "androidx.room:room-runtime:$rootProject.roomVersion"
implementation "androidx.room:room-ktx:$rootProject.roomVersion"
kapt "androidx.room:room-compiler:$rootProject.roomVersion"
androidTestImplementation "androidx.room:room-testing:$rootProject.roomVersion"
And below line at the top-
apply plugin: 'kotlin-kapt'
I met this problem because I have forgotten the apt dependences
implementation "android.arch.lifecycle:extensions:$archLifecycleVersion"
implementation "android.arch.persistence.room:runtime:$archRoomVersion"
annotationProcessor "android.arch.lifecycle:compiler:$archLifecycleVersion"
annotationProcessor "android.arch.persistence.room:compiler:$archRoomVersion"
after added the annotationProcessor, and rebuild it, the problem solved.
If you are using kotlin, add kotlin annotation processor plugin to app level build.gradle
plugins {
id "org.jetbrains.kotlin.kapt"
}
Also remove annotationProcessor and replace it with kapt
Instead of
dependencies {
def room_version = "2.3.0"
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"
}
Use
dependencies {
def room_version = "2.3.0"
implementation "androidx.room:room-runtime:$room_version"
kapt "androidx.room:room-compiler:$room_version"
}
The annotationProcessor only works in java environment. The kapt takes care of both java and kotlin. If something wrong with your implementation, those plugins will show them at the compile time.
Had the same problem. Implemented the few classes and interface as officially told in a new example project created by Android Studio:
https://developer.android.com/training/data-storage/room/
All mentioned solutions above did not help, the necessary _Impl files according to my database class were not generated by Room. Finally executing gradle clean build in terminal gave me the hint that lead to the solution:
"warning: Schema export directory is not provided to the annotation processor so we cannot export the schema. You can either provide room.schemaLocation annotation processor argument OR set exportSchema to false."
I added the parameter exportSchema = false in the database class
#Database(entities = arrayOf(User::class), version = 1, exportSchema = false)
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
}
And then it worked, found these two generated files in the app module under generatedJava:
AppDatabase_Impl
UserDao_Impl
I don't understand this behaviour as the parameter is said to be optional, see
https://stackoverflow.com/a/44645943/3258117
The question is pretty old, but I've stumbled on this today and none of the provided answers helped me. Finally I managed to resolve it by noticing that google documentation actually is still adopted to Java and not Kotlin by default, actually they have added a comment which I've ignored
For Kotlin use kapt instead of annotationProcessor
So, instead of
annotationProcessor "androidx.room:room-compiler:$room_version"
If you are developing with Kotlin, you should use:
kapt "androidx.room:room-compiler:$room_version"
In my kotlin app, I just added the following line at the top of my build.gradle file :
apply plugin: 'kotlin-kapt'
And the following line in the dependencies section:
kapt "androidx.room:room-compiler:2.2.5"
I hope it fixes your issue.
In my case, I was testing the connectivity for room database and I have put the testing class inside the directory which I have created inside the AndroidTest folder. I have moved it out of the custom directory, then it worked pretty well.
The same phenomenon occurred to me.
following
implementation "android.arch.persistence.room:runtime:1.1.1"
Adding causes another build error but tracks the cause from the log.
In my case, there was an error in the SQL implementation.
After fixing, the build was successful.
So you may want to check the implementation of the entire room library instead of looking at the crashed locals.
Use the following gradle link:
compile 'android.arch.persistence.room:runtime:1.0.0-alpha9'
annotationProcessor 'android.arch.persistence.room:compiler:1.0.0-alpha9'
You need to create a different singleton class and get the AppDatabase from there like this:
RoomDB.java
public class RoomDB {
private static RoomDB INSTANCE;
public static AppDatabase getInstance(Context context) {
if (INSTANCE == null) {
INSTANCE =
Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, Constant.DATABASE).allowMainThreadQueries().build();
//Room.inMemoryDatabaseBuilder(context.getApplicationContext(),AppDatabase.class).allowMainThreadQueries().build();
}
return INSTANCE;
}
public static void destroyInstance() {
INSTANCE = null;
}
App.java
public class App extends Application {
private boolean appRunning = false;
#Override
public void onCreate() {
super.onCreate();
RoomDB.getInstance(this); //This will provide AppDatabase Instance
}
The issue is more around the correct library that is not included in the gradle build. I had a similar issue and added the missing
testImplementation "android.arch.persistence.room:testing:$room_version
Changing the dependencies in my gradle file did'nt help me in fixing the error.I had missed this Database annotation in class where Room database was initialized which was causing this issue.
#Database(entities = [UserModel::class], version = 1)
Ensure that the entity model specified in the annotation above refers to the particular model class
For Kotlin Developers
if you checked Dao and Entity and also used Kapt and there is no problem, I guess there is a problem with your kotlin version if you are using kotlin 1.4 and above.
update Room to last version from this link.
2.3.0-alpha03 solved my problem.
For me, the Android Studio automatically updated dependencies as soon as you include any of the Room database related imports. But as per https://developer.android.com/jetpack/androidx/releases/room#declaring_dependencies you need to update few. Here is how my code-base looks like:
AppDatabase.kt
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
#Database(entities = arrayOf(MyEntity::class), version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun myDAO(): MyDAO
companion object {
#Volatile private var instance: AppDatabase? = null
private val LOCK = Any()
operator fun invoke(context: Context)= instance ?: synchronized(LOCK){
instance ?: buildDatabase(context).also { instance = it}
}
private fun buildDatabase(context: Context) = Room.databaseBuilder(context,
AppDatabase::class.java, "db-name.db")
.build()
}
}
Update the build.gradle as specified in one of the answers:
apply plugin: 'kotlin-kapt' // this goes with other declared plugin at top
dependencies { // add/update the following in dependencies section
implementation 'androidx.room:room-runtime:2.2.3'
// annotationProcessor 'androidx.room:room-compiler:2.2.3' // remove this and use the following
kapt "androidx.room:room-compiler:2.2.3"
}
Sync the gradle and you should be good to go.
In addition to missing
annotationProcessor "android.arch.persistence.room:compiler:x.x.x"
I had also missed adding the below annotation in my class
#Entity(tableName = "mytablename")
Nothing works from above answers and I noticed that the issue persists for me when I'm using room version2.3.0 or 2.4.2. However, 2.5.0-alpha01 version works well when I applied it.
build.gradle:app
def roomVersion = '2.5.0-alpha01'
implementation "androidx.room:room-ktx:$roomVersion"
kapt "androidx.room:room-compiler:$roomVersion"
testImplementation "android.arch.persistence.room:testing:$roomVersion"
In my case just by changing annotationProcessor to kapt on my room-compiler dependency, did the work.
As of Jan 2023 - I faced a similar issue after refactoring my code to use ServiceLocator class.
I resolved it by going on a spree of changing room versions. It worked with 2.5.0-alpha02
version_room = "2.5.0-alpha02" <-- build.gradle (project)
//Room
implementation "androidx.room:room-runtime:$version_room"
kapt "androidx.room:room-compiler:$version_room"
// optional - Kotlin Extensions and Coroutines support for Room
implementation "androidx.room:room-ktx:$version_room"
implementation("androidx.room:room-guava:$version_room")
I am running the following on Android Eel 2020.1.1:
version_kotlin = "1.7.21"
version_android_gradle_plugin = "4.0.1"
Reading the example here:
Room Example
I fixed this error just using the correct (I guess it is) annotationProcessorFile, as follows:
annotationProcessor "android.arch.persistence.room:compiler:<latest_version>"
Also, I upgraded to 2.2.0 either in Room Version as in Lifecycle version.
Once synchronized the graddle, I could start working with Room.
So, Good luck! And let the code be with you!
Not in the case of OP, but this also happens when you mistakenly use implementation instead of annotationProcessor like this:
implementation "android.arch.persistence.room:compiler:x.x.x"
Instead of this:
annotationProcessor "android.arch.persistence.room:compiler:x.x.x"
Just in case anyone out there should make the same mistake as I did, don't call your database class "Database" or you'll get the same error.
check this annotation above class
#Database(entities = arrayOf(Schedule::class), version = 1)
abstract class AppDatabase : RoomDatabase() {
// ....
}
I'm trying to use Firebase integration with Glide and for some reason,
Glide.using() cannot resolve this method.
I did add:
compile 'com.firebaseui:firebase-ui-storage:0.6.0'
Into build.gradle and also:
compile 'com.github.bumptech.glide:glide:4.0.0-RC1'
Here is the part which I'm trying to use Glide:
mStorageRef = FirebaseStorage.getInstance().getReference();
mStorageRef.child("images/Puffer-fish-are-pretty-damn-cute.jpg");
// Load the image using Glide
Glide.with(this)
.using(new FirebaseImageLoader()) // cannot resolve method using!
.load(mStorageRef)
.into(imageView);
I hope you can help me with that, didn't find any solutions online.
To solve this, please change this line:
compile 'com.github.bumptech.glide:glide:4.0.0-RC1'
with
compile 'com.github.bumptech.glide:glide:3.7.0'
Glide v4 is using module loaders with the annotation processor library.
Create AppGlideModule and then register FirebaseImageLoader. When loading images use StorageReference.
Here it is in details.
Add libraries in gradle
implementation 'com.github.bumptech.glide:glide:4.7.1'
annotationProcessor 'com.github.bumptech.glide:compiler:4.7.1'
implementation 'com.firebaseui:firebase-ui-storage:4.1.0'
Extend the module and register
#GlideModule
public class MyAppGlideModule extends AppGlideModule {
#Override
public void registerComponents(#NonNull Context context, #NonNull Glide glide, #NonNull Registry registry) {
registry.append(StorageReference.class, InputStream.class, new FirebaseImageLoader.Factory());
}
}
Load images with ref
Uri uri = Uri.parse(photoUrl);
StorageReference ref = FirebaseStorage.getInstance().getReference().child(uri.getPath());
Glide.with(itemView.getContext())
.load(ref)
.into(thumb);
I've installed ButterKnife my build.gradle looks like this:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.3.0'
compile 'com.jakewharton:butterknife:8.4.0'
}
My loginActivity looks like this:
package com.example.egen.forum;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class LoginActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ButterKnife.bind(this);
Toast.makeText(getApplicationContext(), "Your toast message.",
Toast.LENGTH_SHORT).show();
}
#OnClick(R.id.btnLogin) public void test() {
Toast.makeText(getApplicationContext(), "Your toast message.",
Toast.LENGTH_SHORT).show();
}
}
The second toast does not show up. What am I doing wrong here?
You haven't included annotation processor for ButterKnife code generation. Do it like described on the GitHub page:
dependencies {
compile 'com.jakewharton:butterknife:8.4.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'
}
And apply the plugin:
apply plugin: 'com.jakewharton.butterknife'
Otherwise, your code looks fine.
Explanation: ButterKnife library uses annotation processor for generating the code that provides the references to views and executes ButterKnife annotated methods. If you rebuild your project, and the AndroidStudio shows that the #OnClick annotated method is unused, then somethings wrong. If the annotation processor is provided and works correctly, it should show as used and lead to a generated method.
Add this line:
annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'
as well in your build.gradle.
See here for more info
Well, Butterknife is yesterday, use databinding instead: https://developer.android.com/topic/libraries/data-binding/index.html.
This is almost the same tool out of the box