cannot find symbol BR in android data binding - android

I want to use Android Data Binding and has configured according to the official document.
the error message is :
error: cannot find symbol import net.juude.droidviews.BR;
the top level build.gradle file is:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath "com.android.tools.build:gradle:1.3.0-beta2"
classpath 'me.tatarka:gradle-retrolambda:3.0.1'
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.4'
classpath "com.android.databinding:dataBinder:1.0-rc0"
}
}
allprojects {
repositories {
jcenter()
mavenCentral()
}
}
and the build.gradle file in app module is
apply plugin: 'com.android.application'
apply plugin: 'me.tatarka.retrolambda'
apply plugin: 'com.neenbedankt.android-apt'
apply plugin: 'com.android.databinding'
android {
compileSdkVersion 22
buildToolsVersion "22.0.1"
lintOptions {
abortOnError false
}
defaultConfig {
applicationId "net.juude.droidviews"
minSdkVersion 15
targetSdkVersion 22
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
retrolambda {
println("JAVA_HOME: " + System.getenv("JAVA_HOME"))
println("JAVA7_HOME: " + System.getenv("JAVA7_HOME"))
println("JAVA8_HOME: " + System.getenv("JAVA8_HOME"))
javaVersion JavaVersion.VERSION_1_7
}
}
dependencies {
compile project(':ptr-lib-debug')
compile project(':library')
compile 'com.android.support:support-v4:22.1.0'
compile 'com.mcxiaoke.volley:library:1.0.+'
compile files('libs/droidmocks.jar')
compile 'com.android.support:support-annotations:22.1.1'
compile 'com.facebook.fresco:fresco:0.5.0'
compile 'com.android.support:recyclerview-v7:22.1.1'
compile 'io.reactivex:rxandroid:0.24.0'
compile 'io.reactivex:rxjava:1.0.6'
compile 'com.google.dagger:dagger:2.0'
apt 'com.google.dagger:dagger-compiler:2.0'
}
the layout file is
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable name="user" type=" net.juude.droidviews.databinding.User" />
</data>
<LinearLayout
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/user_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{user.mName}"/>
<TextView
android:id="#+id/user_sex"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{user.sex}"/>
</LinearLayout>
</layout>
the fragment is
package net.juude.droidviews.databinding;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import net.juude.droidviews.BR;
import net.juude.droidviews.R;
/**
* Created by juude on 15-6-9.
*/
public class DataBindingFragment extends Fragment{
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewDataBinding dataBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_data_binding, container, false);
//dataBinding.setVariable(BR.)
User user = new User();
user.setSex("男");
user.setName("Juude");
dataBinding.setVariable(BR.user, user);
return dataBinding.getRoot();
}
}
since I did not get syntax error in Android Studio, I can assume that the Android Studio can recognize the BR class;
But when I compile the project, It tells me that
error:cannot find symbol class BR.
so I want to know what should I do to make it generate the right BR.java file?

In case someone still has this problem. I solved this by invalidating the cache in Android Studio. And I'm using Android Studio 2 with API 23
File > Invalidate Caches/Restart

It is a problem caused by android-apt plugin. It ignores the provided dependency that data binding plugin adds.
https://bitbucket.org/hvisser/android-apt/issue/38/android-apt-breaks-brand-new-data-binding#comment-18504545
You can work around it by adding:
apt 'com.android.databinding:compiler:1.0-rc0 to your gradle file.

If you are using Kotlin, try applying the following plugin to your app build.gradle file:
apply plugin: 'kotlin-kapt'
Clean your project and build it again. This solved the issue for me.

I find the cause of the problem in my case. I find in the import statements of my Data Object class contains:
import static android.databinding.tool.util.GenerationalClassUtil.ExtensionFilter.BR;
The problem gets solved after I removed that. Android Studio somehow resolved BR class wrongly for me.

The Bindable annotation generates an entry in the BR class file during compilation. The BR class file will be generated in the module package.
#Bindable
public String getFirstName() {
return this.firstName;
}

I ran into this issue too. The problem was that I changed the class name and didn't update the values in the XML file. This includes the variable names and where they are accessed in the xml file.

