Q: Result of query is setting application variable late I have one Fragment. For the OnClickListener() of all the views that are in the fragment I made another class UtilClickListener. There I am making db call on spinner onItemSelected using room persistence database. The database call first inserts data to the table and then updates an application variable in my application. 
So I am trying to access the updated application variable on the spinner onItemSelected() just after the database call. But the variable is not updating at once, later when I click on other views of the fragment then I get the updated value.
Fragment code:
public class Calculator extends Fragment   {

 @Nullable
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Spinner ageSpinner = rootView.findViewById(R.id.spinner_how_old);
        ageSpinner.setOnItemSelectedListener(new UtilOnClickListener(this));
CRSCalculatorAdapter ageListAdapter = new CRSCalculatorAdapter(rootView.getContext(),
                android.R.layout.simple_spinner_item,Arrays.asList(rootView.getContext().getResources().getStringArray(R.array.age_group)) );
        ageSpinner.setAdapter(ageListAdapter);
}
}

UtilOnClickListener class code:
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
 switch (parentSpinnerId[1]) {

            case "spinner_how_old}":

                mGlobals.setAge(parent.getSelectedItem().toString());
                CRSDatabaseInitializer.populateAsync(CRSDatabase.getDatabase(view.getContext()), crsCalculator.getContext(), Constants.QUERY_TYPE_ALL);
               mListener.onChangeActionBarTitle(Integer.valueOf(mGlobals.getFinalScore())); // Here I am updating score in the action bar which is updating late on the next view click

                break;
}

"CRSDatabaseInitializer" is calling an Asynctask for the database call.
Here is the database initializer code:
public class CRSDatabaseInitializer {
  public static void populateAsync(@NonNull final CRSDatabase db, Context context, String typeOfQuery) {

        PopulateDbAsync task = new PopulateDbAsync(db, typeOfQuery);
}

 private static class PopulateDbAsync extends AsyncTask<Void, Void, Void> {

        private final CRSDatabase mDb;
        private final String mQueryType;

        PopulateDbAsync(CRSDatabase db, String queryType) {
            mDb = db;
            mQueryType = queryType;
        }

        @Override
        protected Void doInBackground(final Void... params) {

 int scoreOfAge = Integer.valueOf(getScoreOnAge(mDb));
            mGlobals.setFinalScore(scoreOfAge); // this is the application variable I need to update.
return null;

}

public static int getScoreOnAge(CRSDatabase db) {

        int userScore = 0;
        if (mGlobals.getAge() != null) {
            userScore = Integer.valueOf(db.ageScoreDao().getScore(mGlobals.getAge(), mGlobals.getMarriedOrNot()));
        }
        return userScore;
    }
}

Adding more codes from CRSDatabaseInitializer where I am inserting my data into the room database:
private static void insertNocCode(CRSDatabase db) {


        NocCode nocData = new NocCode();
        List<String[]> str = insertData(db, "nocCodes.csv");
        for (int i = 0; i < str.size(); i++) {
            nocData.setmNocCode(str.get(i)[0]);
            nocData.setmTitle(str.get(i)[1]);
            nocData.setmSkilltype(str.get(i)[2]);
            addCRSData(db, nocData);


        }
    }

insertData(Database db, String filename); is the method where I am reading a csv file and inserting all the columns in the csv file.
public static List<String[]> insertData(CRSDatabase db, String fileName) {
        String[] str = new String[5];
        ArrayList<String[]> stringArray = new ArrayList<>();

        try {

            InputStreamReader is = new InputStreamReader(mContext.getAssets()
                    .open(fileName));

            BufferedReader reader = new BufferedReader(is);

            String line = "";

            while ((line = reader.readLine()) != null) {
                str = line.split(",");
                stringArray.add(str);
            }

        } catch (IOException ex) {
            ex.printStackTrace();

        } finally

        {
        }
        return stringArray;
    }

And the insert method definition:
private static NocCode addCRSData(final CRSDatabase db, NocCode nocCode) {
        db.nocCodeDao().insert(nocCode);
        return nocCode;
    }


A: So here is the update of this problem that I was going through. I solved the issue using handler. When I am making the database call, I am letting the DB to update the variable first , then I am running one handler to get the updated value later in the fragment. 
Here is the code I updated in the UtilOnClickListener class.
private static class MyHandler extends Handler {}
    private final MyHandler mHandler = new MyHandler();

    public static class UtilRunner implements Runnable {
        private final WeakReference<Calculator> mActivity;

        public UtilRunner(Calculator activity) {
            mActivity = new WeakReference<Calculator>(activity);
        }

        @Override
        public void run() {
            Calculator activity = mActivity.get();

            if (activity.getContext() instanceof MainActivity) {
                OnActionBarListener   mListener = (OnActionBarListener) activity.getContext();
                Globals mGlobals = (Globals) activity.getActivity().getApplicationContext();
                mListener.onChangeActionBarTitle(mGlobals.getFinalScore());

            }
        }
    }

And I am running the handler from OnClick of the views:
mHandler.postDelayed(mRunnable, 200);


A: There are various ways to handle this. In your case I am not able to understand why read operation is getting executed before inserted data is committed even though you are inserting and reading from the same thread. You can have a look on this discussion: stackOverFlow, what I learned from this discussion is that it's always better to take control in your hand because database internal implementation might change from time to time. Let's see the soution:


*

*Wrap the read query inside a transaction either by using annotation @Transaction in Dao class or by wrapping the code for insertion in db.beginTransaction and db.endTransaction.devGuide. This ensures that read can't happen while database is being written.

*What I find best for this is using Rx-Java See Introdution. You can do the insertion and then get notified when it completes and perform the read operation. Since insert operation will not return anything, wrap it inside Completable.fromAction. Completable observable has operator obs1.andThen(obs2), as clear from the name first obs1 is completed then only obs2 is executed. Note that your db.ageScoreDao().getScore(..) method should return an observable, hence wrap the return value in an Observable;
Completable.fromAction(new Action(){
    @Override
    public void run() throws Exception {
        db.nocCodeDao().insert(nocCode);
    }
}).andThen(return db.ageScoreDao().getScore(..)
  .subscribeOn(Scheduler.io())   //do database query on io thread
  .observeOn(AndroidScheduler.mainThread())
  .subscribeWith(new DisposableObserver<Object>(){

      @Override
      public void onNext(Object o) {
           //Here you update the variable
      }
      @Override
      public void onError(Throwable e) {..}
      @Override
      public void onComplete() {..}
  });

