ProgressDialog未显示在片段中

时间:2014-11-14 12:06:06

标签: android android-fragments android-asynctask progressdialog

我有以下课程:

...

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;
            //}
        }

    }
    ....

}

目标是在执行AsyncTask时显示一个Dialog(ProgressDialog),以便Dialog保持在UI前面片刻,然后,地图(之前显示)返回到前面。更确切地说,您启动应用程序(家庭活动),打开左侧抽屉,按Mapa并转到当前片段。显示空地图。您打开右侧抽屉并按下按钮。之后,执行启动AsyncTask的过程(以及我想要的ProgressDialog)。

我不知道为什么,但ProgressDialog没有被展示,但我已经意识到&#34;睡眠&#34;进程正常(每次都正确执行AsyncTask)。

任何人都可以伸出援助之手吗?

PS:我的主要活动(HomeActivity)启动片段。主要活动有两个抽屉:左抽屉始终可见,右抽屉只有在启动FragmentMapa时才能看到(我现在正在向您显示片段)。这个问题可能是由于抽屉行为造成的吗?

非常感谢你

1 个答案:

答案 0 :(得分:0)

解决。如果遇到此问题,请查看以下帖子:https://stackoverflow.com/a/3291713/828551

您必须创建一个接口,在AsyncTask中创建它的实例,并实现启动AsyncTask的主类接口。