For my case the issue was caused by
"error: variable MyVariable was already defined in class MyModel"
The annoying thing was Android Studio gradle build did not display this error at the bottom. I had to comment each databinding error > Rebuild Project until I reach the error. Lesson learnt was to scan through each error from bottom to top and notice anything you may have changed recently.

I too got the same error message, but my root cause was different from what has been shared here.
In my case the issue was that after I resolved a merge conflict, I had by mistake left an extra #Override annotation on a method. Thus the JVM preprocessor failed and then also the data binding classes were not generated.
The irritating part for me was that I was unable to see any error message related to this, or it was hard to spot among all the other compiler errors. And Android Studio does not show the extra annotation as an error either. So in case someone else struggles with the same error, check that you don't haven an error in some annotation that prevents the APT preprocessor from kicking in.

You need to add this to your gradle.properties file
android.databinding.enableV2=true
From developer.android.com
you might get multiple errors reporting that the binding classes aren't found. The new data binding compiler prevents these errors by generating the binding classes before the managed compiler builds your app.

Just restarting Android Studio, without invalidating cache, did the trick for me (I'm using version 2.2.3).

I had this plus 29 other errors suddenly crop up from one moment to the next. I tried clean, rebuild, invalidate caches / restart and no luck. In the end I removed changes I had made and redid them one by one. Found that I had #Injected a service in the wrong class. Once I removed that all 30 errors were gone. The errors gave no clue to what I had done wrong.

If you use Android Studio 2.3 release and your project configuration is as follow:
Gradle version: 3.3
Android plugin version:2.3.0
Compile sdk Version:23+
build tools Version:25+
All need to do is add
dataBinding{enabled=true}
to build.gradle, then sync gradle file.

For me it helped to run ./gradlew clean build in the project folder. It showed an error which android studio didn't.

Generally BR class Generate automatically when you Rebuild your project and I have resolved the problem using this technique Still have issue you can try another solution.

You need to double-check the following steps:
GradleFile:
dataBinding {enabled = true}
Your class Model.
import androidx.databinding.BaseObservable
import androidx.databinding.Bindable
import androidx.databinding.library.baseAdapters.BR
class User2(
private var firstName: String,
private var lastName: String
) : BaseObservable() {
fun setFirstName(firstName: String) {
this.firstName = firstName
notifyPropertyChanged(BR.firstName)
}
#Bindable
fun getFirstName(): String {
return this.firstName
}
}

If you are using Dagger 2, the problem may be caused by dagger's components. Although two libraries are not related, in my case, fixing errors in Dagger reported in the compiler makes the BR class properly appear again.

BR gets generated during compilation, Build -> Rebuild project should do the trick. But for me it failed with error:
e:/home/xx/File.kt: (24, 46): Expecting an element because on that line I had an incompleted BR.. Just commenting or adding anything after . and rebuilding solved it.

Just follow the steps below,
1.Extend your class with BaseObservable class
2.Add #Bindable annotation to each getter methods.
3.Rebuild the project.
Now you'll be able to access BR

In my case, I tried just running the project and it fixed the issue.

Add dependency
implementation "androidx.lifecycle:lifecycle-extensions:2.1.0"
Then sync project. Even if not works, invalidate cache and restart then clean & rebuild project.

In my case i haven't provided #PrimaryKey annotation on one of the entity and it was really difficult to find this error as in logs there are no clue to find it. so be sure to give your Entity a primary key, else this error occurs.

Check your room database related file, because of that class gradle build get failed, and will not get idea actually. issue is in room classes.
what ever androidx.databinding.library.baseAdapters.BR error your getting those file is not generating because of room database class have some syntax error

Related

kotlinx.android.synthetic unused android studio issue

I am working one project using kotlin + Rxjava + MVVM. During development facing issue of importing view ids in Fragment or viewholder.
import kotlinx.android.synthetic.main.layout.* unused with kotlin.
Normaly view id should used from kotlin synthetic layout imports but it directly import it from R.id that should not happen.
Kotlin plugin version : org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.40
My gradle file :
apply plugin: 'com.android.feature'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'idea'
apply plugin: 'kotlin-kapt'
android {
compileSdkVersion 27
baseFeature true
defaultConfig {
minSdkVersion 23
targetSdkVersion 27
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
lintOptions {
abortOnError false
}
}
dependencies {
api "com.android.support:design:$rootProject.support_library_version"
api "com.android.support:appcompat-v7:$rootProject.support_library_version"
api "com.android.support:recyclerview-v7:$rootProject.support_library_version"
api "com.android.support:support-dynamic-animation:$rootProject.support_library_version"
api "com.android.support:cardview-v7:$rootProject.support_library_version"
api "com.android.support:customtabs:$rootProject.support_library_version"
api "com.android.support.constraint:constraint-layout:1.1.0-beta5"
api 'android.arch.lifecycle:extensions:1.1.0'
api 'androidx.core:core-ktx:0.2'
api "com.google.dagger:dagger:$rootProject.dagger_version"
kapt "com.google.dagger:dagger-compiler:$rootProject.dagger_version"
api "android.arch.persistence.room:runtime:$rootProject.room_version"
kapt "android.arch.persistence.room:compiler:$rootProject.room_version"
testImplementation "android.arch.persistence.room:testing:$rootProject.room_version"
api "android.arch.persistence.room:rxjava2:$rootProject.room_version"
androidTestImplementation "android.arch.core:core-testing:$rootProject.room_version"
testImplementation "android.arch.core:core-testing:$rootProject.room_version"
api "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
api "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
api 'com.jakewharton.timber:timber:4.5.1'
api "com.android.support:multidex:1.0.3"
api "com.github.bumptech.glide:glide:$rootProject.glide_version"
api "jp.wasabeef:glide-transformations:$rootProject.glide_transformation_version"
api 'com.github.bumptech.glide:okhttp3-integration:1.5.0#aar'
api "io.reactivex.rxjava2:rxandroid:$rootProject.rxAndroid_version"
api "io.reactivex.rxjava2:rxjava:$rootProject.rxJava_version"
api "com.google.code.gson:gson:$rootProject.gson_version"
api("com.squareup.retrofit2:retrofit:$rootProject.retrofit_version") {
// exclude Retrofit’s OkHttp peer-dependency module and define your own module import
exclude module: 'okhttp'
}
api "com.squareup.okhttp3:okhttp:$rootProject.okhttp_version"
api "com.squareup.okhttp3:logging-interceptor:$rootProject.okhttp_version"
api "com.squareup.retrofit2:adapter-rxjava2:$rootProject.retrofit_version"
api "com.squareup.retrofit2:converter-gson:$rootProject.retrofit_version"
api 'com.jakewharton.threetenabp:threetenabp:1.0.5'
api "com.google.firebase:firebase-invites:$rootProject.play_services_version"
api "com.google.firebase:firebase-core:$rootProject.play_services_version"
api "com.google.firebase:firebase-config:$rootProject.play_services_version"
api "com.google.firebase:firebase-perf:$rootProject.play_services_version"
api "com.google.firebase:firebase-auth:$rootProject.play_services_version"
api "com.google.firebase:firebase-firestore:$rootProject.play_services_version"
api("com.firebaseui:firebase-ui-auth:$rootProject.firebase_ui_version") {
// exclude Retrofit’s OkHttp peer-dependency module and define your own module import
exclude module: 'play-services-auth'
exclude module: 'firebase-auth'
}
// Required only if Facebook login support is required
api('com.facebook.android:facebook-android-sdk:4.31.0')
api "com.google.android.gms:play-services-auth:$rootProject.play_services_version"
// Required only if Twitter login support is required
api("com.twitter.sdk.android:twitter-core:3.0.0#aar") { transitive = true }
api 'com.jakewharton.rxbinding2:rxbinding-kotlin:2.0.0'
api 'com.jakewharton.rxbinding2:rxbinding-support-v4-kotlin:2.0.0'
api 'com.jakewharton.rxbinding2:rxbinding-appcompat-v7-kotlin:2.0.0'
api 'com.jakewharton.rxbinding2:rxbinding-design-kotlin:2.0.0'
api('com.crashlytics.sdk.android:crashlytics:2.9.1#aar') {
transitive = true
}
}
I have also tried clean build and Rebuild project.
Any idea how can i resolve this issue ?
I have tried several approaches including the solutions reported in this thread. I also found out that a lot of folks are facing this annoying problem as you can see here
Nevertheless, the most closest solution to this problem which has worked for me so far is removing apply plugin: kotlin-android-extensions from gradle, Sync gradle plugin and then add it again.
I'm using Android Studio 3.1.3 and I encountered the same issue. I managed to solve this by moving all my codes from java/ to kotlin/ directory inside main/.
app/
|-- src/
| |-- main/
| | |-- java/
| | | |-- com.example.android.app
| | |-- kotlin/ <-- (use this)
| | | |-- com.example.android.app
Then, add the kotlin/ as part of the source sets:
app/build.gradle
android {
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
}
Sometimes, it still requires to sync and rebuild the project to properly import the kotlinx.android....
Reference: Add kotlin code
I have the same problem and I am trying to solve it for too many days...
One trick you can do is to Exclude from Import and Completion <package-name>.R.id.* for project scope.
Go to Settings/Editor/Auto Import to add it.
It improves our issue and if you do this and clean the project, it will work but it does not resolve the issue completely. Many times the imports reappear as unused imports and there is to clean the project over and over :-(.
EDITED
Also, another improvement I have achieved is working with includes on XML. For example, if I am going to use "the same" button in several screens, I make a specific layout for this button and I re-use it on several activities / fragments. You can set the id within this specific layout and synthetic will auto-import it without generating conflicts, due to you have the content view reference declared before.
I show you a simple example:
activity_main.xml
<!-- ... -->
<include layout="#layout/btn_foo"/>
<!-- ... -->
btn_foo.xml
<?xml version="1.0" encoding="utf-8"?>
<Button
android:id="#+id/btnFoo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android"/>
MainActivity.kt
// ...
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.btn_foo.*
// ...
setContentView(R.layout.activity_main)
// ...
btnFoo.setOnClickListener { }
I have to admit that in the other cases I have returned to the typical Hungarian convention whatWhereDescription(Size) to set the ids due to is too much annoying to deal with imports among activities / fragments / view all the time.
I've solved similar issues for ViewHolder implementations:
We have to inherit our ViewHolder class implementation from LayoutContainer. LayoutContainer is an interface available in kotlinx.android.extensions package.
You will have some code similar with this:
class TaskVH(override val containerView: View, val itemListener: TasksFragment.TaskItemListener) : RecyclerView.ViewHolder(containerView), LayoutContainer {
fun bindItem(task: Task) {
item_title.text = ""
item_complete.isChecked = task.isCompleted
itemView.setBackgroundResource(rowViewBackground)
itemView.setOnClickListener { itemListener.onTaskClick(task) }
}
}
I don't know if this tripped anyone else up, but I was having problems because I didn't realize the synthetic objects are only available if you're inside an Activity, Dialog, or Fragment. If you're in some other class (like using Conductor's Controller) you're out of luck.
Cross-posting my bug report with workaround from here: https://issuetracker.google.com/issues/145888144
Original bug was closed as "fixed" by google, but it is definitely not fixed: https://issuetracker.google.com/issues/78547457
SUMMARY:
For some modules in a multi-module project, the IDE does not properly recognize imports for "synthetic" symbols that abstract view ids, a feature provided by the plugin 'kotlin-android-extensions'. This results in class files using these symbols appearing full of errors, as the imports are "unresolved", the symbols are then unknown, and of course anything using these symbols fail because the types are unknown.This is solely an IDE problem though; everything compiles normally and works as expected.
ROOT CAUSE
The kotlin-language facet is not being applied to the errant modules.
BACKGROUND
Facets in IntelliJ IDEA projects are configurable on a module-by-module basis in Project settings. In Android Studio, this part of the Project settings UI is missing (or suppressed.) Presumably, Android Studio is attempting to apply the correct facets based on the gradle plugins applied to each module. This process is /sometimes/ FAILING for this particular case; I have not been able to determine what triggers the success/failure of the process.
TEMPORARY WORKAROUND
This workaround works consistently, and has since 3.5.2 when I discovered it:
Open the ".iml" file for the module you are trying to "fix" in Android Studio editor. (In AS > 4, the iml file is in .idea/modules, earlier than that it was in top-level of your module.) Find the <component name="FacetManager"> block, and notice that there is no facet called "kotlin-language" there. Paste the contents of the text block below so it appears within the <component name="FacetManager"> block. Save the file.
Re-import gradle.
This is a clumsy workaround, and has to be applied on a module-by-module basis. What's more, it may be required to sometimes re-apply the workaround after making changes to the build.gradle file for an affected module. The hope is that Google (or JetBrains, if it turns out it is their problem) will fix this problem properly.
Given that kotlin-android-extensions has fallen out of favor, I don't expect this bug will ever be fixed.
Text to use for the fix
<facet type="kotlin-language" name="Kotlin">
<configuration version="3" platform="JVM 1.8" allPlatforms="JVM [1.8]" useProjectSettings="false">
<compilerSettings />
<compilerArguments>
<option name="jvmTarget" value="1.8" />
<option name="pluginOptions">
<array>
<option value="plugin:org.jetbrains.kotlin.android:enabled=true" />
<option value="plugin:org.jetbrains.kotlin.android:defaultCacheImplementation=hashMap" />
</array>
</option>
</compilerArguments>
</configuration>
</facet>
There is an existing issue (which is assigned) on Google tracker regarding synthetic imports.
https://issuetracker.google.com/issues/78547457
For Conductor:
Create this base class.
import android.os.Bundle
import android.view.View
import com.bluelinelabs.conductor.Controller
import com.bluelinelabs.conductor.RestoreViewOnCreateController
abstract class BaseController(
bundle: Bundle? = null
) : RestoreViewOnCreateController(bundle){
init {
addLifecycleListener(object : LifecycleListener() {
override fun postCreateView(controller: Controller, view: View) {
onViewCreated(view)
}
})
}
open fun onViewCreated(view: View) { }
}
Then in your controller:
import kotlinx.android.synthetic.main.controller_example.view.*
class ProfileController : BaseController() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup, savedViewState: Bundle?): View {
return inflater.inflate(R.layout.controller_example, container, false)
}
override fun onViewCreated(view: View) {
view.txtName.text = "Example"
}
}
I try every other solution bu no one worked for me. At the and I cloned project again and now it's working. I love android studio
Add id kotlin-android-extensions in your build.gradle file in the plugins block.
Google removed this feature by default

Room annotation processor with Data binding

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"

Error:Execution failed for task ':app:transformClassesWithDexBuilderForDebug'

When I add ONE SHARE SDK as dependency I get the following error message:
Error:Execution failed for task ':app:transformClassesWithDexBuilderForDebug'.
com.android.build.api.transform.TransformException: org.gradle.tooling.BuildException:
com.android.dx.cf.iface.ParseException: class name (com/sina/weibo/sdk/component/view/CommentComponentView$RequestParam)
does not match path (weiboSDKCore_3.1.2/com/sina/weibo/sdk/component/view/CommentComponentView$RequestParam.class)
What could be the cause of this error?
Adding the following code to build.gradle app module solved my problem
android{
defaultConfig {
// Enabling multidex support.
multiDexEnabled true
}
dexOptions {
javaMaxHeapSize "4g"
}
}
dependencies {
//...
compile 'com.android.support:multidex:1.0.0'
}
Source Code
It's probably a rare scenario, but I had it. Previously, an android-support-v4.jar file was manually added to my project. This was done before the use of the gradle. Remove the file and the build was successful.
Sounds like the error is recognizing a class cast issue. It expects CommentComponentView$RequestParam.class
but it getting something else. Could be different version or duplicate named class where it is trying to figure out which one to use and it is using the wrong one.
For example if I have a class called
public class MyClass {
}
and the SDK has a class called
public class MyClass {
}
then in the usage it could be confusing the two. Check your import statements to make sure you are using the correct path and version of the parameter that it is expecting as maybe it is a duplicate class that is confusing it by accessing the wrong version of that class.
This may not be your issue, but worth checking out. Goodluck.

Google Play game services - Android samples errors

Based on Android docs (https://developers.google.com/games/services/android/quickstart#before_you_begin) for learning how to configure Google Play game APIs onto a sample app such as TypeANumber, I was wondering why I get the following resource errors from the BaseGameUtils library after importing the project, BasicSamples, from their GitHub's (https://github.com/playgameservices/android-basic-samples) source files:
... Based on the directory in the left panel, did I import it properly? All I did was import it straight from the directory: android-basic-samples/BasicSamples/build.gradle as stated in Step 1 of the link.
Here's my (untouched) Gradle file for the library, BaseGameUtils:
apply plugin: 'com.android.library'
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.3.1'
}
}
dependencies {
// Set defaults so that BaseGameUtils can be used outside of BasicSamples
if (!project.hasProperty('appcompat_library_version')) {
ext.appcompat_library_version = '20.0.+'
}
if (!project.hasProperty('support_library_version')) {
ext.support_library_version = '20.0.+'
}
if (!project.hasProperty('gms_library_version')) {
ext.gms_library_version = '8.1.0'
}
compile "com.android.support:appcompat-v7:${appcompat_library_version}"
compile "com.android.support:support-v4:${support_library_version}"
compile "com.google.android.gms:play-services-games:${gms_library_version}"
compile "com.google.android.gms:play-services-plus:${gms_library_version}"
}
android {
// Set defaults so that BaseGameUtils can be used outside of BasicSamples
if (!project.hasProperty('android_compile_version')) {
ext.android_compile_version = 23
}
if (!project.hasProperty('android_version')) {
ext.android_version = '23'
}
compileSdkVersion android_compile_version
buildToolsVersion android_version
}
... Did anyone else experience this issue before?
EDIT AS OF 4/7, 3:37PM:
So I ended up importing the project again, but within the AndroidStudioProjects directory this time (does that really make a difference?) and I actually ended up making some progress since then. However, for part 3 under step 1 within the docs:
... I ended up changing not only the package name in TypeANumber's manifest file, but also the package directory along with the classes in it as follows:
... So my question now is, am I on the right track so far in terms of the navigation directory panel at the left? :)
Yes. The package attribute in the manifest should always match the directories. Plain and simple. That's why changing it would require you to do a complete refactor. Just keep on going with the tutorial accordingly and I think you'll be good.

