progress dialog in asyntask

1

I have a class that uses an asyntask to store data in a database, everything works fine, until the moment where I want to add a progressdialog to wait for the insertion in the database, I leave my current code, I hope can you help me?

public class RegisterShopPageActivity extends AppCompatActivity {

    EditText nombre, contraseña, email, cumple, comuna;
    String un, pass, db, ip;
    TextView boton;
    FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;
    Connection con;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        getSupportActionBar().hide();
        setContentView(R.layout.activity_register_shop);

        nombre = (EditText) findViewById(R.id.nombreR);
        contraseña = (EditText) findViewById(R.id.passR);
        email = (EditText) findViewById(R.id.mailR);
        cumple = (EditText) findViewById(R.id.cumpleR);
        comuna = (EditText) findViewById(R.id.viveR);
        boton = (TextView) findViewById(R.id.activity_register_shop_submit);
        ip = getResources().getString(R.string.host);
        db = getResources().getString(R.string.db);
        un = getResources().getString(R.string.user);
        pass = getResources().getString(R.string.pass);


        boton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                RegisterShopPageActivity.CheckLogin checkLogin = new RegisterShopPageActivity.CheckLogin();
                checkLogin.execute("");
            }
        });

        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user= FirebaseAuth.getInstance().getCurrentUser();
            }
        };

    }

    @Override
    protected void onStart() {
        super.onStart();
    }

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

    public class CheckLogin extends AsyncTask<String,String,String> {
        String z = "";
        String mail = email.getText().toString().trim();
        String password = contraseña.getText().toString().trim();
        String nombreUser = nombre.getText().toString().trim();
        String nacimiento=cumple.getText().toString().trim();
        String vive=comuna.getText().toString().trim();
        private ProgressDialog dialog;

        @Override
        protected void onPreExecute() {
            dialog = ProgressDialog.show(RegisterShopPageActivity.this, "Creando Usuario","Por favor espera", true);
        }

        @Override
        protected void onPostExecute(String r) {
            if (dialog.isShowing()) {
                dialog.dismiss();
            }

            if(z.equals("Debes completar los 3 campos solicitados")){
                TastyToast.makeText(RegisterShopPageActivity.this,z, TastyToast.LENGTH_LONG, TastyToast.ERROR).show();
            }else if (z.equals("Inserta un nombe valido")){
                TastyToast.makeText(RegisterShopPageActivity.this, z, TastyToast.LENGTH_LONG, TastyToast.ERROR).show();
            }else if(r.trim().contains("The email address is already in use by another account.".trim())){
                TastyToast.makeText(RegisterShopPageActivity.this,"El email ya esta en uso", TastyToast.LENGTH_LONG, TastyToast.INFO).show();
            }else if (r.trim().contains("The email address is badly formatted".trim())){
                TastyToast.makeText(RegisterShopPageActivity.this,"Formato de correo invalido" , TastyToast.LENGTH_LONG, TastyToast.INFO).show();
            }else if(r.trim().contains("An internal error has occurred. [ WEAK_PASSWORD  ]".trim())){
                TastyToast.makeText(RegisterShopPageActivity.this,"La contraseña es muuy debil", TastyToast.LENGTH_LONG, TastyToast.INFO).show();
            }else if(r.trim().contains("A network error (such as timeout, interrupted connection or unreachable host) has occurred.".trim())){
                TastyToast.makeText(RegisterShopPageActivity.this,"Conexión a internet perdida", TastyToast.LENGTH_LONG, TastyToast.ERROR).show();
            } else if(z.equals("funciono")){
                email.setText("");
                contraseña.setText("");
                nombre.setText("");
                cumple.setText("");
                comuna.setText("");
                TastyToast.makeText(RegisterShopPageActivity.this,"Usuario creado con exito, por favor verifique su direccion de correo electronico", TastyToast.LENGTH_LONG, TastyToast.SUCCESS).show();
            }
        }
        @Override
        protected String doInBackground(String... params) {
            if (mail.equals("") && password.equals("") && nombreUser.equals("") && nacimiento.equals("") && vive.equals("")) {
                z = "Debes completar los campos solicitados";
            }
            if (nombreUser.length() < 1) {
                z = "El nombre debe tener al menos 10 caracteres";
            }else if(mail.equals("") || password.equals("") || nombreUser.equals("") || nacimiento.equals("") || vive.equals("")){
                z = "Debes completar los 3 campos solicitados";
            }else {
                mAuth.createUserWithEmailAndPassword(mail, password)
                        .addOnCompleteListener(RegisterShopPageActivity.this, new OnCompleteListener<AuthResult>() {
                            @Override
                            public void onComplete(@NonNull Task<AuthResult> task) {
                                if (task.isSuccessful()) {
                                    Log.d("funciona", "pase por aqui");
                                    try {
                                        con = connectionclass(un, pass, db, ip);
                                        if (con == null) {
                                        } else {
                                            try {
                                                String pass = AESCrypt.encrypt("encryp", password);
                                                String query = "insert Into usuarios values('"+nombreUser+"','"+mail+"','"+pass+"',((SELECT CONVERT (date, SYSDATETIME()))),'"+vive+"','"+nacimiento+"');";
                                                PreparedStatement preparedStatement = con.prepareStatement(query);
                                                preparedStatement.setQueryTimeout(2);
                                                preparedStatement.executeUpdate();
                                                con.close();
                                                Uri imageUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE +
                                                        "://" + getResources().getResourcePackageName(R.drawable.perfilvacio)
                                                        + '/' + getResources().getResourceTypeName(R.drawable.perfilvacio) + '/' + getResources().getResourceEntryName(R.drawable.perfilvacio));

                                                final FirebaseUser update = FirebaseAuth.getInstance().getCurrentUser();

                                                UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
                                                        .setDisplayName(nombreUser)
                                                        .setPhotoUri(imageUri)
                                                        .build();

                                                update.updateProfile(profileUpdates).addOnCompleteListener(new OnCompleteListener<Void>() {
                                                    @Override
                                                    public void onComplete(@NonNull Task<Void> task) {
                                                        if (task.isSuccessful()) {
                                                            update.sendEmailVerification();
                                                            TastyToast.makeText(getApplicationContext(),"Verifica tu dirección de email",TastyToast.LENGTH_LONG,TastyToast.INFO).show();
                                                            FirebaseAuth.getInstance().signOut();
                                                        } else {
                                                            FirebaseAuth.getInstance().signOut();
                                                        }
                                                    }
                                                });
                                            } catch (GeneralSecurityException e) {
                                                Log.d("error de encriptacion", e.getMessage());
                                            }
                                        }
                                    } catch (Exception ex) {
                                        Log.d("error base de datos: ", ex.getMessage());
                                    }
                                }else if(!task.isSuccessful()){
                                    Exception e=task.getException();
                                    try {
                                        throw e;
                                    } catch (Throwable throwable) {
                                        onPostExecute(e.getMessage());
                                    }
                                    Log.d("no funciono",e.getMessage());
                                }
                            }
                        });
                z = "funciono";
            }
            return z;
        }
    }

    @SuppressLint("NewApi")
    public Connection connectionclass(String user, String password, String database, String server)
    {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        Connection connection = null;
        String ConnectionURL = null;
        try
        {
            Class.forName("net.sourceforge.jtds.jdbc.Driver");
            ConnectionURL = "jdbc:jtds:sqlserver://" + server +"/"+ database + ";user=" + user+ ";password=" + password + ";";
            DriverManager.setLoginTimeout(2);
            connection = DriverManager.getConnection(ConnectionURL);
        }
        catch (SQLException se)
        {
            Log.e("error here 1 : ", se.getMessage());
        }
        catch (ClassNotFoundException e)
        {
            Log.e("error here 2 : ", e.getMessage());
        }
        catch (Exception e)
        {
            Log.e("error here 3 : ", e.getMessage());
        }
        return connection;
    }
}

