NullPointerException on getActivity().runOnUiThread(new Runnable(){

36,830

Solution 1

I'm almost sure that this is caused when the thread finish its work but the activity is no longer visible.

You should check if the getActivity() call return null, and ...

To apply corrections on your code, look at this:

// (Calendar) Date function - Displays dateview on Card
final boolean keepRunning1 = true;
Thread thread_two = new Thread(){

@Override
public void run(){

    while(keepRunning1){

        // Make the thread wait half a second. If you want...
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            Toast.makeText(getActivity().getApplicationContext(), "Default Signature                         Fail", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }

        // here you check the value of getActivity() and break up if needed
        if(getActivity() == null)
            return;

        getActivity().runOnUiThread(new Runnable(){
        @Override
        public void run(){
           TextView date = (TextView) getView().findViewById(R.id.date);
           date.setText(DateUtils.formatDateTime(getActivity().getBaseContext(), System.currentTimeMillis(),DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR));
           }
         });
    }
}
};thread_two.start();

Solution 2

After pressing back, your background thread is still running. By the time that thread reaches the getActivity().runOnUiThread() code, the activity no longer exists. Check if the activity still exists like so:

if (getActivity() != null) {
        getActivity().runOnUiThread(new Runnable(){
                @Override
                public void run(){
                    TextView date = (TextView) getView().findViewById(R.id.date);
                    date.setText(DateUtils.formatDateTime(getActivity().getBaseContext(), System.currentTimeMillis(),DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR));
            }
        });
}

Solution 3

Put

if(getActivity() == null)
        return;

before getActivity().runOnUiThread(new Runnable(){ that way when the back button is closed and your Thread is still running it will check whether the calling Activity still exists.

If it does not it will return.

Solution 4

The reason for the NPE is that your thread is not bound to the fragment lifecycle. Once the fragment is detached from its hosting activity, getActivity() returns null.

As a solution, consider removing the thread altogether and just use postDelayed() on a Handler on the UI thread to post Runnables that do the updates you want after a delay.

Solution 5

Try this one

TextView date = (TextView) getView().findViewById(R.id.date);

is date is null or not check

if(date !=null){
                    date.setText(DateUtils.formatDateTime(getActivity().getBaseContext(), System.currentTimeMillis(),DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR));
}
Share:
36,830
Robin
Author by

Robin

Updated on July 09, 2022

Comments

  • Robin
    Robin almost 2 years

    I know there are many different causes for NPE but mine is slightly weird (At least to me).

    So I have converted my Activities to Fragments successfully, but my problem appears to be coming from the function that displays the date. When the application is running, everything works just fine. But as soon as you press the back button. The app force closes, then in the log it says I'm getting NullPointerException at line 102. So looking at the code, I did research on this but unfortunately got nothing.

    This is the line where the error is coming from when you press the back button.

    getActivity().runOnUiThread(new Runnable(){
    

    Also I have tried disabling the back button (As I'm building a launcher and it's not needed). But it doesn't seem to be working.

    Here is the code for the whole date displaying method/function.

    // (Calendar) Date function - Displays dateview on Card
    final boolean keepRunning1 = true;
    Thread thread_two = new Thread(){
        @Override
        public void run(){
    
            while(keepRunning1){
    
                // Make the thread wait half a second. If you want...
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    Toast.makeText(getActivity().getApplicationContext(), "Default Signature Fail", Toast.LENGTH_LONG).show();
                    e.printStackTrace();
                }
    
                    getActivity().runOnUiThread(new Runnable(){
                    @Override
                    public void run(){
                        TextView date = (TextView) getView().findViewById(R.id.date);
                        date.setText(DateUtils.formatDateTime(getActivity().getBaseContext(), System.currentTimeMillis(),DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR));
                    }
                });
            }
        }
    };
    
    thread_two.start();
    

    Thanks for your time, hopefully you can shed some light on what I'm doing wrong.

    Logcat -

    05-23 21:17:33.216: E/AndroidRuntime(6906): java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.app.FragmentActivity.runOnUiThread(java.lang.Runnable)' on a null object reference
    05-23 21:17:33.216: E/AndroidRuntime(6906):     at com.activelauncher.fragments.UtilsFragment$2.run(UtilsFragment.java:102)
    
  • Jas
    Jas over 8 years
    @FaroukTouzi I want to execute the code inside runOnUiThread anyways. If i do the above, then the code inside it won't get executed at all right?
  • Farouk Touzi
    Farouk Touzi over 8 years
    Like I said above, if the main activity is no longer visible, the code inside runOnUiThread won't be executed. This is why you should always check for main activity visibility, to avoid app crash.
  • Vadiraj Purohit
    Vadiraj Purohit over 7 years
    Inside postDelayed method of Handler got getActivity() as null :(
  • Ali Kazi
    Ali Kazi over 7 years
    But what about the operation that was supposed to take place? You return if getActivity() is null, but then something has to call the method again so it can complete when getActivity() is not null...