user2121 user2121 - 5 months ago 12
Android Question

how to count number of objects created of inner class

I have an activity and inside it I have a class called AsyncTask. Inside the AsyncTask class I want to declare a counter as a static variable but I can't because the AsyncTask class is assumed as an inner class to the mainActivity.

Is there any way to create a static variable inside the AsycTask "inner class" to count the number of objects created of the AsyncTask for an example?

code

class MainActivity extends Activity {
....
....
....
....

class MyAsync extends AsyncTask <void, Void, Void> {

private static int counter = 0; // is not possible here
}

}

Answer

You can create a constructor to increment the counter inside the AsyncTask.

Do it like this :

class MainActivity extends Activity {
....
....
....
....
    int counter = 0; 
    class MyAsync extends AsyncTask <void, Void, Void> {

       MyAsync()
       {
           counter++;
       }
    }

}

Logic behind this is : Constructor of any class will be called everytime when the new object of that will created. Inside constructor we have counter++ so each time when the new object is created the counter is incremented and You will have the count of number of objects created.

Comments