joninx
joninx

Reputation: 1780

ProgressDialog not showing up within a Fragment

I have the following class:

...

public class FragmentMapa extends Fragment {

    /*
     * Atributos
     */
    private static String LOG_TAG = "FragmentMapa";

    private HomeActivity homeActivity;
    private GoogleMap mMapa;

    private DrawerLayout mDrawer;
    private ActionBarDrawerToggle mDrawerToggle;
    private ListView mDrawerList;
    private ListView mDrawerRightList;
    private RelativeLayout mDrawerRelativeLayout;
    private String[] mRightDrawerMenuTitles;
    private ImageView mDiputacionLogo;

    private IncidenciasFetchAsyncTask mFetchIncidenciasTask;
    private Incidencias mIs;
    private CamarasFetchAsyncTask mFetchCamarasTask;
    private Camaras mCams;
    private ViabilidadesInvernalesFetchAsyncTask mFetchViabilidadesInvernalesTask;
    private ViabilidadesInvernales mVis;

    private static LatLng POS_CENTRAL = new LatLng(43.243968,-2.896957);
    private static LatLng limiteSurOesteBizkaia = new LatLng(42.895853,-3.594589);
    private static LatLng limiteNorEsteBizkaia = new LatLng(43.540351,-2.180099);
    private static final LatLngBounds BOUNDS = new LatLngBounds(limiteSurOesteBizkaia, limiteNorEsteBizkaia);

    private ArrayList<Marker> markersIncidencias = new ArrayList<Marker>();
    private ArrayList<Marker> markersObras = new ArrayList<Marker>();
    private ArrayList<Marker> markersCamaras = new ArrayList<Marker>();
    private ArrayList<Marker> markersViabilidadInvernal = new ArrayList<Marker>();

    /*
     * Métodos
     */

    public FragmentMapa() {

    }

    @Override
    public void onAttach (Activity activity) {
        super.onAttach(activity);
        homeActivity = (HomeActivity) activity;

        mRightDrawerMenuTitles = getResources().getStringArray(R.array.mapa_submenu_options);

        mDrawer = homeActivity.getmDrawer();
        mDrawerRightList = homeActivity.getmDrawerRightList();
        mDrawerRightList.setAdapter(new ArrayAdapter<String>(
                homeActivity.getSupportActionBar().getThemedContext(), 
                R.layout.rightdrawer_map_list_item,
                mRightDrawerMenuTitles
                ));

        mDrawerRightList.setOnItemClickListener(new DrawerItemClickListener());
    }