this is the logcat with the error I have

05-28 21:29:10.080 25416-25416/com.ciclomapp.ciclomapp.ciclomapp E/WindowManager: android.view.WindowLeaked: Activity com.ciclomapp.ciclomapp.ciclomapp.RegisterShopPageActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{19cb5c08 V.E..... R......D 0,0-575,250} that was originally added here
                                                                                      at android.view.ViewRootImpl.<init>(ViewRootImpl.java:367)
                                                                                      at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:271)
                                                                                      at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
                                                                                      at android.app.Dialog.show(Dialog.java:306)
                                                                                      at android.app.ProgressDialog.show(ProgressDialog.java:116)
                                                                                      at android.app.ProgressDialog.show(ProgressDialog.java:99)
                                                                                      at com.ciclomapp.ciclomapp.ciclomapp.RegisterShopPageActivity$CheckLogin$override.onPreExecute(RegisterShopPageActivity.java:101)
                                                                                      at com.ciclomapp.ciclomapp.ciclomapp.RegisterShopPageActivity$CheckLogin$override.access$dispatch(RegisterShopPageActivity.java)
                                                                                      at com.ciclomapp.ciclomapp.ciclomapp.RegisterShopPageActivity$CheckLogin.onPreExecute(RegisterShopPageActivity.java:0)
                                                                                      at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:591)
                                                                                      at android.os.AsyncTask.execute(AsyncTask.java:539)
                                                                                      at com.ciclomapp.ciclomapp.ciclomapp.RegisterShopPageActivity$1.onClick(RegisterShopPageActivity.java:67)
                                                                                      at android.view.View.performClick(View.java:4856)
                                                                                      at android.view.View$PerformClick.run(View.java:19956)
                                                                                      at android.os.Handler.handleCallback(Handler.java:739)
                                                                                      at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                      at android.os.Looper.loop(Looper.java:211)
                                                                                      at android.app.ActivityThread.main(ActivityThread.java:5371)
                                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                                      at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:945)
                                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:740)