How to disable "cannot resolve method" error inspections in Android Studio

I have some code snippets below when I use android databinding framework with ViewStub.
ItemPostBinding binding=ItemPostBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
final Post post = mDataset.get(position);
binding.stub.getViewStub().setLayoutResource(App.getPostExtensionManager().getLayout(post.getExtension()));
I kown binding.stub will be replaced with ViewStubProxy when codes compiled. But how could I ask Android Studio to ignore the error here before compiling?
(The error is Android Studio cannot resolve getViewStub() method from class ViewStub)
UPDATE 1
I don't know if it was due to my old approach of using android data-binding framework.
classpath 'com.android.databinding:dataBinder:1.0-rc4' // project build.gradle
apply plugin: 'com.android.databinding' // module build.gradle
But with the new method mentioned in the official data-binding guide, all you need to do is adding the settings below in your module's build.gradle file.
android {
....
dataBinding {
enabled = true
}
}
And the error inspections mentioned above is gone, you can even directly use binding.stub without any problem.
binding.stub.setLayoutResource(...)
binding.stub.inflate()
...
UPDATE 2
You can use binding.stub.someViewStubMethod() directly but it will fail while compiling. You still need to use binding.stub.getViewStub().someMethod(). However, just recently the error inspections is gone somehow no matter which method you add data-binding into your project by.
You are not suppose to call getViewStub method this way. binding.stub is already the ViewStub which you put in your layout item_post. You should call binding.stub.setLayoutResource()
Android Studio can't recognize ViewStubProxy correctly. Just cast it before manipulate.
import android.databinding.ViewStubProxy;
...
ViewStubProxy viewStubProxy = (ViewStubProxy)(Object)mBinding.viewStub;
if (!viewStubProxy.isInflated()) {
viewStubProxy.getViewStub().inflate();
}
Error is gone :)

Categories

Resources