    @Override
    public void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


    }

    @Override
    public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.mapa, container, false);

        setupMapIfNeeded();

        return rootView;

    }

    private void setupMapIfNeeded() {

        if( mMapa == null ){
            SupportMapFragment smf = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapaPrincipal);

            if( smf != null ){
                //Toast.makeText(getActivity(), "VAAAMOOSS", Toast.LENGTH_SHORT).show();
                mMapa = smf.getMap();
            }/*else{
                Toast.makeText(getActivity(), "smf es null...", Toast.LENGTH_SHORT).show();
            }*/

            if( mMapa != null ){

                setupMap();

            }

        }

    }

    private void setupMap() {

        //Toast.makeText(getActivity(), "A configurar el mapa!!", Toast.LENGTH_SHORT).show();

        CameraPosition camPos;
        camPos = new CameraPosition.Builder()
        .target(POS_CENTRAL) 
        .zoom((float) 9.5)
        .build();

        final CameraUpdate camUpd =
                CameraUpdateFactory.newCameraPosition(camPos);

        mMapa.animateCamera(camUpd);
        mMapa.setOnCameraChangeListener(new OnCameraChangeListener() {

            @Override
            public void onCameraChange(CameraPosition newPos) {

                float maxZoom = 17.0f;

                if( !BOUNDS.contains(newPos.target) ){
                    //Mover la cámara al centro si se 
                    //va más allá de los límites

                    mMapa.animateCamera(camUpd);
                }

                if(newPos.zoom > maxZoom){
                    mMapa.animateCamera(CameraUpdateFactory.zoomTo(maxZoom));
                }

            }
        });

        mMapa.setOnInfoWindowClickListener( new OnInfoWindowClickListener(){

            public void onInfoWindowClick(Marker aMarker) {

                Toast.makeText(getActivity(), "info window pulsado", Toast.LENGTH_SHORT).show();
                if( markersCamaras.contains(aMarker) ){

                    Camara c = mCams.getCamaraByCoord(aMarker.getPosition());

                    homeActivity.showCameraFragment(c);

                }
            }

        });

    }

    @Override
    public void onActivityCreated (Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

    }

    @Override
    public void onViewStateRestored (Bundle savedInstanceState) {
        super.onViewStateRestored(savedInstanceState);

    }

    @Override
    public void onStart () {
        super.onStart();

    }

    @Override
    public void onResume () {
        super.onResume();

    }

    @Override
    public void onPause () {
        super.onPause();
    }

    @Override
    public void onStop () {
        super.onStop();
    }

    @Override
    public void onDestroyView () {
        super.onDestroyView();
    }

    @Override
    public void onDestroy () {
        super.onDestroy();
    }

    @Override
    public void onDetach () {
        super.onDetach();
    }

    /* The click listener for ListView in the navigation drawer */
    private class DrawerItemClickListener implements OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            final int thePos = position;
            mDrawer.setDrawerListener( new DrawerLayout.SimpleDrawerListener(){

                @Override
                public void onDrawerClosed(View drawerView) {

                    boolean wasChecked = !mDrawerRightList.isItemChecked(thePos);

                    //Toast.makeText(homeActivity, "Item pulsado: " + wasChecked, Toast.LENGTH_SHORT).show();
                    mDrawerRightList.setItemChecked(thePos, !wasChecked);

                    switch (thePos) {
                        case 0:
                            //Incidencias
                            //Toast.makeText(homeActivity, "Incidencias", Toast.LENGTH_SHORT).show();

                            if(!wasChecked){
                                //Toast.makeText(homeActivity, "Incidencias estaba sin pulsar", Toast.LENGTH_SHORT).show();

                                getIncidenciasObras();
                                introducirIncidencias();
                            }else{
                                //Toast.makeText(homeActivity, "Incidencias estaba pulsado", Toast.LENGTH_SHORT).show();
                                removeIncidenciasMarkers();
                            }

                            break;

                        case 1:
                            //Obras
                            //Toast.makeText(homeActivity, "Obras", Toast.LENGTH_SHORT).show();

                            if(!wasChecked){
                                //Toast.makeText(homeActivity, "Obras estaba sin pulsar", Toast.LENGTH_SHORT).show();
                                getIncidenciasObras();
                                introducirObras();
                            }else{
                                //Toast.makeText(homeActivity, "Obras estaba pulsado", Toast.LENGTH_SHORT).show();
                                removeObrasMarkers();
                            }

                            break;  

                        case 2:
                            //Cámaras
                            //Toast.makeText(homeActivity, "Cámaras", Toast.LENGTH_SHORT).show();

                            if(!wasChecked) {
                                getCamaras();
                                introducirCamaras();
                            }else
                                removeCamarasMarkers();
                            break;

                        case 3:
                            //Viabilidad invernal
                            //Toast.makeText(homeActivity, "Viabilidad invernal", Toast.LENGTH_SHORT).show();

                            if(!wasChecked){
                                getViabilidadesInvernales();
                                introducirViabilidadInvernal();
                            }else
                                removeViabilidadInvernalMarkers();
                            break;

                        default:
                            //Toast.makeText(homeActivity, "Default", Toast.LENGTH_SHORT).show();
                            break;

                    }

                }

            });

            if(mDrawer.isDrawerOpen(Gravity.END))
                mDrawer.closeDrawer(mDrawerRightList);
        }
    }

    private void getViabilidadesInvernales(){
        mVis = ViabilidadesInvernales.getInstance();
        if(mVis.isEmptyViabilidadesInvernales()){
            mFetchViabilidadesInvernalesTask = new ViabilidadesInvernalesFetchAsyncTask(homeActivity);
            try {
                mVis = mFetchViabilidadesInvernalesTask.execute("es").get();
            } catch (InterruptedException e) {
                Log.e(LOG_TAG, "Error InterruptedException: " + e.getMessage());
                e.printStackTrace();
            } catch (ExecutionException e) {
                Log.e(LOG_TAG, "Error ExecutionException: " + e.getMessage());
                e.printStackTrace();
            }
        }

    }

    ...

    private void introducirViabilidadInvernal() {

        if(markersViabilidadInvernal.isEmpty()){
            Marker aMarker;

            for (ViabilidadInvernal vi : mVis.getViabilidades()) {

                String estado = "";
                BitmapDescriptor icon;
                if(vi.getEstado() == PuertoEstado.ABIERTO){
                    estado = getResources().getString(R.string.mapa_puerto_abierto);
                    icon = BitmapDescriptorFactory.fromResource(R.drawable.marker_puertoabierto);
                }else{
                    //vi.getEstado() == PuertoEstado.CERRADO
                    estado = getResources().getString(R.string.mapa_puerto_cerrado);
                    icon = BitmapDescriptorFactory.fromResource(R.drawable.marker_puertocerrado);
                }

                aMarker = mMapa.addMarker(new MarkerOptions()
                .position(vi.getCoord())
                .title(vi.getT())
                .snippet(estado)
                .icon(icon));

                markersViabilidadInvernal.add(aMarker);

            }

        }

    }


    private void removeViabilidadInvernalMarkers() {

        for(Marker aMarker : markersViabilidadInvernal){
            aMarker.remove();
        }

    }

    ...

    private class ViabilidadesInvernalesFetchAsyncTask extends AsyncTask<String, Void, ViabilidadesInvernales>{

        private ProgressDialog mPd;
        private HomeActivity ownerActivity;
        private Context context;
        private Exception exceptionToBeThrown;

        public ViabilidadesInvernalesFetchAsyncTask(Activity activity){
            this.ownerActivity = (HomeActivity) activity;
            context = activity;
            this.exceptionToBeThrown = null;
            mPd = new ProgressDialog(context);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mPd.setTitle("cargando");
            mPd.setMessage("miralo");
            //mPd.setTitle(getResources().getString(R.string.mapa_cargando_titulo));
            //mPd.setMessage(getResources().getString(R.string.mapa_cargando, getResources().getString(R.string.mapa_cargando_elemento_viabilidad)));
            mPd.setCancelable(false);
            mPd.setIndeterminate(true);
            mPd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            mPd.show();

        }

        @Override
        protected ViabilidadesInvernales doInBackground(String... params) {
            String idioma = params[0];
            if(!idioma.equalsIgnoreCase("es") && !idioma.equalsIgnoreCase("eu")){
                idioma = "es";
            }
            SystemClock.sleep(5000);
            ViabilidadesInvernalesParser vip = new ViabilidadesInvernalesParser();
            ViabilidadesInvernales lasViabilidades = vip.parse(idioma);

            Log.d(LOG_TAG, lasViabilidades.toString());

            ViabilidadesInvernales vis = ViabilidadesInvernales.getInstance();

            return vis;

        }

        @Override
        protected void onPostExecute(ViabilidadesInvernales vis) {
            super.onPostExecute(vis);
            mVis = vis;

            if(mPd != null){
                mPd.dismiss();
            }

            // Check if exception exists.
            //if (exceptionToBeThrown != null) {
                //TODO
                //ownerActivity.handleXXX();
                //throw exceptionToBeThrown;
            //}
        }

    }
    ....

}

The aim is to show a Dialog (ProgressDialog) when an AsyncTask is executed, so that the Dialog remains in front of the UI for a moment and then, the map (which was being shown previously) returns to the front. More exactly, you launch the application (home activity), you open the left drawer, press Mapa and go to the current fragment. An empty map is shown. You open the right drawer and press a button. Just afterwards, the process of launching AsyncTask is executed (and my desired ProgressDialog).

I don't know why, but the ProgressDialog is not being shown, but I have realised that the "sleep" process is ok (and the AsyncTask is executed properly every time).

Can anybody lend me a hand?

PS: My main activity (HomeActivity) launches fragments. The main activity has two drawers: left drawer is always visible, and right drawer is only visible when launching the FragmentMapa (the fragment I'm showing you right now). Might this issue be due to the Drawer behaviour?

THANK YOU SO MUCH

Upvotes: 3

Views: 3856

Answers (1)

joninx
joninx

Reputation: 1780

SOLVED. Anyone who faces this problem, check the following post: https://stackoverflow.com/a/3291713/828551.

You must create an interface, create an instance of it within the AsyncTask and implement the interface the main class where you launch the AsyncTask.

Upvotes: 1

Related Questions