43

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)
Robin
  • 577
  • 1
  • 7
  • 13
  • 2
    It is possible that the `Activity` is getting closed on back button click and hence you are getting `getActivity()` as null – Apoorv May 23 '14 at 09:29
  • @Apoorv how can I go about stopping the activity from closing upon back button being clicked? – Robin May 23 '14 at 09:31

5 Answers5

72

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();
Charuක
  • 12,953
  • 5
  • 50
  • 88
Farouk Touzi
  • 3,451
  • 2
  • 19
  • 25
  • @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? – Jas Nov 19 '15 at 08:57
  • 1
    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. – Farouk Touzi Nov 19 '15 at 09:08
21

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));
            }
        });
}
Johnny Five
  • 987
  • 1
  • 14
  • 29
Mark Pazon
  • 6,167
  • 2
  • 34
  • 50
10

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.

Apoorv
  • 13,470
  • 4
  • 27
  • 33
  • 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... – Ali Kazi Oct 17 '16 at 06:16
8

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.

laalto
  • 150,114
  • 66
  • 286
  • 303
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));
}
Macrosoft-Dev
  • 2,195
  • 1
  • 12
  • 15