Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
like image 845
Robin Avatar asked May 23 '14 09:05

Robin


People also ask

How do I fix NullPointerException?

NullPointerException is thrown when a reference variable is accessed (or de-referenced) and is not pointing to any object. This error can be resolved by using a try-catch block or an if-else condition to check if a reference variable is null before dereferencing it.

Why do we get NullPointerException?

What Causes NullPointerException. The NullPointerException occurs due to a situation in application code where an uninitialized object is attempted to be accessed or modified. Essentially, this means the object reference does not point anywhere and has a null value.

What is NullPointerException in Java example?

NullPointerException is a runtime exception and it is thrown when the application try to use an object reference which has a null value. For example, using a method on a null reference.


3 Answers

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();
like image 144
Farouk Touzi Avatar answered Sep 30 '22 01:09

Farouk Touzi


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));
            }
        });
}
like image 39
Mark Pazon Avatar answered Sep 30 '22 01:09

Mark Pazon


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.

like image 37
Apoorv Avatar answered Sep 30 '22 00:09

Apoorv