Tengo una clase que utiliza una asyntask para guardar datos en una base de datos, funciona todo bien, hasta el momento donde quiero agregar un progressdialog para la espera de la inserción en la base de datos, les dejo mi codigo actual, espero puedan ayudarme
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;
}
}
este es el logcat con el error que tengo
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)
a mi parecer creo que es por que algún método en el doInBackgrounds, tiene algo que modifica la actividad y hace que se pierda el context de la aplicación.