Before marking the question as duplicate, read my issue first.
I have map fragment that execute a lot of process using firebase realtime database and the issue that I'm facing is that some callbacks do intensive processing which makes the map very laggy and sometimes crashes the app, so I made a new thread to execute that callback and inside it there's some code that update the UI, so I run it using runOnUiThread
.
Everything worked fine once I open the fragment for the first time, after I press back and reopen it again, getActivity
keeps coming null
always!
I tried this famous workaround
FragmentActivity mActivity;
@Override
public void onAttach(Context context) {
super.onAttach(context);
mActivity = (FragmentActivity) context;
}
@Override
public void onDetach() {
super.onDetach();
mActivity = null;
}
And used mActivity
instead of getActivity
, but it didn't work..! mActivity
keeps coming as null
also.!
I don't know why this error happens! when I open the fragment again it added again on the backstack and attached again so the activity shouldn't be null, and why it worked when added on the first time launch only?!
The Code
void updateStudents() {
if (isRecursionEnable) {
return;
}
isRecursionEnable = true;
thread = new Thread(new Runnable() {
@Override
public void run() {
if (!thread.isInterrupted()) {
studentQuery.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(final DataSnapshot snapshot, String s) {
Student_User.add(snapshot.getValue(TestUserStudent.class));
if (getActivity() != null) { // NPE
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
showAllMarkers(snapshot); // show custom markers on the map
}
});
}
}
@Override
public void onChildChanged(final DataSnapshot snapshot, String s) {
Student_User.add(snapshot.getValue(TestUserStudent.class));
if (getActivity() != null) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
showAllMarkers(snapshot);
}
});
}
}
@Override
public void onChildRemoved(DataSnapshot snapshot) {
}
@Override
public void onChildMoved(DataSnapshot snapshot, String s) {
}
@Override
public void onCancelled(DatabaseError error) {
}
});
}
}
}, "");
thread.start();
}