Question

I have an app that uses Fragments. It has 3 Fragments in the View. The left-most Fragment is a list of carers. The middle Fragment is another list which is a carer rota.

When the main screen (Activity that houses all 3 fragments) is loaded only the left fragment is loaded. if you pick a carer, the middle Fragment is loaded (the rota).

The problem is that the user can select next, previous etc from the optionsMenu to select the next or previous day's rota for a given carer. I don't want the optionsMenu showing the next or previous buttons if a rota (middle fragment) is not currently displayed.

Each rota is loaded from an AsyncTask. In onPostExecute i load the carerdetailsFragment, which is the rota. I've overridden the onPrepareOptionsMenu and checked in there to see if a rota is displayed. I have also called invalidateOptionsMenu from onPostExecute after getting a rota.

The optionsMenu does hide the buttons at first, when only the left Fragment is showing, but when you get a rota it doesn't update the optionsmenu until you load the rota again.

why is invalidateOptionsMenu not running the first time?

<?xml version="1.0" encoding="utf-8"?>





    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/carefreebgscaled"

    >


    <fragment android:name="com.carefreegroup.rr3.carefreeoncall.CarerListFragment"
            android:id="@+id/carerlist"
            android:layout_weight="1"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />


    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/carerdetailsinfofragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1" />

<!--     <fragment android:name="com.carefreegroup.rr3.carefreeoncall.CarerDetailsFragment" -->
<!--             android:id="@+id/carerdetails" -->
<!--             android:layout_weight="1" -->
<!--             android:layout_width="match_parent" -->
<!--             android:layout_height="match_parent" /> -->

<!--     <fragment android:name="com.carefreegroup.rr3.carefreeoncall.CarerPurposeOfCallFragment" -->
<!--             android:id="@+id/carerpurposeofcall" -->
<!--             android:layout_weight="1" -->
<!--             android:layout_width="match_parent" -->
<!--             android:layout_height="match_parent" /> -->

    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/carerpurposeofcallfragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1" />

</LinearLayout>

.

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;


import com.carefreegroup.rr3.carefreeoncall.CarerListFragment.OnArticleSelectedListener;
import com.carefreegroup.rr3.carefreeoncall.RotaDatePicker.OnRotaDatePickerListener;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;

import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;

public class OnCallListAndDetailsActivity extends Activity implements OnArticleSelectedListener, OnRotaDatePickerListener{

    private static final String TAG = OnCallListAndDetailsActivity.class.getSimpleName();
    RROnCallApplication rrOnCallApp;
    String firstName;
    String lastName;
    Intent intent;
    String carerIDUpdateRota;
    String updatedRotaDate;
    DateTime now;
    String mCarerID;

