Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should adapters in Android be static inner classes or non-static inner classes

I have a ListView in an Activity and I am setting a custom adapter to the ListView.

Should my adapter class be:

private static class MyAdapter extends ArrayAdapter 

or

private class MyAdapter extends ArrayAdapter

I guess it should make no difference as long as the adapter is enclosed within the activity reference but wanted to confirm that.

like image 719
dnkoutso Avatar asked Oct 28 '11 03:10

dnkoutso


People also ask

Should all inner classes be static?

So the inner class must either itself be static (in which case no owning instance is required), or you only create the inner class instance from within a non-static context.

What is the difference between static inner class and non-static inner class?

Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class.

Why inner classes Cannot have static declarations?

Note: We can not have a static method in a nested inner class because an inner class is implicitly associated with an object of its outer class so it cannot define any static method for itself.

Can we use static in inner class?

Java static nested class A static class is a class that is created inside a class, is called a static nested class in Java. It cannot access non-static data members and methods. It can be accessed by outer class name.


1 Answers

Holding onto the context is fine from within an adapter if you are careful about how you use the adapter. Adapters are usually tied to the lifecycle of their Context (an Activity) so it's fine. Use a WeakReference only if it makes sense.

like image 100
Romain Guy Avatar answered Oct 09 '22 10:10

Romain Guy