In my opinion, I think it's because some method in the doInBackgrounds has something that modifies the activity and makes the context of the application lose.

    
asked by zhet 29.05.2017 в 02:58
source

2 answers

0

Try what this tutorial explains

You must pass to asyntask the reference of the activity with WeakReference

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new MyAsyncTask(this).execute();
    }
    private static class MyAsyncTask extends AsyncTask {

        private WeakReference<MainActivity> mainActivity;    

        public MyAsyncTask(MainActivity mainActivity) {   
            this.mainActivity = new WeakReference<>(mainActivity);            
        }
        @Override
        protected Object doInBackground(Object[] params) {
            return doSomeStuff();
        }
        private Object doSomeStuff() {
            //do something to get result
            return new Object();
        }
        @Override
        protected void onPostExecute(Object object) {
            super.onPostExecute(object);
            if (mainActivity.get() != null){
                //accede a los componentes de mainactivity
            }
        }
    }
}

Another solution is to use observables here the tutorial

It can also be that when the activity is closed and the background task continues and at the end, it does not find the reference of the dialogue:

@Override
public void onDestroy(){
    super.onDestroy();
    if ( progressDialog!=null && progressDialog.isShowing() ){
        progressDialog.cancel();
    }
}
    
answered by 29.05.2017 в 12:21
0

I do it in the following way. I declare the ProgressDialog as an attribute of the main class, in this case within RegisterShopPageActivity. I initialize it and show it in the OnPreExecute method of the Asynktask and I close it in the postExecute, similar to what you do but not the same.

public class RegisterShopPageActivity extends AppCompatActivity {
    ProgressDialog dialog;
    ...

    public class CheckLogin extends AsyncTask<String,String,String> {

        @Override
        protected void onPreExecute() {
            dialog = new ProgressDialog(RegisterShopPageActivity.this);
            dialog.setMessage("Espere...");
            dialog.setIndeterminate(true);  //Las propiedades que quieras
            dialog.setCancelable(false);    //Las propiedades que quieras
            dialog.show();
        }

        @Override
        protected String doInBackground(String... urls) {...}

        @Override
        protected void onPostExecute(String result) {
            ...
            dialog.dismiss();
        }

    }
}

If you do this, the ProgressDialog is closed once you have finished the code you type in the method onPostExecute

    
answered by 30.05.2017 в 13:17