Categories
discuss

How to treat memory leaks using the new AndroidProfiler

I’m trying to learn how to identify and treat memory leaks in my App. I’m reading this great article, but I’m a bit confused about how to apply that in the new “Android Profiler” tool, that came with Android Studio 3.0.

I’have a test application and LeakCanary is pointing that my App has memory leaks.

In fact, when I run the profiler and press “dump java heap” I can see that there are 4 instances of my MyCollectionActivity and, when I click on these instances, I can see the details:

enter image description here

But the tool that is shown in the article has options I cannot see in the “Android Profiler”:

I will not go into depth about how to navigate the huge memory heap.
Instead I’ll direct your attention to the Analyzer Tasks in the upper
right corner of the screenshot below. All you have to do to detect the
memory leak introduced in the example above is to check Detect Leaked
Activities and then press play to get the leaked activity to show up
under Analysis Results.

Where, in the new tool, is, for example, this “Analyzer Tasks” and “Analysis Results” that shows instances that have leaks?

enter image description here

If we select the leaked activity we are presented with a Reference
Tree where the reference that is keeping the activity alive can be
identified. By looking for instances with depth zero we find that the
instance mListener located within the location manager is the reason
our activity can’t be garbage collected.

That Android Profiler’s image doesn’t show that Reference Tree too, it shows the reference, but it doesn’t seem to be very useful.

Answer

  1. First, you need to save the Heap Dump. The dump save with extension hprof. Check the below-attached image for saving this file.
  2. Open the same file in Android Studio, after that, you will be able to see the Analyser Tasks option at the top right corner.

enter image description here

Categories
discuss

get menuitem in oncreate or onresume

I need disable menu item on specific function and i have tried with some code like:

public class ExampleActivity extends AppCompatActivity
    Menu menu;

then assign here

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu, menu);
    this.menu = menu;
    return true;
}

Then later use assigned Menu object to get required items

menu.findItem(R.id.avviapc).setEnabled(false);

or:

MenuItem avviopc;

public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.right_home, menu);
        avviopc = menu.getItem(R.id.avviapc);
        return true;
    }

avviopc.setEnabled(false);

But i have alway crash:

java.lang.IndexOutOfBoundsException: Index: 2131296295, Size: 3
                      at java.util.ArrayList.get(ArrayList.java:411)
                      at android.support.v7.view.menu.MenuBuilder.getItem(MenuBuilder.java:741)

or:

Attempt to invoke interface method 'android.view.MenuItem android.view.Menu.findItem(int)' on a null object reference

I call: menu.findItem(R.id.avviapc).setEnabled(false); onCreate or onResume if specific value in if is true.

If call after 2/3 second after activity start with manual button the code work.

Answer

The menu is called after oncreate and onresume =)

Categories
discuss

Android Studio cannot be initialized (0xc0000005)

I have just installed Android Studio in my new notebook running Windows 10 – 64 bits with Java SE 8 152, but it suddently it stopped working, like, every time I try to run the Android Studio, the error message below appears:

“The application cannot be initialized correctly (0xc0000005)”

I’ve already tried to reinstall, run as admin, deactivate the antivirus… nothing worked.

Answer

I had similar problem and disabling “Force randomization for images (Mandatory ASLR)” for studio64.exe in Windows Defender Security Center > App & browser control > Exploit protection > “Program settings” tab fixed this (you have to point to exact binary file with full path as using just executable name doesn’t seem to work).

Categories
discuss

Jacoco is reporting 0 coverage of Kotlin classes by unit tests, in an Android project

I’m using Android Gradle Plugin 3.0.0.

I’m migrating an Android app from java to kotlin. My app has classes in Java and Kotlin, and tests are in Java.

I run ./gradlew clean jacocoTestReport.

This runs both unit tests (src/test) and instrumentation tests (src/androidTest).

The report produced by jacoco in app/build/reports/jacoco/jacocoTestReport/html/index.html doesn’t show coverage for Kotlin classes which are indeed covered by unit tests.

The report does show coverage correctly from instrumentation tests.

Note: I came across these other questions, which aren’t exactly the same issue:

Relevant portions of my app module’s build.gradle:

apply plugin: 'jacoco'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
...
android {
    defaultConfig {
        sourceSets {
            main.java.srcDirs += "$projectDir/src/main/kotlin"
        }
    }

    testOptions {
        unitTests {
            all {
                jvmArgs '-noverify', '-ea'
            }
            includeAndroidResources = true
        }
    }
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    ....
}

jacoco {
    toolVersion '0.7.9'
}

task jacocoTestReport(type: JacocoReport, dependsOn: ["testDebugUnitTest", "createDebugCoverageReport"]) {
    reports {
        html.enabled = true
    }
    classDirectories = fileTree(
            dir: "${buildDir}",
            includes: ["tmp/kotlin-classes/debug/ca/rmen/android/poetassistant/**/*.class",
                       "intermediates/classes/debug/ca/rmen/android/poetassistant/**/*.class"],
            excludes: ["**/R.class", "**/R*.class", "**/Manifest.class", "**/Manifest*.class", "**/BuildConfig.class",
                       // ignore databinding generated code:
                       "**/ca/rmen/android/poetassistant/databinding/*.class",
                       ... other excludes ...
                       "**/ca/rmen/android/poetassistant/BR.class",
                       "**/com/android/**/*.class"])
    sourceDirectories = files("${project.projectDir}/src/main/java", "${project.projectDir}/src/main/kotlin")
    executionData = fileTree(
            dir: "${buildDir}",
            includes: [
                    "jacoco/testDebugUnitTest.exec",
                    "outputs/code-coverage/connected/*coverage.ec"
            ])
}

Answer

I had to add includeNoLocationClasses = true to my gradle file as follows, to make the jacoco report reflect the coverage of Kotlin classes by unit tests:

android {
    testOptions {
        unitTests {
            all {
                jvmArgs '-noverify', '-ea'
                jacoco {
                    includeNoLocationClasses = true
                }
            }
            includeAndroidResources = true
        }
    }
}

Note: this solution works for running tests from the command line, but I still get 0% coverage when running with coverage from inside Android Studio.

Categories
discuss

Find the closest smaller value of an array

I think what I want is pretty simple but I can’t really find the correct solution.

I have this kind of array in Javascript :

[0, 38, 136, 202, 261, 399]

And I get a generated value from 0 to 600 on a button click. What I need is to find the nearest lower value in this array.

For example, if the generated value is 198, I want to get 136 as the result. If the generated value is 300, I want 261… If it’s 589, I want 399 etc etc.

Until now, I have tried with this code :

var theArray = [ 1, 3, 8, 10, 13 ];
var goal = 7;
var closest = null;

$.each(theArray, function(){
    if (closest == null || Math.abs(this - goal) < Math.abs(closest - goal)) {
        closest = this;
    }
});

alert(closest);

But it only returns the closest value… Now I need the to get only the closest smaller value for the given number… How can I improve my algorithm to fit my needs?

Thanks!

Answer

If you array is sorted, and small enough, a really simple mode to do what you want it’s simplly iterate over the array until number > number-in-array then return the number on the previous position.

function getClosestValue(myArray, myValue){
    //optional
    var i = 0;

    while(myArray[++i] < myValue);

    return myArray[--i];
}

Regards.

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..