Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The weakreference object has been Garbage Collected in static Handler

Given the code

 private static class MyHandler extends Handler 
 {
       private final WeakReference<MainActivity> mTarget;
       MyHandler(MainActivity intarget) {
       mTarget = new WeakReference<MainActivity>(intarget);
 }

 @Override
 public void handleMessage(Message msg) 
 {
       MainActivity target = mTarget.get();  // target becomes null will causes null      pointer exception
       switch (msg.what) {
        ..
        }
 }
}

To avoid NullPoinetrException i can use :

if(target != null {
     // do something
}

But when target becomes null, i can not proceed further in the app.

The question:

Is there any way to get back target when it becomes null and proceed further or should i finish activity or app ?

Thanks.

like image 249
Praveen Avatar asked Apr 01 '26 07:04

Praveen


1 Answers

What's the reasoning behind using an object you will always need to reference as a WeakReference?

References are used as caches, not as objects to access freely. WeakReferences will be wiped as soon as the GC thinks they are not needed, EVEN if they're going to be needed.

Also, the WeakReference never becomes null. It's content may become null, but the reference itself will still be a valid WeakReference. It will be empty, but not null. There's a difference between an empty object and a null object: An empty object is still allocated in memory.

I'd just remove the WeakReference and store the MainActivity as a full object. If you're getting memory leaks, fix your memory leaks instead of trying to work around them.

like image 127
Charlie-Blake Avatar answered Apr 02 '26 22:04

Charlie-Blake



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!