androidandroid-recyclerviewlocal-variablesmember-variables

Safely declaring a RecyclerView object: as a field of the activity or as a local variable of the onCreate() method?


Initial code:

public class SummaryActivity extends AppCompatActivity
{
    private RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_summary);

        recyclerView = findViewById(R.id.summary_recycler);
        ...

Android Studio (v3.3) suggested to make recyclerView local to onCreate() method.

Modified code:

public class SummaryActivity extends AppCompatActivity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_summary);

        RecyclerView recyclerView = findViewById(R.id.summary_recycler);
        ...

Ran both versions multiple times and could not notice any difference. Is one better than the other? If yes, could you please explain why? I have an inkling that declaring recyclerView as a class field/member is safer, however lack the understanding to be sure enough.

I wonder what happens to recyclerView in the second version after the onCreate() method has finished executing. Would garbage collection later on suddenly destroy the object?

The closest thing I found on this topic so far was: Member object instantiation in onCreate vs. during declaration, but it sadly doesn't touch the specific issue that I am facing.

I am sure that this matter doesn't apply to just RecyclerView objects alone and that the understanding will help me code more appropriately in the future, also in other contexts.

Would truly appreciate any clarification offered. Thanks in advance!


Solution

  • I wonder what happens to recyclerView in the second version after the onCreate() method has finished executing. Would garbage collection later on suddenly destroy the object?

    Since the object we are talking about here is a View which is part of the Activity's "content View", it will only be destroyed if the Activity as a whole will be destroyed.

    There is a difference to "normal" fields: the RecyclerView will be instantiated under-the-hood because you call setContentView(R.layout.activity_summary); and so the runtime will inflate the layout file.

    In your code, you don't instantiate it but you assign it to a variable by "finding" it:

    RecyclerView recyclerView = findViewById(R.id.summary_recycler);
    

    If you keep the variable local, it may improve the readability of your code. But you should only do so if you don't need to access the RecyclerView in more than one method, because each time that findViewById() is called, the whole View tree will be searched until a View with a matching id is found.