Greg Peckory
Greg Peckory

Reputation: 8058

Referencing Android Activity View from a Singleton object

Suppose I have an Android Activity (SecondaryActivity), which is started from MainActivity

SecondaryActivity contains a text view, TextView tv;

I have a Singleton that looks something like this:

public class Singleton {
    private static final Singleton instance = new Singleton();

    private static TextView secTextView;

    public static Singleton getInstance() {
        return instance;
    }

    public void setTV(TextView tv){
        secTextView = tv;
    }

    public TextView getTV(){
        return secTextView;
    }
}

In my SecondaryActivity I do:

Singleton.getInstance().setTV(findViewById(R.id.sec_text_view));

Now imagine later I run finish() inside SecondaryActivity so the program state returns back to MainActivity, popping SecondaryActivity off the Activity stack.

And now imagine MainActivity runs

startActivity(new Intent(getApplicationContext, SecondaryActivity.class));

once again.

After this, if I run

Singelton.getInstance().getTV().setText("hello world"));

will we be referencing the TextView within the Activity currently at the top of the Activity stack?

Also, is there any obvious problems with my approach in general?

Upvotes: 0

Views: 889

Answers (1)

LordRaydenMK
LordRaydenMK

Reputation: 13321

will we be referencing the TextView within the Activity currently at the top of the Activity stack?

Only if you run Singleton.getInstance().setTV(findViewById(R.id.sec_text_view)); in the onCreate method of your second activity.

Also, is there any obvious problems with my approach in general?

YES!! You should not put views/activity references in static classes/fields. You are creating memory leaks. When you call finish from the SecondaryActivity your singleton still references the text view and the activity can't be garbage collected. This leaks memory.

When you start SecondaryActivity again, a new instance of SecondaryActivity is created. Unless you call setTV again your singleton still references the text view from the finished activity.

Here is a blog post with more information about memory leaks.

If you want to simplify view binding you should take a look at ButterKnife.

Upvotes: 1

Related Questions