By continuing you indicate that you have read and agree to our Terms of service and Privacy policy
by square Kotlin Version: v2.10 License: Apache-2.0
by square Kotlin Version: v2.10 License: Apache-2.0
Support
Quality
Security
License
Reuse
kandi's functional review helps you automatically verify the functionalities of the libraries and avoid rework.
Currently covering the most popular Java, JavaScript and Python libraries. See a Sample Here
Get all kandi verified functions for this library.
Get all kandi verified functions for this library.
A memory leak detection library for Android.
QUESTION
INSTALL_PARSE_FAILED_MANIFEST_MALFORMED error
Asked 2022-Apr-09 at 18:01Good day,
After installing Android Studio Bumblebee 2021.1.1 Patch 3 and importing my older project (then updating gradle, sdk, and dependancies), I started struggling with INSTALL_PARSE_FAILED_MANIFEST_MALFORMED error. I have followed the suggestions in Installation error: INSTALL_PARSE_FAILED_MANIFEST_MALFORMED? without luck.
Things I checked:
Last item that I believe is responsible for this error is in Logcat: Could not get package user id: run-as: unknown package: com.test.app
How can I resolve this issue?
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test.app">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher_round_foreground"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round_foreground"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:exported="true"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<action android:name="android.intent.action.VIEW" />
</intent-filter>
</activity>
android:theme="@style/Theme.AppCompat.NoActionBar" />
</application>
</manifest>
Run Error:
Installation failed due to: 'Failed to commit install session 1816080056 with command cmd package install-commit 1816080056. Error: INSTALL_PARSE_FAILED_MANIFEST_MALFORMED: Failed parse during installPackageLI: /data/app/vmdl1816080056.tmp/base.apk (at Binary XML file line #137): leakcanary.internal.activity.LeakLauncherActivity: Targeting S+ (version 31 and above) requires that an explicit value for android:exported be defined when intent filters are present'
Logcat:
2022-04-09 13:22:23.974 14319-14319/? E/studio.deploy: Could not get package user id: run-as: unknown package: com.test.app
2022-04-09 13:22:23.991 14319-14319/? E/studio.deploy: Could not find apks for this package: com.test.app
2022-04-09 13:22:23.991 14319-14319/? E/studio.deploy: Error:
2022-04-09 13:22:24.008 14319-14319/? E/studio.deploy: Could not get package user id: run-as: unknown package: com.test.app
2022-04-09 13:22:24.019 14319-14319/? E/studio.deploy: Could not find apks for this package: com.test.app
2022-04-09 13:22:24.019 14319-14319/? E/studio.deploy: Error:
2022-04-09 13:22:24.551 13743-13743/? E/Finsky: [2] VerifyPerSourceInstallationConsentInstallTask.d(2): Package name null is not an installed package
2022-04-09 13:22:24.591 438-452/? E/installd: Couldn't opendir /data/app/vmdl1816080056.tmp: No such file or directory
2022-04-09 13:22:24.591 438-452/? E/installd: Failed to delete /data/app/vmdl1816080056.tmp: No such file or directory
2022-04-09 13:23:08.160 362-362/? E/android.hardware.power.stats@1.0-service-mock: Failed to getEnergyData
2022-04-09 13:23:33.837 8380-9661/? E/WakeLock: GCM_HB_ALARM release without a matched acquire!
2022-04-09 13:23:33.843 8380-9661/? E/WakeLock: GCM_HB_ALARM release without a matched acquire!
2022-04-09 13:25:08.160 362-362/? E/android.hardware.power.stats@1.0-service-mock: Failed to getEnergyData
ANSWER
Answered 2022-Apr-09 at 18:01As with error description in error, it's about LeakLauncherActivity
leakcanary.internal.activity.LeakLauncherActivity: Targeting S+ (version 31 and above) requires that an explicit value for android:exported be defined when intent filters are present
And it looks like this issue has been fixed in new version of leak canary lib. https://github.com/square/leakcanary/issues/2076
QUESTION
Manifest merger failed with multiple errors | Android 12 and higher are required to specify an explicit value for `android:exported`
Asked 2022-Mar-30 at 08:08I am new to java and android. And on running the emulator I am facing this merge conflict issue.
Complete Error message:
Execution failed for task ':processDefaultsDebugMainManifest'.
Manifest merger failed with multiple errors, see logs
Error: android:exported needs to be explicitly specified for element <activity#com.squareup.leakcanary.internal.DisplayLeakActivity>. Apps targeting Android 12 and higher are required to specify an explicit value for
android:exported
when the corresponding component has an intent filter defined. See https://developer.android.com/guide/topics/manifest/activity-element#exported for details. main manifest (this file), line 35
Here AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.iab.omid.sampleapp">
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<application
android:networkSecurityConfig="@xml/network_security_config"
android:name=".AdApplication"
android:allowBackup="false"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
tools:ignore="GoogleAppIndexingWarning">
<activity
android:name=".AdListActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar"
android:exported="true" >
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity
android:name=".AdDetailActivity"
android:label="@string/title_ad_detail"
android:parentActivityName=".AdListActivity"
android:theme="@style/AppTheme.NoActionBar">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.iab.omid.sampleapp.AdListActivity"/>
</activity>
</application>
and build.gradle
buildscript {
ext {
targetCompatibility = JavaVersion.VERSION_1_8
}
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:7.1.2'
}
}
apply plugin: 'com.android.application'
repositories {
google()
maven {
url "https://plugins.gradle.org/m2/"
}
}
android {
compileSdk 32
flavorDimensions ""
defaultConfig {
applicationId "com.iab.omid.sampleapp"
minSdkVersion 18
targetSdkVersion 32
versionCode 1020
versionName "1.1.3"
testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
buildConfigField("String", "PARTNER_NAME", "\"com.iab.omid.sampleapp\"")
buildConfigField("String", "VENDOR_KEY", "\"dummyVendor\"")
buildConfigField("String", "VALIDATION_SCRIPT_URL", "\"complianceomsdk.iabtechlab.com\"")
// This override URL will only change URLs seen in Charles proxy for Html ads
buildConfigField("String", "VALIDATION_SCRIPT_URL_OVERRIDE", "\"complianceomsdk.iabtechlab.com\"")
buildConfigField("String", "VERIFICATION_URL", "\"https://s3-us-west-2.amazonaws.com/omsdk-files/compliance-js/omid-validation-verification-script-v1.js\"")
buildConfigField("String", "VERIFICATION_PARAMETERS", "\"http://omid-android-reference-app/sendMessage?msg=\"")
buildConfigField("String", "HTML_DISPLAY_AD", "\"https://omsdk-files.s3-us-west-2.amazonaws.com/creatives/html_display_creative.html\"")
buildConfigField("String", "HTML_VIDEO_AD", "\"https://omsdk-files.s3-us-west-2.amazonaws.com/creatives/html_video_creative.html\"")
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
productFlavors {
defaults {
}
instrumentationTest {
buildConfigField("String", "VERIFICATION_URL", "\"https://omsdk-files.s3-us-west-2.amazonaws.com/fullstack/fullstack-verification-script.js\"")
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
buildToolsVersion '32.0.0'
}
dependencies {
implementation fileTree(include: ['*.aar'], dir: '../')
implementation 'com.google.android.exoplayer:exoplayer:2.10.5', {
exclude group: 'com.android.support'
}
implementation 'androidx.appcompat:appcompat:1.0.0'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'androidx.recyclerview:recyclerview:1.0.0'
implementation 'com.google.android.material:material:1.0.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'commons-io:commons-io:2.4'
implementation 'io.reactivex:rxandroid:1.2.1'
implementation 'io.reactivex:rxjava:1.3.8'
implementation 'org.apache.commons:commons-lang3:3.6'
implementation 'com.facebook.stetho:stetho:1.5.0'
implementation 'com.facebook.stetho:stetho-okhttp3:1.5.0'
debugImplementation 'com.squareup.leakcanary:leakcanary-android:1.5.4'
releaseImplementation 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.4'
testImplementation 'junit:junit:4.12'
androidTestImplementation('androidx.test.espresso:espresso-core:3.1.0', {
exclude group: 'com.android.support', module: 'support-annotations'
})
androidTestImplementation 'androidx.annotation:annotation:1.3.0'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test:rules:1.4.0'
androidTestImplementation 'org.mockito:mockito-android:4.3.1'
androidTestImplementation 'com.azimolabs.conditionwatcher:conditionwatcher:0.2'
androidTestImplementation 'androidx.test.uiautomator:uiautomator:2.2.0'
}
tasks.withType(JavaCompile) {
options.compilerArgs << "-Xlint:deprecation"
}
task downloadOMSDKJS(type:Exec) {
if (!file('./src/main/res/raw/omsdk_v1.js').exists()) {
workingDir '../'
commandLine 'sh', './scripts/download-omsdk-js.sh'
} else {
// We need a dummy execCommand here.
commandLine 'sh'
}
}
preBuild.dependsOn downloadOMSDKJS
I have already tried many other solutions available on StackOverflow but still haven't made any progress.
Please let me know if any more details are required to be shared to solve this in a comment.
ANSWER
Answered 2022-Mar-30 at 08:08Your libraries are defining probably an "intent_filter" on an activity
debugImplementation 'com.squareup.leakcanary:leakcanary-android:1.5.4'
releaseImplementation 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.4'
If your application is targeting API 31+, the attribute "exported" is mandatory.
So as the developer of that library didn't target API 31, the exported flag what not mandatory on his side. And he built it without exported attribute.
So what you can do, is redefine that specific class on your manifest to declare it explicitly exported or not. For example :
<activity android:name="com.squareup.leakcanary.internal.DisplayLeakActivity"
android:exported="true"/>
QUESTION
android:exported added but still getting error Apps targeting Android 12 and higher are required to specify an explicit value for android:exported
Asked 2022-Mar-24 at 15:30I have added android:exported="true"
to my only activity in manifest but still getting below error after updating compile sdk and target sdk version to 31.I also tried rebuilding the project , invalidating cache and restart but that didn't helped
Error- Apps targeting Android 12 and higher are required to specify an explicit value for android:exported when the corresponding component has an intent filter defined. See https://developer.android.com/guide/topics/manifest/activity-element#exported for details.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.xyz.abc">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:name=".framework.presentation.BaseApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name="com.xyz.presentation.MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Other Manifest Files (Included in merge, but did not contribute any elements) firebase-installations:17.0.0 manifest, versionedparcelable:1.1.1 manifest, runtime:1.0.1 manifest, test:core:1.2.0 manifest, loader:1.0.0 manifest, facebook-share:11.1.0 manifest, leakcanary:leaksentry:2.0-alpha-3 manifest, material-dialogs:input:3.2.1 manifest, material-icons-extended:1.0.0 manifest, play-services-stats:17.0.0 manifest, interpolator:1.0.0 manifest, activity-compose:1.3.1 manifest, material-ripple:1.0.0 manifest, foundation:1.0.0 manifest, asynclayoutinflater:1.0.0 manifest, savedstate-ktx:1.1.0 manifest, navigation-dynamic-features-fragment:2.3.5 manifest, firebase-ui-auth:7.2.0 manifest, animation:1.0.1 manifest, animation-core:1.0.1 manifest, installreferrer:1.0 manifest, firebase-crashlytics:18.0.0 manifest, ui:1.0.1 manifest, lifecycle-viewmodel-savedstate:2.3.1 manifest, play-services-auth-base:17.0.0 manifest, hilt-android:2.35.1 manifest, material-dialogs:core:3.2.1 manifest, AndroidManifest.xml navigation file, savedstate:1.1.0 manifest, cursoradapter:1.0.0 manifest, sqlite-framework:2.0.1 manifest, room-ktx:2.1.0 manifest, leakcanary-android-core:2.0-alpha-3 manifest, AndroidManifest.xml navigation file, media:1.0.0 manifest, coordinatorlayout:1.1.0 manifest, legacy-support-core-utils:1.0.0 manifest, lifecycle-runtime:2.3.1 manifest, coil-kt:coil:1.3.1 manifest, ui-tooling-preview:1.0.0 manifest, facebook-core:11.1.0 manifest, core:1.6.0 manifest, material:1.0.0 manifest, firebase-common:20.0.0 manifest, documentfile:1.0.0 manifest, lifecycle-viewmodel-compose:2.4.0-beta01 manifest, play-services-base:17.1.0 manifest, ui-tooling-data:1.0.0 manifest, coil-base:1.3.1 manifest, firebase-analytics-ktx:19.0.0 manifest, localbroadcastmanager:1.0.0 manifest, swiperefreshlayout:1.1.0-alpha03 manifest, constraintlayout-compose:1.0.0-beta02 manifest, core-ktx:1.6.0 manifest, firebase-database-collection:18.0.0 manifest, coil-compose-base:1.3.1 manifest, activity:1.3.1 manifest, AndroidManifest.xml navigation file, facebook-messenger:11.1.0 manifest, print:1.0.0 manifest, customview:1.1.0 manifest, material-icons-core:1.0.0 manifest, play-services-measurement-sdk:19.0.0 manifest, fragment:1.3.4 manifest, firebase-appcheck-interop:16.0.0-beta01 manifest, facebook-login:11.1.0 manifest, cardview:1.0.0 manifest, runtime-rxjava2:1.0.0 manifest, viewpager2:1.0.0 manifest, play-services-ads-identifier:17.0.0 manifest, play-services-measurement-impl:19.0.0 manifest, lifecycle-livedata-core:2.3.1 manifest, play-services-safetynet:17.0.0 manifest, AndroidManifest.xml navigation file, lifecycle-viewmodel-ktx:2.3.1 manifest, transport-backend-cct:3.0.0 manifest, fragment-ktx:1.2.4 manifest, appcompat:1.3.0 manifest, transport-runtime:3.0.0 manifest, lifecycle-livedata-core-ktx:2.2.0 manifest, firebase-firestore-ktx:23.0.0 manifest, legacy-support-v4:1.0.0 manifest, play-services-basement:17.1.1 manifest, firebase-storage:20.0.0 manifest, play-services-auth-api-phone:17.4.0 manifest, leakcanary-android:2.0-alpha-3 manifest, firebase-auth-interop:20.0.0 manifest, lifecycle-viewmodel:2.3.1 manifest, browser:1.0.0 manifest, firebase-auth:21.0.1 manifest, material:1.2.1 manifest, slidingpanelayout:1.0.0 manifest, vectordrawable:1.1.0 manifest, recyclerview:1.1.0 manifest, play-services-auth:19.0.0 manifest, room-runtime:2.1.0 manifest, dagger-lint-aar:2.35.1 manifest, navigation-dynamic-features-runtime:2.3.5 manifest, play-services-measurement-api:19.0.0 manifest, firebase-encoders-json:18.0.0 manifest, sqlite:2.0.1 manifest, facebook-android-sdk:11.1.0 manifest, firebase-components:17.0.0 manifest, transport-api:3.0.0 manifest, protolite-well-known-types:18.0.0 manifest, markdown-processor:0.1.3 manifest, play-services-measurement-base:19.0.0 manifest, firebase-common-ktx:20.0.0 manifest, activity-ktx:1.3.1 manifest, firebase-crashlytics-ktx:18.0.0 manifest, coil-compose:1.3.1 manifest, multidex:2.0.1 manifest, core-runtime:2.1.0 manifest, fragment-testing:1.2.0 manifest, ui-graphics:1.0.1 manifest, AndroidManifest.xml navigation file, ui-tooling:1.0.0 manifest, grpc-android:1.28.0 manifest, ui-unit:1.0.1 manifest, play-services-measurement:19.0.0 manifest, play:core:1.9.1 manifest, annotation-experimental:1.1.0 manifest, play-services-measurement-sdk-api:19.0.0 manifest, play-services-tasks:17.0.0 manifest, firebase-analytics:19.0.0 manifest, facebook-common:11.1.0 manifest, drawerlayout:1.1.1 manifest, AndroidManifest.xml navigation file, navigation-compose:2.4.0-alpha09 manifest, facebook-gamingservices:11.1.0 manifest, firebase-firestore:23.0.0 manifest, lifecycle-livedata:2.2.0 manifest, legacy-support-core-ui:1.0.0 manifest, test:monitor:1.2.0 manifest, AndroidManifest.xml navigation file, facebook-applinks:11.1.0 manifest, viewpager:1.0.0 manifest, ui-geometry:1.0.1 manifest, lifecycle-runtime-ktx:2.3.1 manifest, constraintlayout:2.0.4 manifest, ui-text:1.0.1 manifest, AndroidManifest.xml navigation file, firebase-installations-interop:17.0.0 manifest, transition:1.3.0 manifest, foundation-layout:1.0.1 manifest, appcompat-resources:1.3.1 manifest, runtime-livedata:1.0.0 manifest, runtime-saveable:1.0.1 manifest, firebase-measurement-connector:19.0.0 manifest, vectordrawable-animated:1.1.0 manifest, main nav_graph.xml navigation file Merging Errors: Error: android:exported needs to be explicitly specified for . Apps targeting Android 12 and higher are required to specify an explicit value for
android:exported
when the corresponding component has an intent filter defined. See https://developer.android.com/guide/topics/manifest/activity-element#exported for details. Dairy.app main manifest (this file) Error: android:exported needs to be explicitly specified for . Apps targeting Android 12 and higher are required to specify an explicit value forandroid:exported
when the corresponding component has an intent filter defined. See https://developer.android.com/guide/topics/manifest/activity-element#exported for details. Dairy.app main manifest (this file) Error: android:exported needs to be explicitly specified for . Apps targeting Android 12 and higher are required to specify an explicit value forandroid:exported
when the corresponding component has an intent filter defined. See https://developer.android.com/guide/topics/manifest/activity-element#exported for details. Dairy.app main manifest (this file)
ANSWER
Answered 2021-Oct-05 at 10:38After the build has failed go to AndroidManifest.xml
and in the bottom click merged manifest see which activities which have intent-filter but don't have exported=true
attribute. Or you can just get the activities which are giving error.
Add these activities to your App manifest with android:exported="true"
and app tools:node="merge"
this will add exported attribute to the activities giving error.
Example:
<activity
android:name="<activity which is giving error>"
android:exported="true"
tools:node="merge" />
You will have to do this once, you can remove this once the library developers update their libs.
QUESTION
Android leakcanary obfuscate
Asked 2022-Mar-17 at 09:43Confusion can't use leakcanary LeakCanary plugin has been imported java.lang.NullPointerException
have integrated Leakcanary for the first time in my app, The trace is generated like the following. Can someone explain to me what does it mean?
2022-03-05 13:08:12.684 25896-25896/com.liangke.tingXieBen E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.liangke.tingXieBen, PID: 25896
java.lang.NullPointerException
at curtains.internal.WindowCallbackWrapper$Companion.getJetpackWrapped(:112)
at curtains.internal.WindowCallbackWrapper$Companion.unwrap(:154)
at curtains.WindowsKt.getWrappedCallback(:233)
at leakcanary.RootViewWatcher$listener$1.onRootViewAdded(:46)
at curtains.OnRootViewAddedListener$DefaultImpls.onRootViewsChanged(:38)
at leakcanary.RootViewWatcher$listener$1.onRootViewsChanged(:43)
at curtains.internal.RootViewsSpy$delegatingViewList$1.add(:25)
at curtains.internal.RootViewsSpy$delegatingViewList$1.add(:23)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:403)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:109)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4535)
at android.app.servertransaction.ResumeActivityItem.execute(ResumeActivityItem.java:52)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:176)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
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)
debug {
minifyEnabled true //注意测试的时候不要混淆
// testCoverageEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
testProguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguardTest-rules.pro'
}
ANSWER
Answered 2022-Mar-17 at 09:43I got the same crash log because I enabled:
minifyEnabled
in debug mode. The solution is adding:
-keep class androidx.appcompat.view.WindowCallbackWrapper { *; }
-keep class android.support.v7.view.WindowCallbackWrapper { *; }
in your progurd rules.
QUESTION
A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptWithoutKotlincTask$KaptExecutionWorkAction?java.lang.reflect.Invocation?
Asked 2022-Mar-06 at 10:01when I run android application in real device I am getting following gradle errors
Execution failed for task ':common:kaptDebugKotlin'.
> A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptWithoutKotlincTask$KaptExecutionWorkAction
> java.lang.reflect.InvocationTargetException (no error message)
below my app.gradle
plugins {
id 'com.android.application'
id 'kotlin-android'
}
apply plugin: 'androidx.navigation.safeargs.kotlin'
apply plugin: 'kotlin-kapt'
apply from: '../commons.gradle'
android {
compileSdkVersion 30
buildFeatures {
dataBinding = true
// for view binding:
// viewBinding = true
}
buildToolsVersion "29.0.3"
defaultConfig {
applicationId "com.example.androidcodingchallenge"
minSdkVersion 21
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables{
useSupportLibrary = true
}
multiDexEnabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = JavaVersion.VERSION_1_8.toString()
}
}
dependencies {
implementation project(':data')
implementation project(':domain')
implementation project(':presentation')
implementation project(':remote')
implementation project(':cache')
implementation project(':common')
implementation project(':device')
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.3.2'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation "com.google.android.material:material:$material_version"
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'androidx.cardview:cardview:1.0.0'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
//navigation component
// implementation "androidx.navigation:navigation-fragment-ktx:2.3.2"
// implementation "androidx.navigation:navigation-ui-ktx:2.3.2"
// UI
implementation "com.github.bumptech.glide:glide:$glide_version"
kapt "com.github.bumptech.glide:compiler:$glide_version"
// Ktx
implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.3.0"
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.0'
implementation "androidx.fragment:fragment-ktx:1.3.0"
// Navigation
implementation "android.arch.navigation:navigation-fragment-ktx:$version_navigation"
implementation "android.arch.navigation:navigation-ui-ktx:$version_navigation"
//viewpager2
implementation "androidx.viewpager2:viewpager2:1.0.0"
implementation 'com.thoughtbot:expandablerecyclerview:1.3'
implementation 'com.thoughtbot:expandablecheckrecyclerview:1.4'
//indicator
implementation 'me.relex:circleindicator:2.1.4'
//lottie
implementation "com.airbnb.android:lottie:3.4.1"
//datastore
implementation "androidx.datastore:datastore-preferences:1.0.0-alpha06"
implementation 'androidx.hilt:hilt-navigation-fragment:1.0.0-alpha03'
//LeakCanary
debugImplementation "com.squareup.leakcanary:leakcanary-android:$leakcanary_version"
//Retrofit
implementation "com.squareup.retrofit2:retrofit:$retrofit_version"
implementation "com.squareup.retrofit2:converter-gson:$retrofit_version"
implementation 'com.squareup.okhttp3:logging-interceptor:4.9.0'
//multidex
implementation 'com.android.support:multidex:1.0.3'
}
below commons.gradle
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
apply plugin: 'dagger.hilt.android.plugin'
androidExtensions {
experimental = true
}
android {
// compileSdkVersion Versions.compileSdkVersion
// buildToolsVersion Versions.buildTool
// defaultConfig {
// minSdkVersion Versions.minSdk
// targetSdkVersion Versions.targetSdk
// versionCode Releases.versionCode
// versionName Releases.versionName
// vectorDrawables.useSupportLibrary = true
// }
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
kapt {
javacOptions {
// Increase the max count of errors from annotation processors.
// Default is 100.
option("-Xmaxerrs", 500)
}
// Configure kapt to correct error types for Hilt
correctErrorTypes true
}
buildFeatures{
dataBinding = true
}
kotlinOptions {
jvmTarget = "1.8"
}
lintOptions {
abortOnError false
}
compileOptions {
targetCompatibility 1.8
sourceCompatibility 1.8
}
}
dependencies {
//Loads packaged libraries in the libs folder
implementation fileTree(dir: 'libs', include: ['*.jar'])
// implementation KotlinLibraries.kotlin
// implementation AndroidLibraries.coreKtx
//
// implementation Libraries.hilt
// implementation Libraries.hiltJetpack
// kapt Libraries.hiltCompiler
// kapt Libraries.hiltJetpackCompiler
//
// // For instrumentation tests
// androidTestImplementation Libraries.hiltAndroidTest
// kaptAndroidTest Libraries.hiltAndroidTestCompiler
//
// // For local unit tests
// testImplementation Libraries.hiltAndroidUnitTest
// kaptTest Libraries.hiltAndroidUnitTestCompiler
//
// implementation TestLibraries.androidTestRunner
// implementation TestLibraries.junit
// implementation TestLibraries.espresso
// implementation TestLibraries.espressoContrib
// Concurrency
implementation "io.reactivex.rxjava2:rxkotlin:$rxkotlin_version"
implementation "io.reactivex.rxjava2:rxandroid:$rxandroid_version"
//Hilt
implementation "com.google.dagger:hilt-android:$hilt_version"
kapt "com.google.dagger:hilt-android-compiler:$hilt_version"
implementation "androidx.hilt:hilt-lifecycle-viewmodel:$hilt_androidx_version"
kapt "androidx.hilt:hilt-compiler:$hilt_androidx_version"
// Utils
implementation "com.jakewharton.threetenabp:threetenabp:$threetenabp_version"
}
below build.gradle file
buildscript {
ext{
kotlin_version = "1.4.20"
version_navigation = "2.3.5"
hilt_version = '2.31.2-alpha'
version_navigation = "2.3.5"
version_lifecycle_extensions = "2.2.0"
lifecycle_version = "2.2.0"
hilt_androidx_version = "1.0.0-alpha03"
material_version = "1.3.0"
coroutines_version = "1.4.1"
junit_version = "4.13"
retrofit_version = "2.9.0"
okHttp_version = "4.9.0"
moshi_converter_version = '2.9.0'
moshi_version = '1.11.0'
mockwebserver_version = "4.9.0"
robolectric_version = "4.4"
mockito_version = "3.5.15"
google_truth_version = "1.0"
coroutines_test = "1.3.1"
room_version = "2.3.0"
threetenabp_version = "1.2.4"
leakcanary_version = "2.4"
timber_version = "4.7.1"
glide_version = "4.11.0"
androidsvg_version = "1.4"
rxkotlin_version = "2.4.0"
rxandroid_version = "2.1.1"
google_services_version = "4.3.8"
}
repositories {
google()
jcenter()
mavenCentral()
}
dependencies {
classpath "com.android.tools.build:gradle:4.1.1"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.5.21"
classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$version_navigation"
classpath "com.google.dagger:hilt-android-gradle-plugin:$hilt_version"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "com.google.gms:google-services:$google_services_version"
classpath 'com.google.firebase:firebase-crashlytics-gradle:2.7.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
flatDir {
dirs 'libs'
}
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
what I have tried invalide cache restart
followed this issue tracker I have tried all suggested answer overthere it did not solve my problem ,Besides that, I run gradlew clean in android studio and it is giving following errors FAILURE: Build completed with 2 failures.
1: Task failed with an exception.A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptWithoutKotlincTask$KaptExecutionWorkAction java.lang.reflect.InvocationTargetException (no error message)
A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptWithoutKotlincTask$KaptExecutionWorkAction java.lang.reflect.InvocationTargetException (no error message)
note that I am using Android Studio Arctic Fox
I want to know where exactly I am making mistake
ANSWER
Answered 2021-Aug-21 at 12:15I fixed it my problem by updating current kotlin version to latest version and moshi version to 1.12.0
QUESTION
Could not resolve all artifacts for configuration ':app:prereleaseCompileClasspath'
Asked 2022-Feb-02 at 00:34I am trying to build an app I clone it from Github CloudStream 3 but it always fails, I am new to android and I couldn't figure out the problem when I try to build the project it show this message:
> Configure project :app
Warning: The 'kotlin-android-extensions' Gradle plugin is deprecated. Please use this migration guide (https://goo.gle/kotlin-android-extensions-deprecation) to start working with View Binding (https://developer.android.com/topic/libraries/view-binding) and the 'kotlin-parcelize' plugin.
FAILURE: Build failed with an exception.
* What went wrong:
Could not determine the dependencies of task ':app:lint'.
> Could not resolve all artifacts for configuration ':app:prereleaseCompileClasspath'.
> Could not find appcompat-1.4.1.aar (androidx.appcompat:appcompat:1.4.1).
Searched in the following locations:
https://dl.google.com/dl/android/maven2/androidx/appcompat/appcompat/1.4.1/appcompat-1.4.1.aar
> Could not find extension-okhttp-2.16.1.aar (com.google.android.exoplayer:extension-okhttp:2.16.1).
Searched in the following locations:
https://dl.google.com/dl/android/maven2/com/google/android/exoplayer/extension-okhttp/2.16.1/extension-okhttp-2.16.1.aar
> Could not find constraintlayout-2.1.3.aar (androidx.constraintlayout:constraintlayout:2.1.3).
Searched in the following locations:
https://dl.google.com/dl/android/maven2/androidx/constraintlayout/constraintlayout/2.1.3/constraintlayout-2.1.3.aar
> Could not find appcompat-resources-1.4.1.aar (androidx.appcompat:appcompat-resources:1.4.1).
Searched in the following locations:
https://dl.google.com/dl/android/maven2/androidx/appcompat/appcompat-resources/1.4.1/appcompat-resources-1.4.1.aar
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
the Gradle setting for the project is:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = "1.5.21"
repositories {
google()
jcenter()
}
dependencies {
classpath "com.android.tools.build:gradle:4.1.3"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'kotlin-kapt'
id 'kotlin-android-extensions'
}
def tmpFilePath = System.getProperty("user.home") + "/work/_temp/keystore/"
def allFilesFromDir = new File(tmpFilePath).listFiles()
def prerelaseStoreFile = null
if (allFilesFromDir != null) {
prerelaseStoreFile = allFilesFromDir.first()
}
android {
testOptions {
unitTests.returnDefaultValues = true
}
signingConfigs {
prerelease {
if (prerelaseStoreFile != null) {
storeFile = file(prerelaseStoreFile)
storePassword System.getenv("SIGNING_STORE_PASSWORD")
keyAlias System.getenv("SIGNING_KEY_ALIAS")
keyPassword System.getenv("SIGNING_KEY_PASSWORD")
}
}
}
compileSdkVersion 31
buildToolsVersion "30.0.3"
defaultConfig {
applicationId "com.lagradost.cloudstream3"
minSdkVersion 21
targetSdkVersion 30
versionCode 42
versionName "2.6.9"
resValue "string", "app_version",
"${defaultConfig.versionName}${versionNameSuffix ?: ""}"
buildConfigField("String", "BUILDDATE", "new java.text.SimpleDateFormat(\"yyyy-MM-dd HH:mm\").format(new java.util.Date(" + System.currentTimeMillis() + "L));")
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
kapt {
includeCompileClasspath = true
}
}
buildTypes {
release {
minifyEnabled false
debuggable true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
prerelease {
applicationIdSuffix ".prerelease"
buildConfigField("boolean", "BETA", "true")
signingConfig signingConfigs.prerelease
versionNameSuffix '-PRE'
minifyEnabled false
debuggable true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
debug {
applicationIdSuffix ".debug"
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
freeCompilerArgs = ['-Xjvm-default=compatibility']
}
}
repositories {
maven { url 'https://jitpack.io' }
}
dependencies {
testImplementation 'org.json:json:20180813'
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.7.0'
implementation 'androidx.appcompat:appcompat:1.4.1'
implementation 'com.google.android.material:material:1.5.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
implementation 'androidx.navigation:navigation-fragment-ktx:2.4.0-rc01'
implementation 'androidx.navigation:navigation-ui-ktx:2.4.0-rc01'
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.4.0'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
//implementation "io.karn:khttp-android:0.1.2" //okhttp instead
implementation 'org.jsoup:jsoup:1.13.1'
implementation "com.fasterxml.jackson.module:jackson-module-kotlin:2.12.3"
implementation "com.google.android.material:material:1.5.0"
implementation "androidx.preference:preference-ktx:1.1.1"
implementation 'com.github.bumptech.glide:glide:4.12.0'
kapt 'com.github.bumptech.glide:compiler:4.12.0'
implementation 'com.github.bumptech.glide:okhttp3-integration:4.12.0'
implementation 'jp.wasabeef:glide-transformations:4.0.0'
implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'
// implementation "androidx.leanback:leanback-paging:1.1.0-alpha09"
// Exoplayer
implementation 'com.google.android.exoplayer:exoplayer:2.16.1'
implementation 'com.google.android.exoplayer:extension-cast:2.16.1'
implementation "com.google.android.exoplayer:extension-mediasession:2.16.1"
//implementation "com.google.android.exoplayer:extension-leanback:2.14.0"
// Bug reports
implementation "ch.acra:acra-core:5.8.4"
implementation "ch.acra:acra-toast:5.8.4"
compileOnly "com.google.auto.service:auto-service-annotations:1.0"
//either for java sources:
annotationProcessor "com.google.auto.service:auto-service:1.0"
//or for kotlin sources (requires kapt gradle plugin):
kapt "com.google.auto.service:auto-service:1.0"
// subtitle color picker
implementation 'com.jaredrummler:colorpicker:1.1.0'
//run JS
implementation 'org.mozilla:rhino:1.7R4'
// TorrentStream
//implementation 'com.github.TorrentStream:TorrentStream-Android:2.7.0'
// Downloading
implementation "androidx.work:work-runtime:2.7.1"
implementation "androidx.work:work-runtime-ktx:2.7.1"
// Networking
implementation "com.squareup.okhttp3:okhttp:4.9.2"
implementation "com.squareup.okhttp3:okhttp-dnsoverhttps:4.9.1"
implementation 'com.google.android.exoplayer:extension-okhttp:2.16.1'
// Util to skip the URI file fuckery 🙏
implementation "com.github.tachiyomiorg:unifile:17bec43"
// API because cba maintaining it myself
implementation "com.uwetrottmann.tmdb2:tmdb-java:2.6.0"
// debugImplementation because LeakCanary should only run in debug builds.
// debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.7'
// for shimmer when loading
implementation 'com.facebook.shimmer:shimmer:0.5.0'
}
what should I do to make It build correctly? thank you for your time.
ANSWER
Answered 2022-Feb-02 at 00:34The solution turns out that I need to downgrade the libraries I used the 1.3.1 version instead of 1.4.1 for the androidx.appcompat
library , the version 2.15.1 instead of 2.16.1 for the com.google.android.exoplayer
and the version 2.1.1 instead of 2.1.3 for the androidx.constraintlayout
QUESTION
RxJava Single - Getting a memory leak, how to correctly unsubscribe?
Asked 2022-Jan-30 at 12:31I'm using RxJava's Single.fromCallable()
to wrap around a third party library that makes an API call. I was testing different states on the call, success, failed, low network, no network.
But on the no network test I ran into a memory leak for the first time ever using RxJava. I spent the last hour combing through the code and trying to narrow down the leak with the LeakCanary
library.
I figured out it was coming from subscribing to the Single.fromCallable()
.
Single.fromCallable(() -> {
return remoteRepository.makeTransaction(signedTransaction).execute();
})
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(txHash -> {
Log.d(TAG, "makeTransaction: " + txHash);
}, err -> {
Log.e(TAG, "makeTransaction: ", err);
});
Once I remove the
.subscribe(txHash -> { ... });
It no longer leaks.
I've tried googling stackoverflow with RxJava Single unsubscribe
and I'm getting answers saying that you don't need to unsubscribe from Single
https://stackoverflow.com/a/43332198/11110509.
But if I don't I'll be getting memory leaks.
I've tried to unsubscribe by making the Single call an instance variable in my ViewModel:
Disposable mDisposable;
mDisposable = Single.fromCallable(() -> {...}).subscribe(txHash -> {..});
and unsubscribing it in the Fragment's onDestroy()
method so it will unsubscribe if the user exits the screen before the call is finished.
@Override
public void onDestroy() {
super.onDestroy();
mViewModel.getDisposable().dispose();
}
But it's still leaking. I'm not sure if this is the correct way to unsubscribe or maybe I'm doing something else incorrectly.
How can I correctly unsubscribe from the Single Callable?
Edit:_________________________________
How I'm recreating the issue:
Screen one is launches screen two. The call is performed instantly on the creation of screen two. Since I'm testing it with no network, the query is continuing to perform on screen two until it times out. So closing the screen two before the call finishes causes the leak.
It doesn't seem to be a context leak because I've removed tried testing it by removing all the methods inside the .subscribe()
:
Single.fromCallable(() -> {
return remoteRepository.makeTransaction(signedTransaction).execute();
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(txHash-> {
//Removed all methods here.
//Still leaks.
}, err -> {
});
But when I remove:
.subscribe(txHash-> {
}, err -> {
});
it no longer leaks.
LeakCanary logs:
┬───
│ GC Root: Java local variable
│
├─ java.lang.Thread thread
│ Leaking: UNKNOWN
│ Retaining 2.4 kB in 81 objects
│ Thread name: 'RxCachedThreadScheduler-2'
│ ↓ Thread.<Java Local>
│ ~~~~~~~~~~~~
╰→ com.dave.testapp.ui.send.SendViewModel instance
Leaking: YES (ObjectWatcher was watching this because com.dave.testapp.ui.send.SendViewModel received
ViewModel#onCleared() callback)
Retaining 588 B in 19 objects
key = 6828ea76-a75c-448b-8278-d0e0bb0229c8
watchDurationMillis = 10324
retainedDurationMillis = 5321
baseApplication instance of com.dave.testapp.BaseApplication
METADATA
Build.VERSION.SDK_INT: 27
Build.MANUFACTURER: Google
LeakCanary version: 2.7
App process name: com.dave.testapp
ANSWER
Answered 2022-Jan-30 at 12:31One easy mistake to be made in Java is forgetting about the implicit reference to the outer class instance whenever you instantiate an anonymous class in a non-static context.
For example:
Single.fromCallable(() -> {
// some logic
return 5;
});
Is actually the same as:
Single.fromCallable(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
// some logic
return 5;
}
});
So what you did is instantiate a new instance of the anonymous class which implements the Callable
interface.
Now, let's put this in some context.
Let's assume we have this inside a service class:
class SomeService {
int aNumber = 5;
Single<Integer> doLogic() {
return Single.fromCallable(() -> {
// using "aNumber" here implicates Service.this.aNumber
// e.g. writing "return 5 + aNumber" is actually the same as
return 5 + SomeService.this.aNumber;
});
}
}
Most of the time this isn't an issue because the outer classes outlive the short-lived objects instantiated inside the methods. However, if your instantiated object can outlive the outer object (in your case the Single is still running even after the ViewModel is out of scope), the whole outer object (in your case, the ViewModel) remains in memory as the Callable
still has the implicit reference to it.
There are many ways how to get rid of this unwanted reference - the easiest being instantiating the object in a static context where you capture only what you really need (instead of the whole "outer this").
class SomeService {
int aNumber = 5;
static Callable staticCallableThatCapturesOnlyParameters(int param) {
return () -> {
// outer this is not available here
return 5 + param; // param is captured through the function args
};
}
Single<Integer> doLogic() {
return Single.fromCallable(staticCallableThatCapturesOnlyParameters(aNumber));
}
}
Another approach would be to simply avoid the anonymous object altogether and use static inner classes, but that quickly bloats code.
QUESTION
Memory Leak in MessageQueue in android?
Asked 2021-Dec-26 at 10:37I am having a memory leak in my MainActivity.java which was detected by LeakCanary. This is my Leak Trace.
┬───
│ GC Root: Input or output parameters in native code
│
├─ android.os.MessageQueue instance
│ Leaking: NO (MessageQueue#mQuitting is false)
│ HandlerThread: "main"
│ ↓ MessageQueue.mMessages
│ ~~~~~~~~~
├─ android.os.Message instance
│ Leaking: UNKNOWN
│ Retaining 14.2 kB in 348 objects
│ Message.what = 0
│ Message.when = 37524601 (681 ms after heap dump)
│ Message.obj = null
│ Message.callback = instance @319985112 of com.application.app.
│ MainActivity$$ExternalSyntheticLambda2
│ ↓ Message.callback
│ ~~~~~~~~
├─ com.application.app.MainActivity$$ExternalSyntheticLambda2 instance
│ Leaking: UNKNOWN
│ Retaining 12 B in 1 objects
│ f$0 instance of com.application.app.MainActivity with mDestroyed =
│ true
│ ↓ MainActivity$$ExternalSyntheticLambda2.f$0
│ ~~~
╰→ com.application.app.MainActivity instance
Leaking: YES (ObjectWatcher was watching this because com.defenderstudio.
geeksjob.MainActivity received Activity#onDestroy() callback and
Activity#mDestroyed is true)
Retaining 11.2 MB in 5622 objects
key = e98df529-afa0-4e0c-b0f0-51a5d3eaf67c
watchDurationMillis = 5249
retainedDurationMillis = 248
mApplication instance of android.app.Application
mBase instance of androidx.appcompat.view.ContextThemeWrapper
METADATA
Build.VERSION.SDK_INT: 30
Build.MANUFACTURER: samsung
LeakCanary version: 2.7
App process name: com.application.app
Count of retained yet cleared: 6 KeyedWeakReference instances
Stats: LruCache[maxSize=3000,hits=6544,misses=134885,hitRate=4%]
RandomAccess[bytes=5904498,reads=134885,travel=75990168059,range=41137566,size=5
3483782]
Heap dump reason: 7 retained objects, app is visible
Analysis duration: 31639 ms
I can't understand what is the problem here. I closed all the postdelayed()
method when ondestroy()
is called. This is the code :
@Override
protected void onDestroy() {
dialog = new Dialog(MainActivity.this, R.style.dialog);
if (dialog.isShowing()) {
dialog.dismiss();
}
if (handler != null && statusChecker != null) {
handler.removeCallbacks(statusChecker);
}
if (databaseReference != null && userSignInInfoReference != null && eventListener != null) {
databaseReference.removeEventListener(eventListener);
userSignInInfoReference.removeEventListener(eventListener);
}
progressDialog = new ProgressDialog(MainActivity.this, R.style.ProgressDialogStyle);
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
headerView = null;
super.onDestroy();
}
Please help me out here!
NOTE : Also Please tell me what is MessageQueue and how close all leaks of it. Thanks in advance!
ANSWER
Answered 2021-Dec-26 at 10:37Check all the data members of your Activity there is some data member which is outliving your activity's lifecycle.
Also check in what places you are passing the activity context and MainActivity.this instance.
Lastly check what callbacks / lambda's are associated with this activity there could be a case that one of your class's member is being shared with some other class like a recycler view adapter which could lead to a leak.
As a thumb rule when working on memory leak issues I encapsulate most if not all data passing with WeakReference that way you are both safe from NPE plus you get benefit of a decoupled class.
Edit - As shared in the comment below using weak reference is a bad practice and there are better ways to resolve memory leaks. Kindly check the answer from @Pierre or link to the comment posted below.
QUESTION
After Kotlin 1.6 and Android Studio update, databinding shows errors but app compiles and runs fine
Asked 2021-Dec-23 at 09:48My android studio version is
Arctic Fox | 2020.3.1 Patch 3
Build #AI-203.7717.56.2031.7784292, built on October 1, 2021
After updating IDE and kotlin to 1.6, I opened a project I was working on and Android Stidio marked data binding fields as red, showing the following error:
In text:
Cannot access 'androidx.databinding.Observable' which is a supertype of
'com.cioccarellia.wordbucket.databinding.ActivityMainBinding'.
Check your module classpath for missing or conflicting dependencies
The weird thing is that everything compiles and the app works just fine, these errors are just in the IDE, and they pop up every time I access views through data binding.
I haven't changed my dependencies since updating android studio. Anyone else has the same problem / solution for this situation?
The Main Activity xml:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
</data>
<androidx.coordinatorlayout.widget.CoordinatorLayout
android:id="@+id/coordinator_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.cioccarellia.wordbucket.activity.MainActivity">
...
</androidx.coordinatorlayout.widget.CoordinatorLayout>
</layout>
General build.gradle:
buildscript {
ext {
kotlin_version = "1.6.0"
}
repositories {
google()
mavenCentral()
gradlePluginPortal()
maven { url 'https://jitpack.io' }
}
dependencies {
classpath "com.android.tools.build:gradle:7.0.3"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'com.google.gms:google-services:4.3.10'
classpath "com.google.dagger:hilt-android-gradle-plugin:2.40.3"
classpath "androidx.navigation:navigation-safe-args-gradle-plugin:2.3.5"
classpath 'com.google.firebase:firebase-crashlytics-gradle:2.8.1'
classpath "com.github.ben-manes:gradle-versions-plugin:0.39.0"
}
}
task clean(type: Delete) {
delete rootProject.buildDir
Application build.gradle:
plugins {
id "com.android.application"
id "kotlin-android"
id "kotlin-kapt"
id "dagger.hilt.android.plugin"
id "com.google.gms.google-services"
id "androidx.navigation.safeargs.kotlin"
id "com.github.ben-manes.versions"
id "kotlin-parcelize"
id "com.google.firebase.crashlytics"
}
android {
compileSdk 31
defaultConfig {
applicationId "com.cioccarellia.wordbucket"
minSdk 23
targetSdk 31
versionCode 1
versionName "1.0.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables.useSupportLibrary true
}
buildTypes {
debug {
versionNameSuffix ".dev"
}
release {
debuggable false
// Enables code shrinking, obfuscation, and optimization
minifyEnabled true
// Enables resource shrinking, which is performed by the
// Android Gradle plugin.
shrinkResources true
// Includes the default ProGuard rules files that are packaged with
// the Android Gradle plugin. To learn more, go to the section about
// R8 configuration files.
proguardFiles getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro"
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
buildFeatures {
dataBinding true
}
sourceSets {
main.res.srcDirs = [
"src/main/res",
"src/main/res-public"
]
android.sourceSets.all {
java.srcDir("src/$name/kotlin")
}
}
lintOptions {
// if set to true (default), stops the build if errors are found.
abortOnError false
// if true, only report errors.
ignoreWarnings false
}
}
dependencies {
// AndroidX
implementation "androidx.core:core-ktx:1.7.0"
implementation "androidx.appcompat:appcompat:1.4.0"
implementation "androidx.constraintlayout:constraintlayout:2.1.2"
implementation "com.google.android.material:material:1.6.0-alpha01"
implementation "androidx.legacy:legacy-support-v4:1.0.0"
// Lifecycle
def lifecycle_version = "2.4.0"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version"
// Navigation
implementation "androidx.navigation:navigation-fragment-ktx:2.3.5"
implementation "androidx.navigation:navigation-ui-ktx:2.3.5"
// Coroutines
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.2"
// DI -> Hilt
implementation "com.google.dagger:hilt-android:2.40.3"
kapt "com.google.dagger:hilt-compiler:2.40.3"
// Import the Firebase BoM
implementation platform("com.google.firebase:firebase-bom:28.4.2")
// When using the BoM, you don"t specify versions in Firebase library dependencies
implementation "com.google.firebase:firebase-crashlytics-ktx"
implementation "com.google.firebase:firebase-analytics-ktx"
implementation "com.google.firebase:firebase-auth-ktx"
implementation "com.google.firebase:firebase-firestore-ktx"
// LeakCanary
debugImplementation "com.squareup.leakcanary:leakcanary-android:2.7"
// Logging
implementation "com.jakewharton.timber:timber:5.0.1"
// Styles
implementation 'com.airbnb.android:paris:2.0.1'
kapt 'com.airbnb.android:paris-processor:2.0.1'
// JUnit Default Dependencies
testImplementation "junit:junit:4.13.2"
androidTestImplementation "androidx.test.ext:junit:1.1.3"
androidTestImplementation "androidx.test.espresso:espresso-core:3.4.0"
}
ANSWER
Answered 2021-Dec-05 at 17:36Try to restart the IDE. If that does not work, clean the project be going to Build > Clean Project at the top of the window, then completely rebuild it by going to Build > Rebuild Project.
Edit: Another reason is that Android Studio will no longer support binding to straight elements, so you have have to specify the binding yourself.
To do this, add BuildFeatures in the application gradle file:
android {
compileSdk 31
//This right here
buildFeatures{
viewBinding true
}
defaultConfig {
applicationId "com.cioccarellia.wordbucket"
minSdk 23
targetSdk 31
versionCode 1
versionName "1.0.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
vectorDrawables.useSupportLibrary true
}
Then create a new binding by adding this to your activity file:
//Declare the binding
private lateinit val binding : ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
//Initialize the binding
binding = ActivityMainBinding.inflate(layoutInflater)
super.onCreate(savedInstanceState)
//Change the content view to the root of the binding
setContentView(binding.root)
}
Then reference binding when using your views:
binding.toolbar.title = bucket.name
QUESTION
Activity leaked after orientation change after using AndroidX Navigation Compose
Asked 2021-Nov-13 at 10:45The MainActivity
gets leaked after the second time the orientation changes, but only after navigating to a new destination using the navHostController
.
A working project where this can be reproduced is available here.
These are the reproduction steps:
FooScreen
, that only contains a TopAppBar
and a Button
).Button
(it will load the BarScreen
, that only contains a TopAppBar
)At this point you should see StrictMode
complaining about the leak inside the logcat:
2021-11-02 16:23:20.672 31230-31230/com.leinardi.template E/StrictMode: class com.leinardi.template.ui.MainActivity; instances=2; limit=1
android.os.StrictMode$InstanceCountViolation: class com.leinardi.template.ui.MainActivity; instances=2; limit=1
at android.os.StrictMode.setClassInstanceLimit(StrictMode.java:1)
The LeakCanary notification should also be visible . This is the LeakCanary log:
┬───
│ GC Root: System class
│
├─ leakcanary.internal.InternalLeakCanary class
│ Leaking: NO (MainActivity↓ is not leaking and a class is never leaking)
│ ↓ static InternalLeakCanary.resumedActivity
├─ com.leinardi.template.ui.MainActivity instance
│ Leaking: NO (Activity#mDestroyed is false)
│ mApplication instance of com.leinardi.template.Template
│ mBase instance of android.app.ContextImpl
│ ↓ MainActivity.navHostController
│ ~~~~~~~~~~~~~~~~~
├─ androidx.navigation.NavHostController instance
│ Leaking: UNKNOWN
│ Retaining 5.5 kB in 140 objects
│ activity instance of com.leinardi.template.ui.MainActivity with mDestroyed = false
│ context instance of com.leinardi.template.ui.MainActivity with mDestroyed = false
│ lifecycleOwner instance of com.leinardi.template.ui.MainActivity with mDestroyed = false
│ ↓ NavController.viewModel
│ ~~~~~~~~~
├─ androidx.navigation.NavControllerViewModel instance
│ Leaking: UNKNOWN
│ Retaining 128.4 kB in 2406 objects
│ ↓ NavControllerViewModel.viewModelStores
│ ~~~~~~~~~~~~~~~
├─ java.util.LinkedHashMap instance
│ Leaking: UNKNOWN
│ Retaining 128.3 kB in 2404 objects
│ ↓ LinkedHashMap.header
│ ~~~~~~
├─ java.util.LinkedHashMap$LinkedHashMapEntry instance
│ Leaking: UNKNOWN
│ Retaining 32 B in 1 objects
│ ↓ LinkedHashMap$LinkedHashMapEntry.after
│ ~~~~~
├─ java.util.LinkedHashMap$LinkedHashMapEntry instance
│ Leaking: UNKNOWN
│ Retaining 127.8 kB in 2389 objects
│ ↓ HashMap$HashMapEntry.value
│ ~~~~~
├─ androidx.lifecycle.ViewModelStore instance
│ Leaking: UNKNOWN
│ Retaining 127.7 kB in 2388 objects
│ ↓ ViewModelStore.mMap
│ ~~~~
├─ java.util.HashMap instance
│ Leaking: UNKNOWN
│ Retaining 127.7 kB in 2387 objects
│ ↓ HashMap.table
│ ~~~~~
├─ java.util.HashMap$HashMapEntry[] array
│ Leaking: UNKNOWN
│ Retaining 127.7 kB in 2385 objects
│ ↓ HashMap$HashMapEntry[].[1]
│ ~~~
├─ java.util.HashMap$HashMapEntry instance
│ Leaking: UNKNOWN
│ Retaining 126.6 kB in 2348 objects
│ ↓ HashMap$HashMapEntry.value
│ ~~~~~
├─ androidx.navigation.compose.BackStackEntryIdViewModel instance
│ Leaking: UNKNOWN
│ Retaining 126.5 kB in 2347 objects
│ ↓ BackStackEntryIdViewModel.saveableStateHolder
│ ~~~~~~~~~~~~~~~~~~~
├─ androidx.compose.runtime.saveable.SaveableStateHolderImpl instance
│ Leaking: UNKNOWN
│ Retaining 126.4 kB in 2343 objects
│ ↓ SaveableStateHolderImpl.parentSaveableStateRegistry
│ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
├─ androidx.compose.ui.platform.DisposableSaveableStateRegistry instance
│ Leaking: UNKNOWN
│ Retaining 125.9 kB in 2321 objects
│ ↓ DisposableSaveableStateRegistry.onDispose
│ ~~~~~~~~~
├─ androidx.compose.ui.platform.DisposableSaveableStateRegistry_androidKt$DisposableSaveableStateRegistry$1 instance
│ Leaking: UNKNOWN
│ Retaining 125.6 kB in 2312 objects
│ Anonymous subclass of kotlin.jvm.internal.Lambda
│ ↓ DisposableSaveableStateRegistry_androidKt$DisposableSaveableStateRegistry$1.$androidxRegistry
│ ~~~~~~~~~~~~~~~~~
├─ androidx.savedstate.SavedStateRegistry instance
│ Leaking: UNKNOWN
│ Retaining 125.6 kB in 2310 objects
│ ↓ SavedStateRegistry.mComponents
│ ~~~~~~~~~~~
├─ androidx.arch.core.internal.SafeIterableMap instance
│ Leaking: UNKNOWN
│ Retaining 125.5 kB in 2309 objects
│ ↓ SafeIterableMap.mEnd
│ ~~~~
├─ androidx.arch.core.internal.SafeIterableMap$Entry instance
│ Leaking: UNKNOWN
│ Retaining 125.3 kB in 2302 objects
│ ↓ SafeIterableMap$Entry.mValue
│ ~~~~~~
├─ androidx.activity.ComponentActivity$$ExternalSyntheticLambda1 instance
│ Leaking: UNKNOWN
│ Retaining 125.3 kB in 2301 objects
│ f$0 instance of com.leinardi.template.ui.MainActivity with mDestroyed = true
│ ↓ ComponentActivity$$ExternalSyntheticLambda1.f$0
│ ~~~
╰→ com.leinardi.template.ui.MainActivity instance
Leaking: YES (ObjectWatcher was watching this because com.leinardi.template.ui.MainActivity received
Activity#onDestroy() callback and Activity#mDestroyed is true)
Retaining 125.3 kB in 2300 objects
key = 2c6ea34a-19c0-4d26-a5ec-88625d79531f
watchDurationMillis = 42581
retainedDurationMillis = 37580
mApplication instance of com.leinardi.template.Template
mBase instance of android.app.ContextImpl
METADATA
Build.VERSION.SDK_INT: 24
Build.MANUFACTURER: Google
LeakCanary version: 2.7
App process name: com.leinardi.template
Stats: LruCache[maxSize=3000,hits=1619,misses=30537,hitRate=5%]
RandomAccess[bytes=1518368,reads=30537,travel=10623307269,range=18917491,size=20769812]
Heap dump reason: user request
Analysis duration: 1249 ms
adb shell am start -d "template://bar" -a android.intent.action.VIEW
)lateinit var navHostController: NavHostController
)rememberCoroutineScope()
instead of LaunchedEffect()
for the templateNavigator.destinations.collect {}
(MainActivity.kt:71)I've also tried to use the Android Studio Profiled to investigate the leak, but I wasn't really successful. Here some screehsots:
I have the suspect that this could be a bug of some AndroidX library, but maybe I'm just doing something wrong.
The repro project is not exactly streamlined: it's a multi module single activity MVVM-MVI Compose only template project that I'm building. Is not done yet but most of the things should be in place.
This is the overview of the modules:
In short, the App only has the single Activity with no logic beside setting up the nav host. The navigation logic is inside the core-navigation
. Each feature module provides UI and business logic. Currently there are 3 features with 1 screen each: Foo, Bar and Debug. Foo screen has only one button that leads to Bar screen. The leak happens inside Bar screen, if you rotate the device twice. It does not happen if you access Bar via Deeplink.
ANSWER
Answered 2021-Nov-13 at 10:45The leak is actually a bug in the navigation compose library and a fix will be available with the next release: https://issuetracker.google.com/issues/204905432#comment4
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
No vulnerabilities reported
Save this library and start creating your kit
HTTPS
https://github.com/square/leakcanary.git
CLI
gh repo clone square/leakcanary
SSH
git@github.com:square/leakcanary.git
Share this Page
by Blankj
by square
by JakeWharton
by git-tips
by afollestad
See all Android Libraries
by nextcloud
by facebook
by Blankj
by JakeWharton
by LuckSiege
See all Android Libraries
by pnc
by svenkapudija
by ParanoidAndroid
by ParanoidAndroid
by polychrom
See all Android Libraries
by pnc
by stephanenicolas
by svenkapudija
by cketti
by ParanoidAndroid
See all Android Libraries
by pnc
by cketti
by passy
by polychrom
by sahan
See all Android Libraries
by ksoichiro
by hanspeide
by DeployGate
by codinguser
by vanniktech
See all Android Libraries
Save this library and start creating your kit
Open Weaver – Develop Applications Faster with Open Source