    String callStartTime;
    String callDuration;
    String callID;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.oncalllistanddetailsactivitylayout);



        rrOnCallApp = (RROnCallApplication) getApplication();




        setTitle("Carer Update Call"); 

                Cursor carers = rrOnCallApp.dbModel.queryAllFromCarer();
                Log.e(TAG, "there are " + carers.getCount() + " in the carer table(OnCallListAndDetailsActivity)");


                View CarerDeailsInfoFragContainer = (View)findViewById(R.id.carerdetailsinfofragment_container);

                if ( CarerDeailsInfoFragContainer ==  null) {

                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

                }

                intent = this.getIntent();

                Log.e(TAG, "Action of intent = " + intent.getAction());


                if (intent.getAction() != null && intent.getAction().equalsIgnoreCase("SHOW_UPDATED_ROTA")){

                    if ( CarerDeailsInfoFragContainer !=  null) {

                    carerIDUpdateRota = intent.getStringExtra("carerid");
                    updatedRotaDate = intent.getStringExtra("rotadate");

                    String[] params = new String[] { carerIDUpdateRota, updatedRotaDate };
                    AsyncGetRota agr = new AsyncGetRota();
                    agr.execute(params);

                }else{

                    carerIDUpdateRota = intent.getStringExtra("carerid");
                    updatedRotaDate = intent.getStringExtra("rotadate");

                    Intent intent = new Intent(this, DisplayCarerDetailsfragmentActivity.class);
                    intent.putExtra("carerid", carerIDUpdateRota);
                    intent.putExtra("date", updatedRotaDate);

                    startActivity(intent);

                }
        }




    }//end of onCreate




    @Override
    public void onArticleSelected(String carerId, String _carerFirstName, String _carerLastName, boolean longClick) {
        // TODO Auto-generated method stub

        Log.e(TAG, "in onArticleSelected!!");

        mCarerID = carerId;


        CarerPurposeOfCallFragment test = (CarerPurposeOfCallFragment) getFragmentManager().findFragmentById(R.id.carerpurposeofcallfragment_container);
        if (test != null && test.isVisible()) {

            Log.e(TAG, "CarerPurposeOfCallFragment is visible");


            FragmentTransaction transaction = getFragmentManager().beginTransaction();

            // Replace whatever is in the fragment_container view with this fragment,
            // and add the transaction to the back stack
            transaction.remove(test);
            //transaction.addToBackStack(null);

            // Commit the transaction
            transaction.commit();
        }
        else {
            //do nothing
            Log.e(TAG, "CarerPurposeOfCallFragment is not visible");
        }





            if(longClick == false){

                CarerInfoFragment carerInfoFrag = new CarerInfoFragment();
                if (carerInfoFrag != null && carerInfoFrag.isVisible()) {

                    Log.e(TAG, "CarerInfoFragment is visible");


                    FragmentTransaction transaction = getFragmentManager().beginTransaction();

                    // Replace whatever is in the fragment_container view with this fragment,
                    // and add the transaction to the back stack
                    transaction.remove(carerInfoFrag);
                    //transaction.addToBackStack(null);

                    // Commit the transaction
                    transaction.commit();
                }   


        now = new DateTime();
        //now.minusDays(14);
        DateTimeFormatter fmt = DateTimeFormat.forPattern("d-MMM-Y");
        String formattedNow = fmt.print(now);





        View CarerDetailsInfoFragContainer = (View)findViewById(R.id.carerdetailsinfofragment_container);

        if ( CarerDetailsInfoFragContainer ==  null) {

            Intent intent = new Intent(this, DisplayCarerDetailsfragmentActivity.class);
            intent.putExtra("carerid", carerId);
            intent.putExtra("date", formattedNow);

            startActivity(intent);


            } else {
            // DisplayFragment (Fragment B) is in the layout (tablet layout),
            // so tell the fragment to update

                String[] params = new String[] { carerId, formattedNow };
                AsyncGetRota agr = new AsyncGetRota();
                agr.execute(params);



            }

            }else{

                View CarerDetailsInfoFragContainer = (View)findViewById(R.id.carerdetailsinfofragment_container);

                if ( CarerDetailsInfoFragContainer ==  null) {


                    Intent intent = new Intent(this, DisplayCarerInfofragmentActivity.class);
                    startActivity(intent);




                }else{

                Fragment newFragment = new CarerInfoFragment();


                FragmentTransaction transaction = getFragmentManager().beginTransaction();


                // Replace whatever is in the fragment_container view with this fragment,
                // and add the transaction to the back stack
                transaction.replace(R.id.carerdetailsinfofragment_container, newFragment);
                //transaction.addToBackStack(null);

                // Commit the transaction
                transaction.commit();


                }



            }






    }//end of onArticleSelected








    private class AsyncGetRota extends AsyncTask<String, Void, TwoDimensionalArrayList<String>> {


            TwoDimensionalArrayList rotaArray;
            ProgressDialog progressDialog;
            String carerID = null;
            String date = null;


            @Override
            protected void onPreExecute() {




                progressDialog = new ProgressDialog(OnCallListAndDetailsActivity.this);
                progressDialog.setTitle("Connecting to Server");
                progressDialog.setMessage("retrieving rota...");
                progressDialog.setIndeterminate(true);
                progressDialog.show();

            }



            @Override
            protected TwoDimensionalArrayList<String> doInBackground(String... params) {

                try {

                    carerID = params[0];
                    date = params[1];


                    Log.e(TAG, "now in doinbackground = " + params[1]);
                    rotaArray = rrOnCallApp.webService.getCarerRota(params[0], params[1]);

                    if (rotaArray == null) {
                        Log.e(TAG, "about to call onstart");

                    }

                } catch (Exception e) {

                    e.printStackTrace();

                }
                return rotaArray;

            }//end of doInBackground



            @Override
            protected void onPostExecute(TwoDimensionalArrayList<String> result) {
                super.onPostExecute(result);
                if (progressDialog != null)
                    progressDialog.dismiss();



                if (result == null) {

                    Log.e(TAG, "rotaArray in onPostExecute OnCallListAndDetailsActivity = null");

                } else {




                    Log.e(TAG, "rotaArray in onPostExecute OnCallListAndDetailsActivity has size " + rotaArray.size());
                    Bundle b = new Bundle();
                    b.putSerializable("rotaArray", rotaArray);
                    b.putString("carerid", carerID);
                    b.putString("date", date);

                    Fragment newFragment = new CarerDetailsFragment();
                    newFragment.setArguments(b);

                    FragmentTransaction transaction = getFragmentManager().beginTransaction();


                    // Replace whatever is in the fragment_container view with this fragment,
                    // and add the transaction to the back stack
                    transaction.replace(R.id.carerdetailsinfofragment_container, newFragment);
                    //transaction.addToBackStack(null);

                    // Commit the transaction
                    transaction.commit();


                    OnCallListAndDetailsActivity.this.invalidateOptionsMenu();





                }

            }//end of onPostExecute

    }








