[ACCEPTED]-NullPointerException on getActivity().runOnUiThread(new Runnable(){-nullpointerexception
I'm almost sure that this is caused when 4 the thread finish its work but the activity 3 is no longer visible.
You should check if 2 the getActivity()
call return null, and ...
To apply corrections 1 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();
After pressing back, your background thread 4 is still running. By the time that thread 3 reaches the getActivity().runOnUiThread()
code, the activity no longer 2 exists. Check if the activity still exists 1 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 3 is closed and your Thread
is still running it 2 will check whether the calling Activity
still exists.
If 1 it does not it will return
.
The reason for the NPE is that your thread 6 is not bound to the fragment lifecycle. Once 5 the fragment is detached from its hosting 4 activity, getActivity()
returns null.
As a solution, consider 3 removing the thread altogether and just 2 use postDelayed()
on a Handler
on the UI thread to post Runnable
s that 1 do the updates you want after a delay.
Try this one
TextView date = (TextView) getView().findViewById(R.id.date);
is date is null or not check 1
if(date !=null){
date.setText(DateUtils.formatDateTime(getActivity().getBaseContext(), System.currentTimeMillis(),DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR));
}
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.