NullPointerException on getActivity().runOnUiThread(new Runnable(){ [duplicate] NullPointerException on getActivity().runOnUiThread(new Runnable(){ [duplicate] android android

NullPointerException on getActivity().runOnUiThread(new Runnable(){ [duplicate]


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 Cardfinal boolean keepRunning1 = true;Thread thread_two = new Thread(){@Overridepublic 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();


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));            }        });}


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.