getActivity() returns null in Fragment function

后端 未结 15 1855
别那么骄傲
别那么骄傲 2020-11-22 07:28

I have a fragment (F1) with a public method like this

public void asd() {
    if (getActivity() == null) {
        Log.d(\"yes\",\"it is null\");
    }
}
         


        
15条回答
  •  梦如初夏
    2020-11-22 08:12

    PJL is right. I have used his suggestion and this is what i have done:

    1. defined global variables for fragment:

      private final Object attachingActivityLock = new Object();

      private boolean syncVariable = false;

    2. implemented

    @Override
    public void onAttach(Activity activity) {
      super.onAttach(activity);
      synchronized (attachingActivityLock) {
          syncVariable = true;
          attachingActivityLock.notifyAll();
      }
    }
    

    3 . I wrapped up my function, where I need to call getActivity(), in thread, because if it would run on main thread, i would block the thread with the step 4. and onAttach() would never be called.

        Thread processImage = new Thread(new Runnable() {
    
            @Override
            public void run() {
                processImage();
            }
        });
        processImage.start();
    

    4 . in my function where I need to call getActivity(), I use this (before the call getActivity())

        synchronized (attachingActivityLock) {
            while(!syncVariable){
                try {
                    attachingActivityLock.wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    

    If you have some UI updates, remember to run them on UI thread. I need to update ImgeView so I did:

    image.post(new Runnable() {
    
        @Override
        public void run() {
            image.setImageBitmap(imageToShow);
        }
    });
    

提交回复
热议问题