butterknife | Bind Android views and callbacks to fields and methods | Android library
kandi X-RAY | butterknife Summary
Support
Quality
Security
License
Reuse
- Parse a listener annotation .
- Adds the method bindings to the result .
- Create a new argument transformer .
- Get a drawable for a specific resource id .
- Gets the required bindings .
- Override in order to set the activity s fields .
- Handle a click event .
- Generate code block
- Unbinds all bindings .
- Runs the given actions on the given list .
butterknife Key Features
butterknife Examples and Code Snippets
Trending Discussions on butterknife
Trending Discussions on butterknife
QUESTION
I have configured crashlytics as per Firebase Documentation https://firebase.google.com/docs/crashlytics/get-started?platform=android. But crash reports not generated and uploaded to server.
Kindly refer my build details.
Here is our project-level build.gradle
buildscript {
repositories {
google()
jcenter()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:4.2.1'
classpath 'com.google.gms:google-services:4.3.10'
classpath 'com.google.firebase:firebase-crashlytics-gradle:2.8.1'
}
}
allprojects {
repositories {
google()
jcenter()
maven { url 'https://jitpack.io'}
maven{ url 'https://maven.google.com/' }
mavenCentral()
flatDir {
dirs 'libs'
}
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
build.gradle(:app)
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.google.firebase.crashlytics'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.XXX.XXX"
minSdkVersion 21
targetSdkVersion 28
versionCode 375
versionName "2.25.1"
multiDexEnabled true
testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
dataBinding {
enabled = true
}
signingConfig signingConfigs.config
}
android {
lintOptions {
checkReleaseBuilds false
abortOnError false
}
}
flavorDimensions "appVariant", "projectCode"
productFlavors {
A {
applicationId 'com.XXX.A'
dimension "appVariant"
}
B {
applicationId 'com.XXX.B'
dimension "appVariant"
}
C {
applicationId 'com.XXX.C'
dimension "appVariant"
}
D {
applicationId 'com.XXX.D'
dimension "appVariant"
}
DEV {
dimension "projectCode"
}
QA {
dimension "projectCode"
}
LIVE {
dimension "projectCode"
}
DEMO {
dimension "projectCode"
}
BETA {
dimension "projectCode"
}
}
applicationVariants.all { variant ->
variant.outputs.all { output ->
def project = "XXX"
def SEP = "_"
def flavor = variant.productFlavors[0].name
def projcode = variant.productFlavors[1].name
def buildType = variant.buildType.name
def buildTypeName = "";
switch (buildType) {
case "ABC": buildTypeName = SEP + "AB"; break;
case "XYZ": buildTypeName = SEP + "XY"; break;
default:
buildTypeName = "";
}
def version = variant.versionName
def newApkName = project + buildTypeName + SEP + flavor + SEP + projcode + SEP + version + ".apk"
outputFileName = new File(newApkName)
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
buildTypes {
debug {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
signingConfig signingConfigs.config
buildConfigField "String", "AREA", "\"\""
}
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
signingConfig signingConfigs.config
buildConfigField "String", "AREA", "\"\""
}
ABC {
signingConfig signingConfigs.config
minifyEnabled false
buildConfigField "String", "AREA", "\"_A\""
}
XYZ {
signingConfig signingConfigs.config
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
signingConfig signingConfigs.config
buildConfigField "String", "AREA", "\"_X\""
}
}
packagingOptions {
exclude 'META-INF/DEPENDENCIES.txt'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
exclude 'META-INF/NOTICE'
exclude 'META-INF/LICENSE'
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/notice.txt'
exclude 'META-INF/license.txt'
exclude 'META-INF/dependencies.txt'
exclude 'META-INF/LGPL2.1'
}
}
repositories {
maven {
url 'https://maven.google.com/'
name 'Google'
}
}
dependencies {
def room_version = "1.1.1"
def lifecycle_version = "1.1.1"
def work_version = "1.0.0-beta01"
implementation files('libs/commons-net-3.3.jar')
implementation files('libs/httpclient-4.3.4.jar')
implementation files('libs/httpcore-4.3.2.jar')
implementation files('libs/httpmime-4.3.4.jar')
implementation files('libs/silipmlib.jar')
implementation files('libs/HyperLogLib8.jar')
// Import the BoM for the Firebase platform
implementation platform('com.google.firebase:firebase-bom:29.3.0')
implementation 'com.google.firebase:firebase-crashlytics'
implementation 'com.google.firebase:firebase-analytics'
implementation 'com.google.firebase:firebase-messaging'
//dependency for Workmanager
implementation 'androidx.work:work-runtime:2.0.1'
//dependencies for Room database
implementation 'androidx.room:room-runtime:2.0.0'
//noinspection GradleCompatible
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
annotationProcessor 'androidx.room:room-compiler:2.0.0'
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'androidx.appcompat:appcompat:1.0.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.google.android.material:material:1.0.0'
//dependency for custom progress dialog
//dependency for retrofit
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.google.code.gson:gson:2.8.0'
implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
//dependency for joda time for date time calculation
implementation 'joda-time:joda-time:2.10'
//dependency for glide
implementation 'com.github.bumptech.glide:glide:3.7.0'
//dependency for custom toast
implementation 'com.valdesekamdem.library:md-toast:0.9.0'
//dependency for marshmallow permission - dexter library
implementation 'com.karumi:dexter:4.2.0'
// ViewModel and LiveData
implementation 'androidx.lifecycle:lifecycle-extensions:2.0.0'
annotationProcessor 'androidx.lifecycle:lifecycle-compiler:2.0.0'
// alternately - if using Java8, use the following instead of compiler
implementation 'androidx.lifecycle:lifecycle-common-java8:2.0.0'
implementation 'com.jakewharton:butterknife:10.1.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:10.1.0'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0'
implementation project(':floatingmenu')
implementation project(':html2bitmap')
debugImplementation 'com.amitshekhar.android:debug-db:1.0.4'
implementation 'androidx.lifecycle:lifecycle-extensions:2.0.0'
implementation 'com.github.vipulasri:timelineview:1.0.6'
implementation 'me.relex:circleindicator:1.2.2@aar'
implementation 'com.haozhang.libary:android-slanted-textview:1.2'
implementation 'com.google.android.gms:play-services-maps:15.0.1'
implementation 'com.google.android.gms:play-services-location:15.0.1'
// implementation 'com.google.android.gms:play-services-gcm:11.8.0'
// implementation 'com.google.android.gms:play-services-ads:11.8.0'
implementation('com.github.florent37:materialviewpager:1.2.3') {
exclude group: 'com.android.support'
}
implementation 'com.orhanobut:dialogplus:1.11@aar'
// implementation 'me.dm7.barcodescanner:zbar:1.8.4'
implementation 'me.dm7.barcodescanner:zxing:1.9'
implementation 'com.journeyapps:zxing-android-embedded:2.3.0@aar'
implementation 'com.journeyapps:zxing-android-legacy:2.3.0@aar'
implementation 'com.journeyapps:zxing-android-integration:2.3.0@aar'
implementation 'com.google.zxing:core:3.2.0'
implementation 'net.cachapa.expandablelayout:expandablelayout:2.9.2'
implementation 'com.github.siyamed:android-shape-imageview:0.9.+@aar'
implementation files('libs/HyperLogLib8.jar')
implementation project(':scandecode-release')
implementation 'com.tt:whorlviewlibrary:1.0.3'
implementation 'io.reactivex:rxandroid:1.2.1'
implementation 'io.reactivex:rxjava:1.1.6'
implementation 'com.jakewharton.rxbinding:rxbinding:0.4.0'
implementation 'com.jakewharton.rxbinding:rxbinding-design:0.4.0'
implementation 'org.apache.commons:commons-text:1.7'
// these are for retrolambda and streams api
implementation 'com.annimon:stream:1.1.2'
}
With initialisation:
FirebaseApp.initializeApp(this)
FirebaseCrashlytics.getInstance().setCrashlyticsCollectionEnabled(true)
And manifest:
Here is the logcat for the Crashlytics/CrashTest crash:
2022-04-10 15:53:07.717 21310-21310/com.XXX.XXX E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.XXX.XXX, PID: 21310
java.lang.RuntimeException: Test Crash
at com.XXX.XXX.UI.HomeActivity$1.onClick(HomeActivity.java:345)
at android.view.View.performClick(View.java:6392)
at android.view.View$PerformClick.run(View.java:25133)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:198)
at android.app.ActivityThread.main(ActivityThread.java:7055)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:523)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:836)
This is the log that we receive when app relaunched after crash.
D:\user\Android Projects\XXX>adb logcat -s FirebaseCrashlytics
--------- beginning of main
--------- beginning of system
--------- beginning of crash
04-10 15:54:56.911 22018 22018 I FirebaseCrashlytics: Initializing Firebase Crashlytics 18.2.9 for com.XXX.XXX
04-10 15:54:56.926 22018 22018 D FirebaseCrashlytics: Crashlytics automatic data collection ENABLED by API.
04-10 15:54:56.940 22018 22018 D FirebaseCrashlytics: AnalyticsConnector now available.
04-10 15:54:56.943 22018 22018 D FirebaseCrashlytics: Registered Firebase Analytics listener.
04-10 15:54:56.948 22018 22018 D FirebaseCrashlytics: Mapping file ID is: 00000000000000000000000000000000
04-10 15:54:56.958 22018 22018 D FirebaseCrashlytics: Checking for cached settings...
04-10 15:54:56.992 22018 22018 D FirebaseCrashlytics: Loaded cached settings: {"settings_version":3,"cache_duration":86400,"features":{"collect_logged_exceptions":true,"collect_reports":
true,"collect_analytics":false,"prompt_enabled":false,"push_enabled":false,"firebase_crashlytics_enabled":false,"collect_anrs":true,"collect_metric_kit":false},"app":{"status":"activated
","update_required":false,"report_upload_variant":2,"native_report_upload_variant":2},"fabric":{"org_id":"62513aa60277ea5e0396d4ef","bundle_id":"com.XXX.XXX"},"on_demand_
upload_rate_per_minute":10,"on_demand_backoff_base":1.2,"on_demand_backoff_step_duration_seconds":60,"expires_at":1649666891559}
04-10 15:54:56.996 22018 22018 D FirebaseCrashlytics: Crashlytics automatic data collection ENABLED by API.
04-10 15:54:57.113 22018 22018 D FirebaseCrashlytics: Successfully configured exception handler.
04-10 15:54:57.116 22018 22049 D FirebaseCrashlytics: Opening a new session with ID 6252B07803E20001560228F94565CB5E
04-10 15:54:57.183 22018 22049 D FirebaseCrashlytics: Registered Firebase Analytics event receiver for breadcrumbs
04-10 15:54:58.013 22018 22018 D FirebaseCrashlytics: Crashlytics automatic data collection ENABLED by API.
04-10 15:54:58.642 22018 22018 D FirebaseCrashlytics: Crashlytics automatic data collection ENABLED by API.
These are set to false in cached settings:
"collect_analytics":false,
"firebase_crashlytics_enabled":false,
This setting was weird. Both of them are false for some reason though I never did turn them off explicitly. Never even played with these settings.
Not sure what is wrong. Any help will be appreciated.
ANSWER
Answered 2022-Apr-11 at 14:08Solved!..
There was another utility logger library initialized in the application class that prevented crashlytics from collecting log. https://github.com/hypertrack/hyperlog-android
Also the initialization & manifest part is not necessary unless you want to explicitly enable/disable crashlytics working.
QUESTION
I need to update an app that hasn't been updated since 2018.
I haven't messed with Android for a while, and even after updating all the libraries used, I can't find where the error is. I don't even know how many questions I've read here, and none of them have worked so far. So I decided to open my own question.
Here is the project build.gradle:
buildscript {
repositories {
mavenCentral()
maven {
url "https://jitpack.io"
}
maven {
url 'https://maven.google.com/'
name 'Google'
}
google()
}
dependencies {
classpath "com.android.tools.build:gradle:7.0.4"
classpath 'com.google.gms:google-services:4.3.10'
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
classpath 'com.google.firebase:firebase-crashlytics-gradle:2.8.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
mavenCentral()
maven {
url "https://jitpack.io"
}
maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
google()
}
}
app build.grade:
plugins {
id 'com.android.application'
//id 'io.fabric'
id 'com.google.firebase.crashlytics'
id 'com.google.gms.google-services'
//id 'android-apt'
//id 'kotlin-kapt'
//id 'kotlin-android-extensions'
//id 'kotlin-android'
}
android {
compileSdkVersion 31
buildToolsVersion '30.0.2'
targetSdkVersion 27
minSdk 21
//implementation 'com.android.support:appcompat-v7:27.1.1'
buildFeatures {
viewBinding true
}
lintOptions {
disable 'InvalidPackage'
checkReleaseBuilds true
// Or, if you prefer, you can continue to check for errors in release builds,
// but continue the build even when errors are found:
abortOnError true
}
defaultConfig {
applicationId "llamaze.com.br.whattodraw"
minSdkVersion 15
targetSdkVersion 31
versionCode 20
versionName "1.51"
vectorDrawables.useSupportLibrary = true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'androidx.legacy:legacy-support-v13:1.0.0'
implementation 'androidx.appcompat:appcompat:1.4.1'
implementation "com.google.android.material:material:${materialVersion}"
implementation 'androidx.vectordrawable:vectordrawable-animated:1.1.0'
implementation 'androidx.browser:browser:1.4.0'
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'com.google.android.material:material:1.5.0'
implementation 'androidx.palette:palette:1.0.0'
implementation 'androidx.preference:preference:1.1.1'
implementation 'androidx.legacy:legacy-preference-v14:1.0.0'
implementation 'com.google.android.gms:play-services-analytics:18.0.1'
implementation 'com.jakewharton:butterknife:10.1.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:10.1.0'
implementation 'com.google.firebase:firebase-crash:16.2.1'
implementation 'com.google.firebase:firebase-invites:17.0.0'
implementation 'com.google.firebase:firebase-core:20.0.2'
implementation 'com.google.firebase:firebase-messaging:23.0.0'
implementation 'com.firebase:firebase-jobdispatcher:0.6.0'
implementation "androidx.recyclerview:recyclerview:${androidX}"
implementation 'com.google.firebase:firebase-crashlytics:18.2.6'
implementation 'com.facebook.android:facebook-android-sdk:latest.release'
//Para o review do dropdown menu
implementation ('com.github.ozodrukh:CircularReveal:2.0.1@aar') {
transitive = true;
}
//Busca update do app
implementation 'com.github.rampo.updatechecker:library:2.1.8'
//Adapter para multiselect
implementation('com.mikepenz:fastadapter:1.5.2@aar') {
transitive = true
}
implementation "com.mikepenz:fastadapter:${latestFastAdapterRelease}"
implementation "com.mikepenz:fastadapter-extensions-expandable:${latestFastAdapterRelease}"
implementation "com.mikepenz:fastadapter-extensions-binding:${latestFastAdapterRelease}" // view binding helpers
implementation "com.mikepenz:fastadapter-extensions-diff:${latestFastAdapterRelease}" // diff util helpers
implementation "com.mikepenz:fastadapter-extensions-drag:${latestFastAdapterRelease}" // drag support
implementation "com.mikepenz:fastadapter-extensions-paged:${latestFastAdapterRelease}" // paging support
implementation "com.mikepenz:fastadapter-extensions-scroll:${latestFastAdapterRelease}" // scroll helpers
implementation "com.mikepenz:fastadapter-extensions-swipe:${latestFastAdapterRelease}" // swipe support
implementation "com.mikepenz:fastadapter-extensions-ui:${latestFastAdapterRelease}" // pre-defined ui components
implementation "com.mikepenz:fastadapter-extensions-utils:${latestFastAdapterRelease}" // needs the `expandable`, `drag` and `scroll` extension.
implementation 'com.mikepenz:materialize:1.2.1'
implementation 'com.github.javiersantos:BottomDialogs:1.2.1'
//Show room do app
implementation 'com.github.wooplr:Spotlight:1.2.3'
//Disparar ações quando instala/update/etc
implementation 'com.github.prashantsolanki3:Shoot:0.8.3'
//Material Eidt Text
implementation 'com.rengwuxian.materialedittext:library:2.1.4'
//Load de imagens
implementation 'com.github.bumptech.glide:glide:4.12.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.12.0'
//Data base
implementation 'org.litepal.android:core:3.2.3'
//Dialogs
implementation 'com.afollestad.material-dialogs:core:3.3.0'
//okhttp
implementation 'com.squareup.okhttp3:okhttp:4.9.0'
//target primeira vez que abre o app
implementation 'uk.co.samuelwall:material-tap-target-prompt:3.3.2'
//Automatiza tamanho do texto
//compile 'me.grantland:autofittextview:0.2.+'
//animação do botão like
//compile 'hanks.xyz:smallbang-library:0.1.2'
implementation 'pub.hanks:smallbang:1.2.2'
//In-app purchase
implementation 'com.anjlab.android.iab.v3:library:2.0.3'
//PrefManager protegido
implementation 'com.github.prashantsolanki3:Secure-Pref-Manager:0.25'
implementation 'com.github.zzz40500:AndroidSweetSheet:1.1.0'
implementation 'com.github.florent37:expansionpanel:1.2.4'
}
gradle.wrapper:
distributionBase=GRADLE_USER_HOME
distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-bin.zip
distributionPath=wrapper/dists
zipStorePath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
the error log:
Build file 'C:\Users\***\Documents\***\app\build.gradle' line: 20
A problem occurred evaluating project ':app'.
> No signature of method: build_6075gp011x3gyj1eak294unrj.android() is applicable for argument types: (build_6075gp011x3gyj1eak294unrj$_run_closure1) values: [build_6075gp011x3gyj1eak294unrj$_run_closure1@395bc463]
* Try:
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.
* Exception is:
org.gradle.api.GradleScriptException: A problem occurred evaluating project ':app'.
at org.gradle.groovy.scripts.internal.DefaultScriptRunnerFactory$ScriptRunnerImpl.run(DefaultScriptRunnerFactory.java:93)
at org.gradle.configuration.DefaultScriptPluginFactory$ScriptPluginImpl.lambda$apply$0(DefaultScriptPluginFactory.java:133)
at org.gradle.configuration.ProjectScriptTarget.addConfiguration(ProjectScriptTarget.java:79)
at org.gradle.configuration.DefaultScriptPluginFactory$ScriptPluginImpl.apply(DefaultScriptPluginFactory.java:136)
at org.gradle.configuration.BuildOperationScriptPlugin$1.run(BuildOperationScriptPlugin.java:65)
at org.gradle.internal.operations.DefaultBuildOperationRunner$1.execute(DefaultBuildOperationRunner.java:29)
at org.gradle.internal.operations.DefaultBuildOperationRunner$1.execute(DefaultBuildOperationRunner.java:26)
at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:66)
at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:59)
at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:157)
at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:59)
at org.gradle.internal.operations.DefaultBuildOperationRunner.run(DefaultBuildOperationRunner.java:47)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:68)
at org.gradle.configuration.BuildOperationScriptPlugin.lambda$apply$0(BuildOperationScriptPlugin.java:62)
at org.gradle.configuration.internal.DefaultUserCodeApplicationContext.apply(DefaultUserCodeApplicationContext.java:44)
at org.gradle.configuration.BuildOperationScriptPlugin.apply(BuildOperationScriptPlugin.java:62)
at org.gradle.api.internal.project.DefaultProjectStateRegistry$ProjectStateImpl.lambda$applyToMutableState$0(DefaultProjectStateRegistry.java:366)
at org.gradle.api.internal.project.DefaultProjectStateRegistry$ProjectStateImpl.fromMutableState(DefaultProjectStateRegistry.java:393)
at org.gradle.api.internal.project.DefaultProjectStateRegistry$ProjectStateImpl.applyToMutableState(DefaultProjectStateRegistry.java:365)
at org.gradle.configuration.project.BuildScriptProcessor.execute(BuildScriptProcessor.java:42)
at org.gradle.configuration.project.BuildScriptProcessor.execute(BuildScriptProcessor.java:26)
at org.gradle.configuration.project.ConfigureActionsProjectEvaluator.evaluate(ConfigureActionsProjectEvaluator.java:35)
at org.gradle.configuration.project.LifecycleProjectEvaluator$EvaluateProject.lambda$run$0(LifecycleProjectEvaluator.java:100)
at org.gradle.api.internal.project.DefaultProjectStateRegistry$ProjectStateImpl.lambda$applyToMutableState$0(DefaultProjectStateRegistry.java:366)
at org.gradle.api.internal.project.DefaultProjectStateRegistry$ProjectStateImpl.lambda$withProjectLock$3(DefaultProjectStateRegistry.java:426)
at org.gradle.internal.work.DefaultWorkerLeaseService.withLocks(DefaultWorkerLeaseService.java:211)
at org.gradle.api.internal.project.DefaultProjectStateRegistry$ProjectStateImpl.withProjectLock(DefaultProjectStateRegistry.java:426)
at org.gradle.api.internal.project.DefaultProjectStateRegistry$ProjectStateImpl.fromMutableState(DefaultProjectStateRegistry.java:407)
at org.gradle.api.internal.project.DefaultProjectStateRegistry$ProjectStateImpl.applyToMutableState(DefaultProjectStateRegistry.java:365)
at org.gradle.configuration.project.LifecycleProjectEvaluator$EvaluateProject.run(LifecycleProjectEvaluator.java:91)
at org.gradle.internal.operations.DefaultBuildOperationRunner$1.execute(DefaultBuildOperationRunner.java:29)
at org.gradle.internal.operations.DefaultBuildOperationRunner$1.execute(DefaultBuildOperationRunner.java:26)
at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:66)
at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:59)
at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:157)
at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:59)
at org.gradle.internal.operations.DefaultBuildOperationRunner.run(DefaultBuildOperationRunner.java:47)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:68)
at org.gradle.configuration.project.LifecycleProjectEvaluator.evaluate(LifecycleProjectEvaluator.java:63)
at org.gradle.api.internal.project.DefaultProject.evaluate(DefaultProject.java:751)
at org.gradle.api.internal.project.DefaultProject.evaluate(DefaultProject.java:151)
at org.gradle.api.internal.project.DefaultProjectStateRegistry$ProjectStateImpl.ensureConfigured(DefaultProjectStateRegistry.java:339)
at org.gradle.execution.TaskPathProjectEvaluator.configure(TaskPathProjectEvaluator.java:41)
at org.gradle.execution.TaskPathProjectEvaluator.configureHierarchy(TaskPathProjectEvaluator.java:57)
at org.gradle.configuration.DefaultProjectsPreparer.prepareProjects(DefaultProjectsPreparer.java:48)
at org.gradle.configuration.BuildTreePreparingProjectsPreparer.prepareProjects(BuildTreePreparingProjectsPreparer.java:64)
at org.gradle.configuration.BuildOperationFiringProjectsPreparer$ConfigureBuild.run(BuildOperationFiringProjectsPreparer.java:52)
at org.gradle.internal.operations.DefaultBuildOperationRunner$1.execute(DefaultBuildOperationRunner.java:29)
at org.gradle.internal.operations.DefaultBuildOperationRunner$1.execute(DefaultBuildOperationRunner.java:26)
at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:66)
at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:59)
at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:157)
at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:59)
at org.gradle.internal.operations.DefaultBuildOperationRunner.run(DefaultBuildOperationRunner.java:47)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:68)
at org.gradle.configuration.BuildOperationFiringProjectsPreparer.prepareProjects(BuildOperationFiringProjectsPreparer.java:40)
at org.gradle.initialization.VintageBuildModelController.lambda$prepareProjects$1(VintageBuildModelController.java:93)
at org.gradle.internal.build.StateTransitionController.lambda$doTransition$1(StateTransitionController.java:222)
at org.gradle.internal.build.StateTransitionController.doTransition(StateTransitionController.java:243)
at org.gradle.internal.build.StateTransitionController.doTransition(StateTransitionController.java:221)
at org.gradle.internal.build.StateTransitionController.transitionIfNotPreviously(StateTransitionController.java:190)
at org.gradle.initialization.VintageBuildModelController.prepareProjects(VintageBuildModelController.java:93)
at org.gradle.initialization.VintageBuildModelController.doBuildStages(VintageBuildModelController.java:77)
at org.gradle.initialization.VintageBuildModelController.getConfiguredModel(VintageBuildModelController.java:58)
at org.gradle.internal.build.StateTransitionController.notInStateIgnoreOtherThreads(StateTransitionController.java:89)
at org.gradle.internal.build.DefaultBuildLifecycleController.getConfiguredBuild(DefaultBuildLifecycleController.java:98)
at org.gradle.internal.build.AbstractBuildState.ensureProjectsConfigured(AbstractBuildState.java:65)
at org.gradle.internal.buildtree.DefaultBuildTreeModelCreator$DefaultBuildToolingModelController.locateBuilderForTarget(DefaultBuildTreeModelCreator.java:90)
at org.gradle.internal.buildtree.DefaultBuildTreeModelCreator$DefaultBuildToolingModelController.locateBuilderForDefaultTarget(DefaultBuildTreeModelCreator.java:82)
at org.gradle.tooling.internal.provider.runner.DefaultBuildController$DefaultTargetModel.locate(DefaultBuildController.java:239)
at org.gradle.tooling.internal.provider.runner.DefaultBuildController.getToolingModelBuilder(DefaultBuildController.java:184)
at org.gradle.tooling.internal.provider.runner.DefaultBuildController.getModel(DefaultBuildController.java:98)
at org.gradle.tooling.internal.consumer.connection.ParameterAwareBuildControllerAdapter.getModel(ParameterAwareBuildControllerAdapter.java:39)
at org.gradle.tooling.internal.consumer.connection.UnparameterizedBuildController.getModel(UnparameterizedBuildController.java:113)
at org.gradle.tooling.internal.consumer.connection.NestedActionAwareBuildControllerAdapter.getModel(NestedActionAwareBuildControllerAdapter.java:31)
at org.gradle.tooling.internal.consumer.connection.UnparameterizedBuildController.getModel(UnparameterizedBuildController.java:76)
at org.gradle.tooling.internal.consumer.connection.NestedActionAwareBuildControllerAdapter.getModel(NestedActionAwareBuildControllerAdapter.java:31)
at org.gradle.tooling.internal.consumer.connection.UnparameterizedBuildController.getModel(UnparameterizedBuildController.java:61)
at org.gradle.tooling.internal.consumer.connection.NestedActionAwareBuildControllerAdapter.getModel(NestedActionAwareBuildControllerAdapter.java:31)
at org.jetbrains.plugins.gradle.model.ProjectImportAction.execute(ProjectImportAction.java:95)
at org.jetbrains.plugins.gradle.model.ProjectImportAction.execute(ProjectImportAction.java:41)
at org.gradle.tooling.internal.consumer.connection.InternalBuildActionAdapter.execute(InternalBuildActionAdapter.java:64)
at org.gradle.tooling.internal.provider.runner.AbstractClientProvidedBuildActionRunner$ActionAdapter.runAction(AbstractClientProvidedBuildActionRunner.java:131)
at org.gradle.tooling.internal.provider.runner.AbstractClientProvidedBuildActionRunner$ActionAdapter.beforeTasks(AbstractClientProvidedBuildActionRunner.java:99)
at org.gradle.internal.buildtree.DefaultBuildTreeModelCreator.beforeTasks(DefaultBuildTreeModelCreator.java:57)
at org.gradle.internal.buildtree.DefaultBuildTreeLifecycleController.lambda$fromBuildModel$1(DefaultBuildTreeLifecycleController.java:72)
at org.gradle.internal.buildtree.DefaultBuildTreeLifecycleController.lambda$runBuild$4(DefaultBuildTreeLifecycleController.java:103)
at org.gradle.internal.build.StateTransitionController.lambda$transition$0(StateTransitionController.java:145)
at org.gradle.internal.build.StateTransitionController.doTransition(StateTransitionController.java:243)
at org.gradle.internal.build.StateTransitionController.transition(StateTransitionController.java:145)
at org.gradle.internal.buildtree.DefaultBuildTreeLifecycleController.runBuild(DefaultBuildTreeLifecycleController.java:100)
at org.gradle.internal.buildtree.DefaultBuildTreeLifecycleController.fromBuildModel(DefaultBuildTreeLifecycleController.java:71)
at org.gradle.tooling.internal.provider.runner.AbstractClientProvidedBuildActionRunner.runClientAction(AbstractClientProvidedBuildActionRunner.java:43)
at org.gradle.tooling.internal.provider.runner.ClientProvidedPhasedActionRunner.run(ClientProvidedPhasedActionRunner.java:53)
at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
at org.gradle.internal.buildtree.ProblemReportingBuildActionRunner.run(ProblemReportingBuildActionRunner.java:49)
at org.gradle.launcher.exec.BuildOutcomeReportingBuildActionRunner.run(BuildOutcomeReportingBuildActionRunner.java:69)
at org.gradle.tooling.internal.provider.FileSystemWatchingBuildActionRunner.run(FileSystemWatchingBuildActionRunner.java:114)
at org.gradle.launcher.exec.BuildCompletionNotifyingBuildActionRunner.run(BuildCompletionNotifyingBuildActionRunner.java:41)
at org.gradle.launcher.exec.RootBuildLifecycleBuildActionExecutor.lambda$execute$0(RootBuildLifecycleBuildActionExecutor.java:40)
at org.gradle.composite.internal.DefaultRootBuildState.run(DefaultRootBuildState.java:155)
at org.gradle.launcher.exec.RootBuildLifecycleBuildActionExecutor.execute(RootBuildLifecycleBuildActionExecutor.java:40)
at org.gradle.internal.buildtree.DefaultBuildTreeContext.execute(DefaultBuildTreeContext.java:40)
at org.gradle.launcher.exec.BuildTreeLifecycleBuildActionExecutor.lambda$execute$0(BuildTreeLifecycleBuildActionExecutor.java:65)
at org.gradle.internal.buildtree.BuildTreeState.run(BuildTreeState.java:53)
at org.gradle.launcher.exec.BuildTreeLifecycleBuildActionExecutor.execute(BuildTreeLifecycleBuildActionExecutor.java:65)
at org.gradle.launcher.exec.RunAsBuildOperationBuildActionExecutor$3.call(RunAsBuildOperationBuildActionExecutor.java:61)
at org.gradle.launcher.exec.RunAsBuildOperationBuildActionExecutor$3.call(RunAsBuildOperationBuildActionExecutor.java:57)
at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:204)
at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:199)
at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:66)
at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:59)
at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:157)
at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:59)
at org.gradle.internal.operations.DefaultBuildOperationRunner.call(DefaultBuildOperationRunner.java:53)
at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:73)
at org.gradle.launcher.exec.RunAsBuildOperationBuildActionExecutor.execute(RunAsBuildOperationBuildActionExecutor.java:57)
at org.gradle.launcher.exec.RunAsWorkerThreadBuildActionExecutor.lambda$execute$0(RunAsWorkerThreadBuildActionExecutor.java:38)
at org.gradle.internal.work.DefaultWorkerLeaseService.withLocks(DefaultWorkerLeaseService.java:211)
at org.gradle.launcher.exec.RunAsWorkerThreadBuildActionExecutor.execute(RunAsWorkerThreadBuildActionExecutor.java:38)
at org.gradle.tooling.internal.provider.ContinuousBuildActionExecutor.execute(ContinuousBuildActionExecutor.java:103)
at org.gradle.tooling.internal.provider.SubscribableBuildActionExecutor.execute(SubscribableBuildActionExecutor.java:64)
at org.gradle.internal.session.DefaultBuildSessionContext.execute(DefaultBuildSessionContext.java:46)
at org.gradle.tooling.internal.provider.BuildSessionLifecycleBuildActionExecuter$ActionImpl.apply(BuildSessionLifecycleBuildActionExecuter.java:100)
at org.gradle.tooling.internal.provider.BuildSessionLifecycleBuildActionExecuter$ActionImpl.apply(BuildSessionLifecycleBuildActionExecuter.java:88)
at org.gradle.internal.session.BuildSessionState.run(BuildSessionState.java:69)
at org.gradle.tooling.internal.provider.BuildSessionLifecycleBuildActionExecuter.execute(BuildSessionLifecycleBuildActionExecuter.java:62)
at org.gradle.tooling.internal.provider.BuildSessionLifecycleBuildActionExecuter.execute(BuildSessionLifecycleBuildActionExecuter.java:41)
at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:36)
at org.gradle.tooling.internal.provider.GradleThreadBuildActionExecuter.execute(GradleThreadBuildActionExecuter.java:25)
at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:63)
at org.gradle.tooling.internal.provider.StartParamsValidatingActionExecuter.execute(StartParamsValidatingActionExecuter.java:31)
at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:58)
at org.gradle.tooling.internal.provider.SessionFailureReportingActionExecuter.execute(SessionFailureReportingActionExecuter.java:42)
at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:47)
at org.gradle.tooling.internal.provider.SetupLoggingActionExecuter.execute(SetupLoggingActionExecuter.java:31)
at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:65)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:37)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:104)
at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:39)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:104)
at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:29)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:104)
at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:35)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:104)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.create(ForwardClientInput.java:78)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.create(ForwardClientInput.java:75)
at org.gradle.util.internal.Swapper.swap(Swapper.java:38)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:75)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:104)
at org.gradle.launcher.daemon.server.exec.LogAndCheckHealth.execute(LogAndCheckHealth.java:55)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:104)
at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:63)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:37)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:104)
at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:84)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:37)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:104)
at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:52)
at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:297)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:61)
Caused by: groovy.lang.MissingMethodException: No signature of method: build_6075gp011x3gyj1eak294unrj.android() is applicable for argument types: (build_6075gp011x3gyj1eak294unrj$_run_closure1) values: [build_6075gp011x3gyj1eak294unrj$_run_closure1@395bc463]
at build_6075gp011x3gyj1eak294unrj.run(C:\Users\***\Documents\***\app\build.gradle:20)
at org.gradle.groovy.scripts.internal.DefaultScriptRunnerFactory$ScriptRunnerImpl.run(DefaultScriptRunnerFactory.java:91)
... 162 more
Thks in advance
ANSWER
Answered 2022-Jan-21 at 12:38Convert this:
buildToolsVersion '30.0.2'
to this:
buildToolsVersion "30.0.2"
(Note the double quotes + Upgrade it to the latest version if possible)
Also, these lines are of no use since you are already using google():
maven {
url 'https://maven.google.com/'
name 'Google'
}
Also, you have declared these twice:
targetSdkVersion 27
minSdk 21
Remove the ones just inside android{..}
Some of your dependencies also use double quotes, try changing them to single ones.
QUESTION
I've inflated a PopupWindow using the method .showAsDropDown()
however I'm not sure why It's not allowing me to shift it right or left. It works perfectly fine when shifting up and down.
public class TestWindow extends PopupWindow {
private final Context context;
public TestWindow (Context context) {
super(context);
this.context = context;
setupView();
}
private void setupView() {
View view = LayoutInflater.from(context)
.inflate(R.layout.popup_window_wallet_options, null);
ButterKnife.bind(this, view);
setOutsideTouchable(true);
setFocusable(true);
setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.bgr_menu_clear_wallet));
setElevation(SpacingUtils.convertIntToDP(context, 4));
setContentView(view);
}
}
PopupWindow popupWindow = new TestWindow(context);
popupWindow.showAsDropDown(anchorButton, 50, -30);
Shifting the menu up by 30 works perfectly fine, but also I'm trying to shift it towards the left and it's not working. What am I doing incorrectly?
Note:
I've already tried it with 50
and -50
so I'm at lost why it's not moving horizontally
My R.layout.popup_window_wallet_options
ANSWER
Answered 2022-Jan-01 at 17:36Disclaimer: This is not a direct fix to
showAsDropDown()
, but it could be a workaround withshowAtLocation()
.
By using the window decorView as the anchorView, and accumulating the actual anchorView location to x & y shift values.
int[] anchorView = new int[2];
anchorButton.getLocationInWindow(anchorView); // anchor button location in the window
popupWindow.showAtLocation(getWindow().getDecorView(), Gravity.NO_GRAVITY,
anchorView[0] + 50,
anchorView[1] + anchorButton.getHeight() -30);
UPDATE:
The anchorButton is an ImageView. Can you post your code + xml for it
Nothing special than yours. This is the popup window layout
The activity just has a button as the anchorView:
And calling it:
Button button = findViewById(R.id.button);
PopupWindow popupWindow = new TestWindow(MainActivity.this);
popupWindow.showAsDropDown(button, 50, -30);
QUESTION
I'm trying to learn MVVM architecture by having displaying a list after querying an API. I'm a bit unsure on how I should deal with the issue of rotating my device because once I rotate it, my onCreate
method is called again and a second query to the API is called. Where should I place my network call so it doesn't perform another query when the screen orientation changes?
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
viewModel = new ViewModelProvider(this).get(PostViewModel.class);
adapter = new PostAdapter(viewModel.getListPosts());
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
viewModel.getGetPostsLiveData().observe(this, listPosts -> {
Log.d(TAG, "onCreate: Called...");
adapter.notifyDataSetChanged();
});
viewModel.getPosts();
}
My method viewModel.getPosts();
performs the query and is called again when the device screen orientation changes.
According to this answer:
onPause();
onSaveInstanceState();
onStop();
onDestroy();
onCreate();
onStart();
onResume();
This is the lifecycle of a screen orientation change. For those 3 methods, onCreate, onStart, and onResume
they are called once when the app opens and are called again everytime the screen changes. So I am unsure where I should place request to make the network call at.
ANSWER
Answered 2021-Dec-13 at 17:07If it's a one time call you could just call it from your ViewModel.
init {
getPosts()
}
QUESTION
I am trying to run a TensorFlow-lite model on my App on a smartphone. First, I trained the model with numerical data using LSTM and build the model layer using TensorFlow.Keras. I used TensorFlow V2.x and saved the trained model on a server. After that, the model is downloaded to the internal memory of the smartphone by the App and loaded to the interpreter using "MappedByteBuffer". Until here everything is working correctly.
The problem is in the interpreter can not read and run the model. I also added the required dependencies on the build.gradle.
The conversion code to tflite model in python:
from tensorflow import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, LSTM
from tensorflow.keras import regularizers
#Create the network
model = Sequential()
model.add(LSTM(...... name = 'First_layer'))
model.add(Dropout(rate=Drop_out))
model.add(LSTM(...... name = 'Second_layer'))
model.add(Dropout(rate=Drop_out))
# compile model
model.compile(loss=keras.losses.mae,
optimizer=keras.optimizers.Adam(learning_rate=learning_rate), metrics=["mae"])
# fit model
model.fit(.......)
#save the model
tf.saved_model.save(model,'saved_model')
print("Model type", model1.dtype)# Model type is float32 and size around 2MB
#Convert saved model into TFlite
converter = tf.lite.TFLiteConverter.from_saved_model('saved_model')
tflite_model = converter.convert()
with open("Model.tflite, "wb") as f:
f.write(tflite_model)
f.close()
I tried also other conversion way using Keras
# converter = tf.lite.TFLiteConverter.from_keras_model(keras_model)
# tflite_model = converter.convert()
After this step, the "Model.tflite" is converted and downloaded to the internal memory of the smartphone.
Android studio code:
try {
private Interpreter tflite = new Interpreter(loadModelFile());
Log.d("Load_model", "Created a Tensorflow Lite of AutoAuth.");
} catch (IOException e) {
Log.e("Load_model", "IOException loading the tflite file");
}
private MappedByteBuffer loadModelFile() throws IOException {
String model_path = model_directory + model_name + ".tflite";
Log.d(TAG, model_path);
File file = new File(model_path);
if(file!=null){
FileInputStream inputStream = new FileInputStream(file);
FileChannel fileChannel = inputStream.getChannel();
return fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
}else{
return null;
}
}
The "loadModelFile()" function is working correctly because I checked it with another tflite model using MNIST dataset for image classification. The problem is only the interpreter.
This is also build.gradle's contents:
android {
aaptOptions {
noCompress "tflite"
}
}
android {
defaultConfig {
ndk {
abiFilters 'armeabi-v7a', 'arm64-v8a'
}
}
}
dependencies {
implementation 'com.jakewharton:butterknife:8.8.1'
implementation 'org.tensorflow:tensorflow-lite:0.1.2-nightly'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
implementation fileTree(dir: 'libs', include: ['*.jar'])
//noinspection GradleCompatible
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:2.0.4'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
ANSWER
Answered 2021-Nov-24 at 00:05Referring to one of the most recent TfLite android app examples might help: Model Personalization App. This demo app uses transfer learning model instead of LSTM, but the overall workflow should be similar.
As Farmaker mentioned in the comment, try using SNAPSHOT in the gradle dependency:
implementation 'org.tensorflow:tensorflow-lite:0.0.0-nightly-SNAPSHOT'
To load the model properly, can you try:
protected MappedByteBuffer loadMappedFile(String filePath) throws IOException {
AssetFileDescriptor fileDescriptor = assetManager.openFd(this.directoryName + "/" + filePath);
FileInputStream inputStream = new FileInputStream(fileDescriptor.getFileDescriptor());
FileChannel fileChannel = inputStream.getChannel();
long startOffset = fileDescriptor.getStartOffset();
long declaredLength = fileDescriptor.getDeclaredLength();
return fileChannel.map(MapMode.READ_ONLY, startOffset, declaredLength);
}
This snippet can also be found in the GitHub example link I posted above.
QUESTION
I have an Issue with gradle in my Android Project. I feel stupid I could't solve this Issue myself. I closed the project yesterday evening end reopend it this morning, So gradle wasn't touched at all. This morning i got the following error
Could not compile build file 'D:\Code\Android\workouttracker\app\build.gradle'.
> startup failed:
build file 'D:\Code\Android\workouttracker\app\build.gradle': 87: Unexpected input: '{' @ line 87, column 14.
dependencies {
So i guessed it must be a missing braket, but I couldn't find one in my build gradle, maybe I am stupid or blind. I get the same error when I run gradlew in the project direcroy
Here is my build.gradle (After me trieing to fix it)
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
configurations.implementation {
exclude group: 'org.jetbrains' , module:'annotations'
exclude group: 'org.jetbrains.kotlin' , module:'kotlin-stdlib'
exclude group: 'com.intellij', module:'annotations'
exclude group: 'com.intellij', module:'annotations'
exclude group: 'com.intellij', module:'annotations'
}
android {
lintOptions {
checkReleaseBuilds false
// Or, if you prefer, you can continue to check for errors in release builds,
// but continue the build even when errors are found:
abortOnError false
}
compileSdkVersion 30
buildToolsVersion '32.0.0-rc1'
defaultConfig {
applicationId 'ch.workouttracker'
minSdkVersion 28
targetSdkVersion 30
versionCode 901
versionName '0.9.0.1'
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
resConfigs "de" // And any other languages you support
}
signingConfigs {
release {
storeFile file("C:\\Users\\DonBolli\\.android\\debug.keystore")
storePassword ANDROID_STORE_PASSWORD
keyAlias 'workouttrackerkey'
keyPassword ANDROID_KEY_PASSWORD
}
debug {
storeFile file("C:\\Users\\DonBolli\\.android\\debug.keystore")
storePassword ANDROID_STORE_PASSWORD
keyAlias 'workouttrackerkey'
keyPassword ANDROID_KEY_PASSWORD
}
}
buildTypes {
debug {
minifyEnabled false
signingConfig signingConfigs.debug
}
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
signingConfig signingConfigs.release
}
}
packagingOptions {
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE.md'
exclude 'META-INF/LICENSE-FIREBASE.txt'
exclude 'META-INF/NOTICE'
exclude 'META-INF/NOTICE.md'
exclude 'META-INF/DEPENDENCIES'
}
defaultConfig {
vectorDrawables.useSupportLibrary = true
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
allprojects {
repositories {
mavenCentral()
maven { url = "https://maven.fabric.io/public" }
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
//Firebase
implementation platform('com.google.firebase:firebase-bom:29.0.0')
implementation ("com.google.firebase:firebase-core:20.0.0") {
exclude group: "com.android.support", module: "support-v4"
}
implementation 'com.google.firebase:firebase-messaging:23.0.0'
implementation 'com.google.firebase:firebase-analytics:20.0.0'
implementation 'com.google.firebase:firebase-plugins:2.0.0'
implementation 'com.google.firebase:firebase-ml-vision:24.0.0'
implementation ("com.google.firebase:firebase-auth:21.0.1") {
exclude group: "com.android.support", module: "support-v4"
}
implementation 'com.google.firebase:firebase-database:20.0.2'
implementation 'com.google.firebase:firebase-storage:20.0.0'
//CrashAlyrics
implementation 'com.google.firebase:firebase-crashlytics'
implementation 'com.google.firebase:firebase-analytics'
//Graphview
implementation 'com.jjoe64:graphview:4.2.1'
implementation 'org.apache.commons:commons-lang3:3.4'
//Google Play
implementation ("com.google.android.gms:play-services-base:17.6.0") {
exclude group: "com.android.support", module: "support-v4"
}
implementation 'com.google.android.gms:play-services-auth:19.2.0'
//Support
implementation "androidx.appcompat:appcompat:1.1.0"
implementation "androidx.appcompat:appcompat-resources:1.1.0"
implementation "androidx.navigation:navigation-fragment-ktx:2.2.1"
implementation "androidx.drawerlayout:drawerlayout:1.0.0"
implementation "androidx.gridlayout:gridlayout:1.0.0"
implementation "androidx.preference:preference:1.1.0"
implementation "androidx.recyclerview:recyclerview:1.1.0"
implementation "androidx.cardview:cardview:1.0.0"
implementation "io.reactivex.rxjava2:rxjava:2.2.13"
implementation "io.reactivex.rxjava2:rxandroid:2.1.1"
// Gradle
implementation com.android.tools.build:gradle);
//Glide
implementation 'com.github.bumptech.glide:glide:4.11.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
/**
* dependency to request the runtime permissions.
*/
implementation 'com.karumi:dexter:4.2.0'
// code generator for view
implementation "com.jakewharton:butterknife:10.2.0"
annotationProcessor "com.jakewharton:butterknife-compiler:10.2.0"
testImplementation 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'
ANSWER
Answered 2021-Nov-13 at 08:01There was an error inside the dependencies
// Gradle
implementation com.android.tools.build:gradle);
Changed this to
// Gradle
implementation 'com.android.tools.build:gradle'
QUESTION
I have included following dependencies in build.gradle file. I get the following errors. How to fix them.I have included following dependencies in build.gradle file. I get the following errors. How to fix them.I have included following dependencies in build.gradle file. I get the following errors. How to fix them.I have included following dependencies in build.gradle file. I get the following errors. How to fix them.I have included following dependencies in build.gradle file. I get the following errors. How to fix them.I have included following dependencies in build.gradle file. I get the following errors. How to fix them.
build.gradle:
plugins {
id 'com.android.application'
}
android {
compileSdkVersion 30
buildToolsVersion "30.0.3"
useLibrary 'org.apache.http.legacy'
defaultConfig {
applicationId "com.example.testimageuploadhttp"
minSdkVersion 21
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
def butterKnifeVersion = "8.4.0"
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "com.jakewharton:butterknife:${butterKnifeVersion}"
annotationProcessor "com.jakewharton:butterknife-compiler:${butterKnifeVersion}"
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.3.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'androidx.annotation:annotation:1.0.0'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:4.10'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
//implementation fileTree(dir: 'libs', include: ['*.jar'])
testImplementation 'junit:junit:4.12'
//noinspection DuplicatePlatformClasses,DuplicatePlatformClasses
implementation 'com.googlecode.json-simple:json-simple:1.1.1'
//Volley Library - You need to add this line
implementation 'com.mcxiaoke.volley:library-aar:1.0.0'
//Add this line
implementation 'net.gotev:uploadservice:3.4'
}
error:
Duplicate class org.hamcrest.BaseDescription found in modules jetified-hamcrest-core-1.1 (org.hamcrest:hamcrest-core:1.1) and jetified-junit-4.10 (junit:junit:4.10)
Duplicate class org.hamcrest.BaseMatcher found in modules jetified-hamcrest-core-1.1 (org.hamcrest:hamcrest-core:1.1) and jetified-junit-4.10 (junit:junit:4.10)
Duplicate class org.hamcrest.CoreMatchers found in modules jetified-hamcrest-core-1.1 (org.hamcrest:hamcrest-core:1.1) and jetified-junit-4.10 (junit:junit:4.10)
Duplicate class org.hamcrest.Description found in modules jetified-hamcrest-core-1.1 (org.hamcrest:hamcrest-core:1.1) and jetified-junit-4.10 (junit:junit:4.10)
Duplicate class org.hamcrest.Factory found in modules jetified-hamcrest-core-1.1 (org.hamcrest:hamcrest-core:1.1) and jetified-junit-4.10 (junit:junit:4.10)
Duplicate class org.hamcrest.Matcher found in modules jetified-hamcrest-core-1.1 (org.hamcrest:hamcrest-core:1.1) and jetified-junit-4.10 (junit:junit:4.10)
Duplicate class org.hamcrest.SelfDescribing found in modules jetified-hamcrest-core-1.1 (org.hamcrest:hamcrest-core:1.1) and jetified-junit-4.10 (junit:junit:4.10)
Duplicate class org.hamcrest.StringDescription found in modules jetified-hamcrest-core-1.1 (org.hamcrest:hamcrest-core:1.1) and jetified-junit-4.10 (junit:junit:4.10)
Duplicate class org.hamcrest.core.AllOf found in modules jetified-hamcrest-core-1.1 (org.hamcrest:hamcrest-core:1.1) and jetified-junit-4.10 (junit:junit:4.10)
Duplicate class org.hamcrest.core.AnyOf found in modules jetified-hamcrest-core-1.1 (org.hamcrest:hamcrest-core:1.1) and jetified-junit-4.10 (junit:junit:4.10)
Duplicate class org.hamcrest.core.DescribedAs found in modules jetified-hamcrest-core-1.1 (org.hamcrest:hamcrest-core:1.1) and jetified-junit-4.10 (junit:junit:4.10)
Duplicate class org.hamcrest.core.Is found in modules jetified-hamcrest-core-1.1 (org.hamcrest:hamcrest-core:1.1) and jetified-junit-4.10 (junit:junit:4.10)
Duplicate class org.hamcrest.core.IsAnything found in modules jetified-hamcrest-core-1.1 (org.hamcrest:hamcrest-core:1.1) and jetified-junit-4.10 (junit:junit:4.10)
Duplicate class org.hamcrest.core.IsEqual found in modules jetified-hamcrest-core-1.1 (org.hamcrest:hamcrest-core:1.1) and jetified-junit-4.10 (junit:junit:4.10)
Duplicate class org.hamcrest.core.IsInstanceOf found in modules jetified-hamcrest-core-1.1 (org.hamcrest:hamcrest-core:1.1) and jetified-junit-4.10 (junit:junit:4.10)
Duplicate class org.hamcrest.core.IsNot found in modules jetified-hamcrest-core-1.1 (org.hamcrest:hamcrest-core:1.1) and jetified-junit-4.10 (junit:junit:4.10)
Duplicate class org.hamcrest.core.IsNull found in modules jetified-hamcrest-core-1.1 (org.hamcrest:hamcrest-core:1.1) and jetified-junit-4.10 (junit:junit:4.10)
Duplicate class org.hamcrest.core.IsSame found in modules jetified-hamcrest-core-1.1 (org.hamcrest:hamcrest-core:1.1) and jetified-junit-4.10 (junit:junit:4.10)
Duplicate class org.hamcrest.internal.ArrayIterator found in modules jetified-hamcrest-core-1.1 (org.hamcrest:hamcrest-core:1.1) and jetified-junit-4.10 (junit:junit:4.10)
Duplicate class org.hamcrest.internal.SelfDescribingValue found in modules jetified-hamcrest-core-1.1 (org.hamcrest:hamcrest-core:1.1) and jetified-junit-4.10 (junit:junit:4.10)
Duplicate class org.hamcrest.internal.SelfDescribingValueIterator found in modules jetified-hamcrest-core-1.1 (org.hamcrest:hamcrest-core:1.1) and jetified-junit-4.10 (junit:junit:4.10)
Go to the documentation to learn how to Fix dependency resolution errors.
testImplementation 'junit:junit:4.+'
testImplementation 'junit:junit:4.12'
are duplicated, but it is not because of that. I tried commenting out 1. It happens only when I add
implementation 'com.googlecode.json-simple:json-simple:1.1.1'
else things compile fine.
ANSWER
Answered 2021-Sep-23 at 06:37You have duplicated your dependencies. Entries:
testImplementation 'junit:junit:4.+'
testImplementation 'junit:junit:4.12'
Are pointing to the same library
QUESTION
I got this error when I tried to debug my app
java.lang.NoSuchMethodError: No virtual method requestPermissions([Ljava/lang/String;I)V in class Lcom/cscodetech/townclap/activity/LoginActivity; or its super classes (declaration of 'com.zestar.myclip.activity.LoginActivity' appears in /data/app/com.zestar.myclip-1/base.apk:classes2.dex)
at com.zestar.myclip.activity.LoginActivity.onCreate(LoginActivity.java:92)
The logcat pointed to this line of code
requestPermissions(new String[]{Manifest.permission.CALL_PHONE, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 1);
What is wrong with that line
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ButterKnife.bind(this);
FirebaseApp.initializeApp(this);
requestPermissions(new String[]{Manifest.permission.CALL_PHONE, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 1);
custPrograssbar = new CustPrograssbar();
sessionManager = new SessionManager(LoginActivity.this);
atCode.setOnFocusChangeListener((view, b) -> {
if (!b) {
// on focus off
String str = atCode.getText().toString();
ListAdapter listAdapter = atCode.getAdapter();
for (int i = 0; i < listAdapter.getCount(); i++) {
String temp = listAdapter.getItem(i).toString();
if (str.compareTo(temp) == 0) {
return;
}
}
atCode.setText("");
}
});
getCodelist();
}
ANSWER
Answered 2021-Sep-20 at 21:38as requestPermissions
like @TylerV said, try using this way instead as instructed in Documentation for how to request app permissions | Android Developers
this should be the right way to request permissions in fragments which goes as this:
- You first initialize this variable in fragment/activity which specifies what should happen if the permissions were granted or not:
private ActivityResultLauncher requestPermissionLauncher =
registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), result -> { {
//result is a map(string permission,boolean granted or not)
//to check if all permissions were granted or not
if(result.containsValue(false)){
// Explain to the user that the feature is unavailable because
// the features requires a permission that the user has denied.
// At the same time, respect the user's decision. Don't link to
// system settings in an effort to convince the user to change
// their decision.
Toast.makeText(getContext(), "Can't continue without the required permissions", Toast.LENGTH_LONG).show();
}
else {
//continue your work flow
}
});
- Then when you need to request for a permission you call launch on the object you declared with an array holding the permission you're requesting :
if (ActivityCompat.checkSelfPermission(getContext(),
Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED ||
ActivityCompat.checkSelfPermission(getContext(),
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
ActivityCompat.checkSelfPermission(getContext(),
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.ACCESS_FINE_LOCATION) {
requestPermissionLauncher.launch(new String[]{Manifest.permission.CALL_PHONE,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION});
} else // continue your work
QUESTION
While upload my app in Google playstore I get this error; We've detected this app uses an unsupported version of Play billing. Please upgrade to Billing Library version 3 or newer to publish this app.
Below are the dependencies on my android studio app, which of them is the billing library to change?
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.google.android.material:material:1.1.0'
implementation 'com.github.AnchorFreePartner.hydra-sdk-android:sdk:3.1.1'
implementation 'com.github.AnchorFreePartner.hydra-sdk-android:openvpn:3.1.1'
implementation 'junit:junit:4.12'
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'androidx.recyclerview:recyclerview:1.1.0'
implementation 'com.android.support:multidex:1.0.3'
implementation 'com.jakewharton:butterknife:10.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.1'
implementation 'com.google.android.gms:play-services-ads:19.0.1'
implementation 'com.facebook.android:audience-network-sdk:5.6.1'
implementation 'com.onesignal:OneSignal:3.12.7@aar'
implementation 'com.google.firebase:firebase-analytics:17.3.0'
implementation 'com.google.android.gms:play-services-gcm:17.0.0'
implementation 'com.google.android.gms:play-services-location:17.0.0'
implementation 'com.anjlab.android.iab.v3:library:1.1.0'
implementation 'com.squareup.retrofit2:retrofit:2.6.2'
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.squareup.retrofit2:converter-gson:2.6.2'
ANSWER
Answered 2021-Sep-10 at 12:03You are using this library for InApp purchasing but this library says we have updated to V3 but Google play store warn about this library that library is not updated to V3 or V4
implementation 'com.anjlab.android.iab.v3:library:1.1.0'
You should use Official documents for InApp Purchasing
Example V4build.gradle
implementation 'com.android.billingclient:billing:4.0.0'
strings.xml
Place Your ID Here
android.test.purchased
InAppPurchase.kt
import android.app.Activity
import android.content.Context
import android.widget.Toast
import com.android.billingclient.api.*
import java.io.IOException
import java.util.ArrayList
class InAppPurchase(context: Context) : PurchasesUpdatedListener{
private val mContext: Context = context
private var billingClient: BillingClient
var ackPurchase =
AcknowledgePurchaseResponseListener { billingResult ->
if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
//if purchase is acknowledged
// Grant entitlement to the user. and restart activity
SharedPreferencesUtils.setPurchasedBillingValue(mContext, true)
showMessage("Item Purchased")
(mContext as Activity).recreate()
}
}
init {
billingClient =
BillingClient.newBuilder(mContext).enablePendingPurchases().setListener(this).build()
billingClient.startConnection(object : BillingClientStateListener {
override fun onBillingSetupFinished(billingResult: BillingResult) {
if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
val queryPurchase = billingClient.queryPurchases(BillingClient.SkuType.INAPP)
val queryPurchases = queryPurchase.purchasesList
if (queryPurchases != null && queryPurchases.size > 0) {
handlePurchases(queryPurchases)
} else {
SharedPreferencesUtils.setPurchasedBillingValue(mContext, false)
}
}
}
override fun onBillingServiceDisconnected() {}
})
}
fun productPurchase() {
//check if service is already connected
if (billingClient.isReady) {
initiatePurchase()
} else {
billingClient =
BillingClient.newBuilder(mContext).enablePendingPurchases().setListener(this).build()
billingClient.startConnection(object : BillingClientStateListener {
override fun onBillingSetupFinished(billingResult: BillingResult) {
if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
initiatePurchase()
} else {
showMessage("Error" + billingResult.debugMessage)
}
}
override fun onBillingServiceDisconnected() {}
})
}
}
private fun initiatePurchase() {
val skuList: MutableList = ArrayList()
skuList.add(mContext.resources.getString(R.string.product_id))
val params = SkuDetailsParams.newBuilder()
params.setSkusList(skuList).setType(BillingClient.SkuType.INAPP)
billingClient.querySkuDetailsAsync(
params.build()
) { billingResult, skuDetailsList ->
if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
if (skuDetailsList != null && skuDetailsList.size > 0) {
val flowParams = BillingFlowParams.newBuilder()
.setSkuDetails(skuDetailsList[0])
.build()
billingClient.launchBillingFlow(mContext as Activity, flowParams)
} else {
//try to add item/product id "purchase" inside managed product in google play console
showMessage("Purchase Item not Found")
}
} else {
showMessage(" Error " + billingResult.debugMessage)
}
}
}
/**
* Verifies that the purchase was signed correctly for this developer's public key.
*
* Note: It's strongly recommended to perform such check on your backend since hackers can
* replace this method with "constant true" if they decompile/rebuild your app.
*
*/
private fun verifyValidSignature(signedData: String, signature: String): Boolean {
return try {
// To get key go to Developer Console > Select your app > Development Tools > Services & APIs.
val base64Key = mContext.getString(R.string.license_key)
Security.verifyPurchase(base64Key, signedData, signature)
} catch (e: IOException) {
false
}
}
fun handlePurchases(purchases: List) {
for (purchase in purchases) {
//if item is purchased
if (mContext.getString(R.string.product_id) == purchase.skus[0] && purchase.purchaseState == Purchase.PurchaseState.PURCHASED) {
if (!verifyValidSignature(purchase.originalJson, purchase.signature)) {
// Invalid purchase
// show error to user
showMessage("Invalid Purchase")
return
}
// else purchase is valid
// if item is purchased and not acknowledged
if (!purchase.isAcknowledged) {
val acknowledgePurchaseParams = AcknowledgePurchaseParams.newBuilder()
.setPurchaseToken(purchase.purchaseToken)
.build()
billingClient.acknowledgePurchase(acknowledgePurchaseParams, ackPurchase)
} else {
// Grant entitlement to the user on item purchase
// restart activity
if (!SharedPreferencesUtils.getPurchasedBillingValue(mContext)) {
SharedPreferencesUtils.setPurchasedBillingValue(mContext,true)
showMessage("Item Purchased")
(mContext as Activity).recreate()
}
}
} else if (mContext.getString(R.string.product_id) == purchase.skus[0] && purchase.purchaseState == Purchase.PurchaseState.PENDING) {
showMessage("Purchase is Pending. Please complete Transaction")
} else if (mContext.getString(R.string.product_id) == purchase.skus[0] && purchase.purchaseState == Purchase.PurchaseState.UNSPECIFIED_STATE) {
SharedPreferencesUtils.setPurchasedBillingValue(mContext,false)
showMessage("Purchase Status Unknown")
}
}
}
private fun showMessage(message: String) {
(mContext as Activity).runOnUiThread{
Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show()
}
}
override fun onPurchasesUpdated(billingResult: BillingResult, purchases: MutableList?) {
//if item newly purchased
if (billingResult.responseCode == BillingClient.BillingResponseCode.OK && purchases != null) {
handlePurchases(purchases)
} else if (billingResult.responseCode == BillingClient.BillingResponseCode.ITEM_ALREADY_OWNED) {
val queryAlreadyPurchasesResult =
billingClient.queryPurchases(BillingClient.SkuType.INAPP)
val alreadyPurchases = queryAlreadyPurchasesResult.purchasesList
alreadyPurchases?.let { handlePurchases(it) }
} else if (billingResult.responseCode == BillingClient.BillingResponseCode.USER_CANCELED) {
showMessage("Purchase Canceled")
} else {
showMessage("Error updated" + billingResult.debugMessage)
}
}
fun onDestroyBilling() {
billingClient.endConnection()
}
}
Security.kt
import android.text.TextUtils
import android.util.Base64
import java.io.IOException
import java.security.*
import java.security.spec.InvalidKeySpecException
import java.security.spec.X509EncodedKeySpec
/**
* Security-related methods. For a secure implementation, all of this code should be implemented on
* a server that communicates with the application on the device.
*/
object Security {
private const val KEY_FACTORY_ALGORITHM = "RSA"
private const val SIGNATURE_ALGORITHM = "SHA1withRSA"
/**
* Verifies that the data was signed with the given signature, and returns the verified
* purchase.
* @param base64PublicKey the base64-encoded public key to use for verifying.
* @param signedData the signed JSON string (signed, not encrypted)
* @param signature the signature for the data, signed with the private key
* @throws IOException if encoding algorithm is not supported or key specification
* is invalid
*/
@Throws(IOException::class)
fun verifyPurchase(
base64PublicKey: String, signedData: String,
signature: String
): Boolean {
if (TextUtils.isEmpty(signedData) || TextUtils.isEmpty(base64PublicKey)
|| TextUtils.isEmpty(signature)
) {
//Purchase verification failed: missing data
return false
}
val key = generatePublicKey(base64PublicKey)
return verify(key, signedData, signature)
}
/**
* Generates a PublicKey instance from a string containing the Base64-encoded public key.
*
* @param encodedPublicKey Base64-encoded public key
* @throws IOException if encoding algorithm is not supported or key specification
* is invalid
*/
@Throws(IOException::class)
fun generatePublicKey(encodedPublicKey: String): PublicKey {
return try {
val decodedKey = Base64.decode(encodedPublicKey, Base64.DEFAULT)
val keyFactory = KeyFactory.getInstance(KEY_FACTORY_ALGORITHM)
keyFactory.generatePublic(X509EncodedKeySpec(decodedKey))
} catch (e: NoSuchAlgorithmException) {
// "RSA" is guaranteed to be available.
throw RuntimeException(e)
} catch (e: InvalidKeySpecException) {
val msg = "Invalid key specification: $e"
throw IOException(msg)
}
}
/**
* Verifies that the signature from the server matches the computed signature on the data.
* Returns true if the data is correctly signed.
*
* @param publicKey public key associated with the developer account
* @param signedData signed data from server
* @param signature server signature
* @return true if the data and signature match
*/
private fun verify(publicKey: PublicKey, signedData: String, signature: String): Boolean {
val signatureBytes: ByteArray = try {
Base64.decode(signature, Base64.DEFAULT)
} catch (e: IllegalArgumentException) {
//Base64 decoding failed
return false
}
try {
val signatureAlgorithm = Signature.getInstance(SIGNATURE_ALGORITHM)
signatureAlgorithm.initVerify(publicKey)
signatureAlgorithm.update(signedData.toByteArray())
return signatureAlgorithm.verify(signatureBytes)
} catch (e: NoSuchAlgorithmException) {
// "RSA" is guaranteed to be available
throw RuntimeException(e)
} catch (e: InvalidKeyException) {
//Invalid key specification
} catch (e: SignatureException) {
//Signature exception
}
return false
}
}
MainActivity.kt
var inAppPurchase: InAppPurchase = InAppPurchase(this)
btnInApp.setOnClickListener {
inAppPurchase.productPurchase()
}
QUESTION
I'm new to android studio and i'm not sure what was going on with it. How can I solve this error?
In the logcat, it mentioned that I required a view for recycler_food_list which apparently I had already coded into the foodlistfragment.java.
Logcat
2021-06-15 11:11:57.189 5164-5164/com.android.ridefun E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.android.ridefun, PID: 5164
java.lang.IllegalStateException: Required view 'recycler_food_list' with ID 2131231048 for field 'recycler_food_list' was not found. If this view is optional add '@Nullable' (fields) or '@Optional' (methods) annotation.
at butterknife.internal.Utils.findRequiredView(Utils.java:84)
at butterknife.internal.Utils.findRequiredViewAsType(Utils.java:96)
at com.android.ridefun.ui.foodlist.FoodListFragment_ViewBinding.(FoodListFragment_ViewBinding.java:21)
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
at butterknife.ButterKnife.bind(ButterKnife.java:170)
at com.android.ridefun.ui.foodlist.FoodListFragment.onCreateView(FoodListFragment.java:44)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2963)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:518)
at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:282)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:2189)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:2106)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:2002)
at androidx.fragment.app.FragmentManager$5.run(FragmentManager.java:524)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
fragment_food_list.xml
layout_food_item
FoodListFragment.java
public class FoodListFragment extends Fragment {
private FoodListViewModel sendViewModel;
Unbinder unbinder ;
@BindView(R.id.recycler_food_list)
RecyclerView recycler_food_list;
LayoutAnimationController layoutAnimationController;
MyFoodListAdapter adapter;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
sendViewModel =
new ViewModelProvider(this).get(FoodListViewModel.class);
View root = inflater.inflate(R.layout.fragment_menu, container, false);
unbinder = ButterKnife.bind(this,root);
initViews();
sendViewModel.getMutableLiveDataFoodList().observe(getViewLifecycleOwner(), foodModels -> {
adapter = new MyFoodListAdapter(getContext(),foodModels);
recycler_food_list.setAdapter(adapter);
recycler_food_list.setLayoutAnimation(layoutAnimationController);
});
return root;
}
private void initViews() {
recycler_food_list.setHasFixedSize(true);
recycler_food_list.setLayoutManager(new LinearLayoutManager(getContext()));
layoutAnimationController = AnimationUtils.loadLayoutAnimation(getContext(),R.anim.layout_item_from_left);
}
MyFoodListAdapter
public class MyFoodListAdapter extends RecyclerView.Adapter {
private Context context;
private List foodModelList;
public MyFoodListAdapter(Context context, List foodModelList) {
this.context = context;
this.foodModelList = foodModelList;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new MyViewHolder(LayoutInflater.from(context)
.inflate(R.layout.layout_food_item,parent,false));
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
Glide.with(context).load(foodModelList.get(position).getImage()).into(holder.img_food_image);
holder.txt_food_price.setText(new StringBuilder("$")
.append(foodModelList.get(position).getPrice()));
holder.txt_food_name.setText(new StringBuilder("")
.append(foodModelList.get(position).getName()));
}
@Override
public int getItemCount() {
return foodModelList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder{
private Unbinder unbinder;
@BindView(R.id.txt_food_name)
TextView txt_food_name;
@BindView(R.id.txt_food_price)
TextView txt_food_price;
@BindView(R.id.img_food_image)
ImageView img_food_image;
@BindView(R.id.img_fav)
ImageView img_fav;
@BindView(R.id.img_quick_cart)
ImageView img_cart;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
unbinder = ButterKnife.bind(this,itemView);
}
}
ANSWER
Answered 2021-Jun-15 at 03:29You're doing inflater.inflate(R.layout.fragment_menu, container, false);
, not inflating your R.layout.fragment_food_list
. You'll need to inflate the right layout to find your Recycler view.
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install butterknife
Support
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesExplore Kits - Develop, implement, customize Projects, Custom Functions and Applications with kandi kits
Save this library and start creating your kit
Share this Page