//  @Override
//  public void onRotaButtonSelected(String action, String date, String carerid) {
//      
//      CarerPurposeOfCallFragment test = (CarerPurposeOfCallFragment) getFragmentManager().findFragmentById(R.id.carerpurposeofcallfragment_container);
//      if (test != null && test.isVisible()) {
//          
//          Log.e(TAG, "CarerPurposeOfCallFragment is visible");
//          
//          
//          FragmentTransaction transaction = getFragmentManager().beginTransaction();
//
//          // Replace whatever is in the fragment_container view with this fragment,
//          // and add the transaction to the back stack
//          transaction.remove(test);
//          //transaction.addToBackStack(null);
//
//          // Commit the transaction
//          transaction.commit();
//      }
//      
//      if(action.equalsIgnoreCase("next")){
//          
//          Log.e(TAG, "next clicked and date passed in is " + date);
//          
//          now = now.plusDays(1);
//          
//          DateTimeFormatter fmt = DateTimeFormat.forPattern("d-MMM-Y");
//          String formattedNow = fmt.print(now);
//          
//          getRota(formattedNow, carerid);
//          
//          
//          
//      
//      }else if(action.equalsIgnoreCase("previous")){
//          
//          Log.e(TAG, "previous clicked");
//          
//            now = now.minusDays(1);
//          
//          DateTimeFormatter fmt = DateTimeFormat.forPattern("d-MMM-Y");
//          String formattedNow = fmt.print(now);
//          
//          getRota(formattedNow, carerid);
//          
//      }else if(action.equalsIgnoreCase("pickday")){
//          
//          Log.e(TAG, "pickday clicked");
//          
//          loadDatePicker();
//          
//          
//      }
//      
//  }//end of onRotaButtonSelected



    public void getRota(String date, String carerid){


        View CarerDetailsInfoFragContainer = (View)findViewById(R.id.carerdetailsinfofragment_container);

        if ( CarerDetailsInfoFragContainer ==  null) {

            Intent intent = new Intent(this, DisplayCarerDetailsfragmentActivity.class);
            intent.putExtra("carerid", carerid);
            intent.putExtra("date", date);

            startActivity(intent);


            } else {
            // DisplayFragment (Fragment B) is in the layout (tablet layout),
            // so tell the fragment to update

                String[] params = new String[] { carerid, date };
                AsyncGetRota agr = new AsyncGetRota();
                agr.execute(params);

            }


    }//getRota



    public void loadDatePicker(){

        Fragment newFragment = new RotaDatePicker();


        FragmentTransaction transaction = getFragmentManager().beginTransaction();


        // Replace whatever is in the fragment_container view with this fragment,
        // and add the transaction to the back stack
        transaction.replace(R.id.carerdetailsinfofragment_container, newFragment);
        //transaction.addToBackStack(null);

        // Commit the transaction
        transaction.commit();


    }




    @Override
    public void onRotaDateSelected(DateTime date) {

        //set now so when the user clicks next/previous after pickDay has been pressed the datatime is remembered
        //eg  24->25->29->28
        //not 24->25->29->24
        now = date;

        DateTimeFormatter fmt = DateTimeFormat.forPattern("d-MMM-Y");
        String formattedNow = fmt.print(date);

        getRota(formattedNow, mCarerID);


    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu items for use in the action bar
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.rotamenu, menu);
        return super.onCreateOptionsMenu(menu);
    }




    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {


        CarerPurposeOfCallFragment test = (CarerPurposeOfCallFragment) getFragmentManager().findFragmentById(R.id.carerpurposeofcallfragment_container);
        if (test != null && test.isVisible()) {

            Log.e(TAG, "CarerPurposeOfCallFragment is visible");


            FragmentTransaction transaction = getFragmentManager().beginTransaction();

            // Replace whatever is in the fragment_container view with this fragment,
            // and add the transaction to the back stack
            transaction.remove(test);
            //transaction.addToBackStack(null);

            // Commit the transaction
            transaction.commit();
        }




        switch (item.getItemId()) {

        case R.id.previous:

             Log.e(TAG, "previous clicked");

            if(now != null){

            now = now.minusDays(1);

            DateTimeFormatter fmt = DateTimeFormat.forPattern("d-MMM-Y");
            String formattedNow = fmt.print(now);

            getRota(formattedNow, mCarerID);

            }else{
                Log.e(TAG, "now is null");
            }

            return true;


        case R.id.next:

             Log.e(TAG, "next clicked");

            if(now != null){
            now = now.plusDays(1);

            DateTimeFormatter fmt2 = DateTimeFormat.forPattern("d-MMM-Y");
            String formattedNow2 = fmt2.print(now);

            getRota(formattedNow2, mCarerID);
            }else{
                Log.e(TAG, "now is null");
            }

            return true;


        case R.id.pickaday:

             Log.e(TAG, "pickday clicked");

             if(mCarerID != null){

            loadDatePicker();
             }

            return true;

        case R.id.updatecall2:

            Log.e(TAG, "update call  clicked");

            if(mCarerID != null){

            ContentValues cv = ((CarerDetailsFragment) getFragmentManager().findFragmentById(R.id.carerdetailsinfofragment_container)).getCallParams();

             callStartTime = cv.getAsString("callstarttime");
             callDuration = cv.getAsString("callduration");
             callID = cv.getAsString("callid");

             if(callStartTime == null || callDuration == null || callID == null){


                 AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);

                    // set title
                    alertDialogBuilder.setTitle("No Call Selected!");

                    // set dialog message
                    alertDialogBuilder
                            .setMessage(
                                    "Please Select a call from the rota to update." )
                            .setCancelable(false)
                            .setPositiveButton("OK",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int id) {


                                        }
                                    });

                    // create alert dialog
                    AlertDialog alertDialog = alertDialogBuilder.create();

                    // show it
                    alertDialog.show();




             }else{

             CarerListFragment carerListFrag = (CarerListFragment) getFragmentManager().findFragmentById(R.id.carerlist);

                if (carerListFrag != null && carerListFrag.isVisible()) {

                    DateTimeFormatter fmt = DateTimeFormat.forPattern("d-MMM-Y");
                    String date = fmt.print(now);

                Intent updateCall = new Intent(this, UpdateCallDateTimeAndCarerActivity.class);
                updateCall.putExtra("callstarttime", callStartTime);
                updateCall.putExtra("callid", callID);
                updateCall.putExtra("callduration", callDuration);
                updateCall.putExtra("carerid", mCarerID);
                updateCall.putExtra("rotadate", date);


                startActivity(updateCall);

                }else{

                    Log.e(TAG, "must be on a phone!");

                    DateTimeFormatter fmt = DateTimeFormat.forPattern("d-MMM-Y");
                    String date = fmt.print(now);

                    Intent updateCallOnPhone = new Intent(this, UpdateCallDateTimeActivity.class);
                    updateCallOnPhone.putExtra("callstarttime", callStartTime);
                    updateCallOnPhone.putExtra("callid", callID);
                    updateCallOnPhone.putExtra("callduration", callDuration);
                    updateCallOnPhone.putExtra("carerid", mCarerID);
                    updateCallOnPhone.putExtra("rotadate", date);

                    startActivity(updateCallOnPhone);

                }


             }



            }else{

                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);

                // set title
                alertDialogBuilder.setTitle("No Carer Selected!");

                // set dialog message
                alertDialogBuilder
                        .setMessage(
                                "Please Select a carer from the carer list." )
                        .setCancelable(false)
                        .setPositiveButton("OK",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {


                                    }
                                });

                // create alert dialog
                AlertDialog alertDialog = alertDialogBuilder.create();

                // show it
                alertDialog.show();

            }

            return true;





        }

        return super.onMenuItemSelected(featureId, item);
    }

    @Override
     public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);

        CarerDetailsFragment test2 = (CarerDetailsFragment) getFragmentManager().findFragmentById(R.id.carerdetailsinfofragment_container);
        if (test2 == null  ) {

            Log.e(TAG, "CarerDetailsFragment = not visible");

         menu.getItem(0).setVisible(false);
         menu.getItem(1).setVisible(false);
         menu.getItem(2).setVisible(false);

    }else{
        Log.e(TAG, "CarerDetailsFragment = visible");
        menu.getItem(0).setVisible(true);
        menu.getItem(1).setVisible(true);
        menu.getItem(2).setVisible(true);
    }

    // add your conditions here and change 0 with the R.id.moredetails item postion.
        CarerPurposeOfCallFragment test = (CarerPurposeOfCallFragment) getFragmentManager().findFragmentById(R.id.carerpurposeofcallfragment_container);
        if (test == null || ! test.isVisible()) {

         menu.getItem(3).setVisible(false);

    }else{

        menu.getItem(3).setVisible(true);
    }




    return true;

    }//end of onPrepareOptionsMenu


}//end of class
Was it helpful?

Solution

SOLVED

instead of calling invalidateOptionsMenu from onPostExecute in the activity, i call

getActivity().invalidateOptionsMenu();

In Fragment class I placed it inside onActivityCreated();

works fine now.

Matt

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top