I have a couple of fragments in the viewpager, I set some values in the first fragment I have to update the very next fragment with the values from the first one, so I store the values created in the first fragment in the database and I'm trying to update the next view with the values from database, I'm using Room for database, right now what I'm trying to follow an approach described in this answer How to determine when fragment becomes visible in viewpager and what I'm doing is I'm creating a new thread to access the database and update the global variable bodyScore
from the database. here is some code
public class MindFragment extends Fragment implements FragmentLifecycle {
SeekBar mindSeekBar;
private View rootView;
ViewPager viewPager;
private int seekBarProgress;
private Date date = new Date();
private static final String TAG = MindFragment.class.getSimpleName();
private LifeWheelView lview;
private volatile int bodyScore;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.activity_fill, container, false);
viewPager = getActivity().findViewById(R.id.viewpager);
lview = rootView.findViewById(R.id.lifeWheelView);
lview.setMind(bodyScore, 0);
}
@Override
public void onResumeFragment() {
Log.i(TAG, "onResumeFragment()");
Thread thread = new Thread(new Runnable() {
ScoreDao mScoreDao;
CategoryDao mCategoryDao;
@Override
public void run() {
LifewheelRoomDatabase db = LifewheelRoomDatabase.getDatabase(getContext());
mScoreDao = db.scoreDao();
mCategoryDao = db.categoryDao();
CategoryName categoryName = mCategoryDao.getCategoryByName("Body");
Integer category_id = categoryName.getId();
int bodyScoreExceptionFlag = 0;
while ( bodyScoreExceptionFlag == 0 ) {
try {
Score st = mScoreDao.getScoreByCategory(HelperMethods.getStartOfDay(), HelperMethods.getEndOfDay(), category_id);
if( st == null) {
bodyScore = 0;
}
else {
bodyScore = st.score;
}
bodyScoreExceptionFlag++;
} catch (NullPointerException e) {
continue;
}
}
}
});
thread.start();
lview.setMind(bodyScore, 0);
}
}
On the line lview.setMind(bodyScore,0);
I'm getting a NullPointerException
.
So my question is:
if the Fragment has been created before it's been viewed
lview
variable should be initialized. and when it becomes visible why when I'm trying to call a method on it why am I getting this exception.How should the things like this be handled when updating the view ( not list or recycler view ) from the database in the view pager where the subsequent views are updated with the input from the last view.