简体   繁体   中英

Android dialog box not showing properly

The following code connects the app with an API and retrieve the data from there, it is working perfectly, the only problem is that the dialog box disappear too fast, it had to show while the sync is in progress and then disappear.

/**
 * SYNC
 */

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import com.database.adapter.ClientesAdapter;
import com.model.ClienteModel;
import com.webservice.rest.ClientesRest;

import java.sql.SQLException;
import java.util.List;
public class SincronizarTask extends AsyncTask<Void, Void, Boolean> {

    private final ProgressDialog dialog;
    private Context ctx;
    private ProgressDialog mProgressDialog;

    public SincronizarTask(Activity activity) {

        ctx = activity;

        dialog = new ProgressDialog(ctx);


    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
     dialog.setCancelable(false);
    dialog.setIndeterminate(false);
    dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    dialog.setTitle("Sincronizando");
    dialog.setMessage("Aguarde...");
    dialog.show();
    }

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

        Log.i("RM", "doInBackground");

        try {
            ClientesRest mClientesRest = new ClientesRest(this.ctx);

            Log.i("RM", "doInBackground : P1");

            mClientesRest.getClientes(new ClientesRest.ClientesRestListener() {
                public void clientesReceived(List<ClienteModel> clientes) {
                    Log.i("RM", "doInBackground : P:2");
//                    Log.i("RM", String.valueOf(clientes));
                    Log.i("RM", "doInBackground : P:3");

                    ClientesAdapter mClientesAdapter = new ClientesAdapter(ctx);

                    for (int i = 0; i < clientes.size(); i++) {
                       System.out.println(clientes.get(i).get_nome());

                        /*
                        Verifica se o cliente existe no banco de dados local
                         */
                        Integer idClienteBdLocal = null;
                        try {
                            idClienteBdLocal = mClientesAdapter.consultaCadastroExistente(clientes.get(i).get_idrm());
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }

                        if(clientes.get(i).get_status() == "D"){

                            if(mClientesAdapter.getRegistro(idClienteBdLocal).get_status() != "D"){
                                try {
                                    mClientesAdapter.atualizar(new ClienteModel(idClienteBdLocal, clientes.get(i).get_idrm(), null, null, null, null, null, null, null, null, null, null, null, null, clientes.get(i).get_status()));
                                } catch (SQLException e) {
                                    e.printStackTrace();
                                }

                            }
                        }



                        if (idClienteBdLocal != 0)
                            {
                                /*Atualiza o banco de dados local*/
                                try {
                                    mClientesAdapter.atualizar(new ClienteModel(local, clientes.get(i).get_id(), clientes.get(i).get_name(), clientes.get(i).get_t(), clientes.get(i).get_add(), clientes.get(i).get_nu(), null, clientes.get(i).get_bb(), clientes.get(i).get_ba(), clientes.get(i).get_ci(), clientes.get(i).get_es(), null, clientes.get(i).get_cr(), clientes.get(i).get_mod(), clientes.get(i).get_st()));
                                } catch (SQLException e) {
                                    e.printStackTrace();
                                }
                            }else {
                                /*Cria registro no banco de dados local*/
                                try {
                                    mClientesAdapter.adicionar(new ClienteModel(clientes.get(i).get_idrm(), clientes.get(i).get_nome(), clientes.get(i).get_tipo(), clientes.get(i).get_endereco(), clientes.get(i).get_numero(), null, clientes.get(i).get_cep(), clientes.get(i).get_bairro(), clientes.get(i).get_cidade(), clientes.get(i).get_estado(), null, clientes.get(i).get_criado(), clientes.get(i).get_modificado(), clientes.get(i).get_status()));
                                } catch (SQLException e) {
                                    e.printStackTrace();
                                }
                            }

                    }

                }

            });


        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;

    }

    @Override
    protected void onPostExecute(final Boolean success) {
        if (dialog.isShowing()) {
        dialog.dismiss();
    }
    }

    @Override
    protected void onCancelled() {
        dialog.dismiss();
    }

}

MainActivity:

public class MainActivity extends SherlockFragmentActivity {

    private ActionBar barra;
    private ViewPager mViewPager;
    private TabsAdapter mTabsAdapter;

    private Preferencias mPreferencias;

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


        /* Verifica se tem uma sessão */
        mPreferencias = new Preferencias(getApplicationContext());
        Toast.makeText(getApplicationContext(), mPreferencias.getRmSessionEmail(), Toast.LENGTH_SHORT).show();

        mViewPager = new ViewPager(this);
        mViewPager.setId(R.id.pager);
        setContentView(mViewPager);

        barra = getSupportActionBar();
        barra.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
//        barra.setDisplayShowHomeEnabled(false); /* retira a barra */
//        barra.setDisplayShowTitleEnabled(false); /* retira o texto da barra */

        mTabsAdapter = new TabsAdapter(this, mViewPager);
        mTabsAdapter.addTab(barra.newTab().setIcon(R.drawable.agenda).setText(" Agenda"), jbkbjk.class, null);
        mTabsAdapter.addTab(barra.newTab().setIcon(R.drawable.viagens).setText(" Viagens"), jnjn.class, null);
        mTabsAdapter.addTab(barra.newTab().setIcon(R.drawable.clientes).setText(" Clientes"), ki.class, null);
        mTabsAdapter.addTab(barra.newTab().setIcon(R.drawable.pedidos).setText(" Pedidos"), popo.class, null);


    }

    private static final int REFRESH = 1;
    private static final int SEARCH = 2;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getSupportMenuInflater();
        inflater.inflate(R.menu.activity_itemlist, menu);

        menu.add(0, REFRESH, 0, "Refresh")
                .setIcon(R.drawable.ic_action_view_as_grid)
                .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);


        menu.add(0, SEARCH, 0, "Search")
                .setIcon(R.drawable.ic_action_search)
                .setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case REFRESH:

                return true;
            case SEARCH:
                // Do search
                return true;
            case R.id.add_item:
                this.dispatchSync();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void dispatchSync(){

         /* dispara a sincronização dos dados */
        SincronizarTask mSincronizarTask = new SincronizarTask(this);
        mSincronizarTask.execute((Void) null);


    }

}

You should call the dialog on the onPreExecute method, that way the dialog box will be executed on the UI thread, like this:

@Override
protected void onPreExecute() {
    super.onPreExecute();
 if (!dialog.isShowing()) {
        dialog.show();
    }
}

From Android AsyncTask documentation:

The 4 steps When an asynchronous task is executed, the task goes through 4 steps:

  • onPreExecute()

, invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.

  • doInBackground(Params...)

, invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.

  • onProgressUpdate(Progress...)

, invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.

  • onPostExecute(Result)

, invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM