2016-04-15 13 views
0

Bitte helfen Sie, ich kann ProgressDialog nicht entlassen, wenn die synchronization.The Methode sincronizaahora das Verfahren vor für die Show ruft die progressdialog und das Verfahren actualizarDatosLocalesProductos das Verfahren vor ruft die progressdailog für abtun, aber es funktioniert nicht Arbeiten.kann nicht entlassen ProgressDialog

private void actualizarDatosLocalesProductos(JSONObject response, SyncResult syncResult) 
 
    { 
 
     JSONArray productos = null; 
 
     int j=3; 
 
     try 
 
     { 
 
      // Obtener array "productos" 
 
      productos = response.getJSONArray(Constantes.PRODUCTOS); 
 
     } catch (JSONException e) { 
 
      e.printStackTrace(); 
 
     } 
 
     // Parsear con Gson 
 
     Producto[] res = gson.fromJson(productos != null ? productos.toString() : null, Producto[].class); 
 
     List<Producto> data = Arrays.asList(res); 
 
     // Lista para recolección de operaciones pendientes 
 
     ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); 
 

 
     // Tabla hash para recibir las entradas entrantes 
 
     HashMap<String, Producto> expenseMap = new HashMap<String, Producto>(); 
 
     for (Producto e : data) { 
 
      expenseMap.put(e.idProducto, e); 
 
     } 
 

 
     // Consultar registros remotos actuales 
 
     Uri uri = ContractParaDatos.CONTENT_URI_PRODUCTO; 
 
     String select = ContractParaDatos.ColumnasProducto.ID_REMOTA + " IS NOT NULL"; 
 
     Cursor c = resolver.query(uri, PROJECTION_PRODUCTOS, select, null, null); 
 
     assert c != null; 
 
     Log.i(TAG, "Se encontraron " + c.getCount() + " registros locales."); 
 
     // Encontrar datos obsoletos 
 
     String id; 
 
     String nombre; 
 
     Double precio; 
 
     Double iva; 
 

 
     while (c.moveToNext()) 
 
     { 
 
      syncResult.stats.numEntries++; 
 
      id = c.getString(COLUMNA_ID_REMOTA); 
 
      nombre = c.getString(COLUMNA_PRODUCTO); 
 
      precio = c.getDouble(COLUMNA_PRECIO); 
 
      iva = c.getDouble(COLUMNA_IVA); 
 
      Producto match = expenseMap.get(id); 
 
      if (match != null) { 
 
       // Esta entrada existe, por lo que se remueve del mapeado 
 
       expenseMap.remove(id); 
 
       Uri existingUri = ContractParaDatos.CONTENT_URI_PRODUCTO.buildUpon().appendPath(id).build(); 
 
       // Comprobar si el producto necesita ser actualizado 
 
       boolean b = match.nombrePrd != null && !match.nombrePrd.equals(nombre); 
 
       boolean b1 = match.precioPrd != precio; 
 
       boolean b2 = match.IVA != iva; 
 

 
       if (b || b1 || b2) 
 
       { 
 
        Log.i(TAG, "Programando actualización de: " + existingUri); 
 
        ops.add(ContentProviderOperation.newUpdate(existingUri) 
 
          .withValue(ContractParaDatos.ColumnasProducto.PRODUCTO, match.nombrePrd) 
 
          .withValue(ContractParaDatos.ColumnasProducto.PRECIO, match.precioPrd) 
 
          .withValue(ContractParaDatos.ColumnasProducto.IVA, match.IVA) 
 
          .build()); 
 
        syncResult.stats.numUpdates++; 
 
       } else { 
 
        Log.i(TAG, "No hay acciones para este registro: " + existingUri); 
 
       } 
 
      } else { 
 
       // Debido a que la entrada no existe, es removida de la base de datos 
 
       Uri deleteUri = ContractParaDatos.CONTENT_URI_PRODUCTO.buildUpon() 
 
         .appendPath(id).build(); 
 
       Log.i(TAG, "Programando eliminación de: " + deleteUri); 
 
       ops.add(ContentProviderOperation.newDelete(deleteUri).build()); 
 
       syncResult.stats.numDeletes++; 
 
      } 
 
     } 
 
     c.close(); 
 
     // Insertar items resultantes 
 
     for (Producto e : expenseMap.values()) 
 
     { 
 
      Log.i(TAG, "Programando inserción de: " + e.idProducto); 
 
      ops.add(ContentProviderOperation.newInsert(ContractParaDatos.CONTENT_URI_PRODUCTO) 
 
        .withValue(ContractParaDatos.ColumnasProducto.ID_REMOTA, e.idProducto) 
 
        .withValue(ContractParaDatos.ColumnasProducto.PRODUCTO, e.nombrePrd) 
 
        .withValue(ContractParaDatos.ColumnasProducto.PRECIO, e.precioPrd) 
 
        .withValue(ContractParaDatos.ColumnasProducto.IVA, e.IVA) 
 
        .build()); 
 
      syncResult.stats.numInserts++; 
 
     } 
 

 
     if (syncResult.stats.numInserts > 0 || 
 
       syncResult.stats.numUpdates > 0 || 
 
       syncResult.stats.numDeletes > 0) { 
 
      Log.i(TAG, "Aplicando operaciones..."); 
 

 
      try 
 
      { 
 
       resolver.applyBatch(ContractParaDatos.AUTHORITY, ops); 
 
      } catch (RemoteException | OperationApplicationException e) { 
 
       e.printStackTrace(); 
 
      } 
 
      resolver.notifyChange(
 
        ContractParaDatos.CONTENT_URI_PRODUCTO, 
 
        null, 
 
        false); 
 
      Log.i(TAG, "Sincronización finalizada."); 
 
      Toast.makeText(context, "Termino", Toast.LENGTH_LONG).show();//<----------------------------------------------------- 
 

 

 
      //////////////////////////////////////////////////////77777 
 
      try { 
 
       pre(context, j); 
 
      } catch (IOException e) { 
 
       e.printStackTrace(); 
 
      } 
 

 
      //////////////////////////////////////////////////////// 
 

 
     } else { 
 
      Log.i(TAG, "No se requiere sincronización"); 
 
     } 
 
    }

public static void sincronizarAhora(Context context, boolean onlyUpload, boolean rutas) 
 
    { 
 
     int j=2; 
 
     Log.i(TAG, "Realizando petición de sincronización manual"); 
 
     Toast.makeText(context, "Cargando Datos", Toast.LENGTH_LONG).show();//<----------------------------------------------------- 
 
     try { 
 
      pre(context, j); 
 
     } catch (IOException e) { 
 
      e.printStackTrace(); 
 
     } 
 

 
     Bundle bundle = new Bundle(); 
 
     bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true); 
 
     bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); 
 
     bundle.putBoolean(ContractParaDatos.NUMERO_RUTA, rutas); 
 
     if (onlyUpload) 
 
      bundle.putBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD, true); 
 
     ContentResolver.requestSync(obtenerCuentaASincronizar(context), 
 
       context.getString(R.string.provider_authority), bundle); 
 
    }

public static void pre(Context context, int i) throws IllegalArgumentException, SecurityException, IllegalStateException, IOException 
 
    { 
 
     ProgressDialog mProgressDialog; 
 

 
     mProgressDialog = new ProgressDialog(context); 
 

 
     if (i==2) 
 
     { 
 
      mProgressDialog.setTitle("Cargando Anuncios"); 
 
      mProgressDialog.setMessage("Espere un momento..."); 
 
      mProgressDialog.show(); 
 
     } 
 
     else if (i==3 || mProgressDialog.isShowing()) 
 
     { 
 
      mProgressDialog.dismiss(); 
 
     } 
 
    }

Antwort

1

Warum Sie einen neuen Fortschritt Dialog zu schaffen in pre() Methode? Sollten Sie es nicht global deklarieren und dann überall einsetzen?

0

Try ProgressDialog in Ihrem Haupt-Thread/Aktivität wie @Yashasvi

private static ProgressDialog mProgressDialog; 

// Main thread/activity 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    mProgressDialog = new ProgressDialog(this); 
    mProgressDialog.setTitle("Cargando Anuncios"); 
    mProgressDialog.setMessage("Espere un momento..."); 

} 


public static void pre(Context context, int i) throws IllegalArgumentException, SecurityException, IllegalStateException, IOException 
{ 
    if (i==2) 
    { 
     mProgressDialog.show(); 
    } 
    else if (i==3 || mProgressDialog.isShowing()) 
    { 
     mProgressDialog.dismiss(); 
    } 
} 

Komplettlösung
import android.app.ProgressDialog; 
import android.content.Context; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 

import java.io.IOException; 

public class Main2Activity extends AppCompatActivity { 

    private static ProgressDialog mProgressDialog; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main2); 

     mProgressDialog = new ProgressDialog(this); 
     mProgressDialog.setTitle("Cargando Anuncios"); 
     mProgressDialog.setMessage("Espere un momento..."); 

     try { 
      pre(this, 2); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

    public static void pre(Context context, int i) throws IllegalArgumentException, SecurityException, IllegalStateException, IOException 
    { 
     if (i==2) 
     { 
      mProgressDialog.show(); 
     } 
     else if (i==3 || mProgressDialog.isShowing()) 
     { 
      mProgressDialog.dismiss(); 
     } 
    } 
} 
+0

Als ich es global in dem Verfahren vorge erklären() Ich habe einen Fehler mit der varierbar. Der Fehler ist Nicht-statisches Feld "mProgressDialog" kann nicht aus einem statischen Kontext referenziert werden. –

1
sagte zu instanziiert

Zuerst haben Sie Ihre progressDialog in Klassenbereich zu erklären, und instanziiert es nur ein Zeit, der folgende Code macht die ganze Arbeit für Sie. Sie können den Kontext Ihre Methode oder in der Klasse Konstruktor übergeben, wenn Sie aus Android-Komponente sind, die einen Kontext hat ...

public void showProgressDialog(String message) { 
     if (progressDialog != null && progressDialog.isShowing()){ 
      progressDialog.setMessage(message); 
     } else { 
      progressDialog = new ProgressDialog(context); 
      progressDialog.setCancelable(false); 
      progressDialog.setMessage(message); 
      try { 
       progressDialog.show(); 
      } catch (final IllegalArgumentException ignored) { 
       // java.lang.IllegalArgumentException: View not attached to window manager 
       // has leaked window 
      } 
     } 
    } 

public void dismissProgressDialog(){ 
     if (progressDialog != null && progressDialog.isShowing()){ 
      try { 
       progressDialog.dismiss(); 
      } catch (final IllegalArgumentException ignored) { 
       // java.lang.IllegalArgumentException: View not attached to window manager 
       // has leaked window 
      } 
      progressDialog = null; 
     } 
    } 
Verwandte Themen