Android对话框无法正常显示

时间:2014-07-07 16:02:29

标签: java android android-asynctask progressdialog

以下代码将应用程序与API连接并从那里检索数据,它运行正常,唯一的问题是对话框消失得太快,它必须在同步进行时显示然后消失。

/**
 * 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);


    }

}

1 个答案:

答案 0 :(得分:1)

你应该在onPreExecute方法上调用对话框,这样就会在UI线程上执行对话框,如下所示:

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

来自Android AsyncTask documentation:

这4个步骤 执行异步任务时,任务将执行4个步骤:

  • onPreExecute()

,在执行任务之前在UI线程上调用。此步骤通常用于设置任务,例如通过在用户界面中显示进度条。

  • doInBackground(参数...)

,在onPreExecute()完成执行后立即在后台线程上调用。此步骤用于执行可能需要很长时间的后台计算。异步任务的参数将传递给此步骤。计算结果必须由此步骤返回,并将传递回最后一步。此步骤还可以使用publishProgress(Progress ...)发布一个或多个进度单元。这些值发布在UI线程的onProgressUpdate(Progress ...)步骤中。

  • onProgressUpdate(进步...)

,在调用publishProgress(Progress ...)后在UI线程上调用。执行的时间是不确定的。此方法用于在后台计算仍在执行时显示用户界面中的任何形式的进度。例如,它可用于为进度条设置动画或在文本字段中显示日志。

  • onPostExecute(结果)

,在后台计算完成后在UI线程上调用。后台计算的结果作为参数传递给此步骤。