Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android weakReference to Activity goes null while activity is executing

I am getting a NullPointerException that I cannot understand why this is happening. mainActivityWeakReference.get() appears to return null.

So my guess is the Activity is recreated and the reference variable is set to null once the class is loaded and the reference is only updated once the onCreate method is called. But what I do not understand is that I am busy performing instructions within the activity that the reference points to and yet the reference is null.

Can Activities co-exist for a brief moment and how do I handle this situation. To me it seems that a simple null check would not be sufficient to address the problem. Perhaps I should call finish();

public class MainActivity extends android.support.v7.app.AppCompatActivity {

  private WeakReference<AppCompatActivity> mainActivityWeakReference = null;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
         mainActivityWeakReference = new WeakReference<AppCompatActivity>(this);
  }

   public void handleAction(UserAction userAction) {
        switch (userAction) {
           case UPDATE_UI:
                << ERROR HERE
                mainActivityWeakReference.get().getSupportFragmentManager().executePendingTransactions();
                break;
       }
    }

My Stack Trace:

java.lang.NullPointerException: Attempt to read from field 'android.os.Handler android.support.v4.a.m.a' on a null object reference
    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1476)
    at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:490)
    at za.co.entersekt.nedbank.MainActivity.handleAction(MainActivity.java:297)

More detail added:

public abstract class FragmentManager {
....

public boolean execPendingActions() {
        if (mExecutingActions) {
            throw new IllegalStateException("Recursive entry to executePendingTransactions");
        }

        if (Looper.myLooper() != mActivity.mHandler.getLooper()) {<<FragmentManager.java:1476
            throw new IllegalStateException("Must be called from main thread of process");
        }
like image 968
Wayne Avatar asked Oct 19 '22 15:10

Wayne


1 Answers

That is because by definition a weak reference is a reference that does not protect the referenced object from collection by a garbage collecton
So if you need an instance of activity try doing getActivity() or getContext()

like image 159
Mightian Avatar answered Oct 21 '22 06:10

Mightian