How to change TextView Text from static method?

Viewed 141

I have a value inside my app which constantly increases, the handler which does that is in a static method inside my "EventHandlerClass.java". I now want to show this value on my TextView inside my MainActivity.

Here is my static method with the handler:

public static void pointsCounter() {
        handler = new Handler(Looper.getMainLooper());

        runnable = new Runnable() {
            public void run() {
                points = points + 5;
                String pointMsg = "Points: " + points;
                MainActivity.coinsTextView.setText(pointMsg);
                 
                handler.postDelayed(this, 1000);
            }
        };
        handler.postDelayed(runnable, 1000);
    }

This pointsCounter Method gets called from another static method inside the EventHandlerClass.java.

It increases the points value +5 every second and I want it to get displayed in a TextView. What is the right way to do it? Because when I try it this way I have to make the coinsTextView in the MainActivity static, we all know you cannot reference non static variable from static context. When I do so it tells me "Do not place Android context classes in static fields; this is a memory leak". So my question is how can I update my UI element from the static method without risking a memory leak? What is the right way to do it?

1 Answers

as you said Never place static View or Context in your application since it will cause unexcepted memory leaks, however if you still want to use static TextView in your application you can wrap the TextView in a WeakReference :

WeakReference: a weak reference is a reference not strong enough to keep the object in memory. If we try to determine if the object is strongly referenced and it happened to be through WeakReferences, the object will be garbage-collected. this an example how to use it :

public class MainActivity extends AppCompatActivity {
    private static WeakReference<TextView> viewWeakReference;
    private static Handler handler;
    private static int points;
    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        
        textView = findViewById(R.id.textV);
        viewWeakReference = new WeakReference<>(textView);
        pointsCounter();
    }


    public static void pointsCounter() {
        handler = new Handler(Looper.getMainLooper());

        Runnable runnable = new Runnable() {
            public void run() {
                points = points + 5;
                String pointMsg = "Points: " + points;
                viewWeakReference.get().setText(pointMsg);
                handler.postDelayed(this, 1000);
            }
        };
        handler.postDelayed(runnable, 1000);
    }
}
Related