package com.example.waoperations.Transference;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import java.text.DateFormat;
import java.util.Locale;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.waoperations.R;
import com.example.waoperations.Transference.TransferenceItemDetail;
import com.example.waoperations.Transference.TransferenceItemSummary;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.os.Vibrator;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import java.util.Locale;
import android.widget.SearchView;
import android.app.Activity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.widget.EditText;
import android.widget.ListView;

public class TransferenceItemSummary extends Activity {

	StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
	
    public String PO,USER,EMP,EMP2,BOD,BARCODE,ID,INVTID,LINENUM,CONFIG;
    public String Disponible = " ";
    public String transf = "";
    public String transf2 = "";
    public String FechaCreacionTransfer="";
	public String Articulo="";
	public String PedidoCompra="";
	public String Transfer="";
	public int INDEX;
	public double newtotaldisp=0;
     
    TextView mDisplay;
    View header;
    ArrayList<String> IDTransf = new ArrayList<String>();
    ArrayList<String> BodDest = new ArrayList<String>();
	ArrayList<String> InventLINENUMPO = new ArrayList<String>();
	ArrayList<String> InventTransid = new ArrayList<String>();
	ArrayList<String> LinenumidTR = new ArrayList<String>();
    TransferenceAdapter1 newTransferenceAdapter;
    private ProgressDialog progressDialog;
    private SwipeRefreshLayout swipeRefreshLayout;
    private TransferenceDataBaseHelper2 databaseHelper;
	private TransferenceDataBaseHelperPO databaseHelperPO;
	private CrossDockingDataBaseHelper databaseHelperCrsDck;

	public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        Typeface fontbold = Typeface.createFromAsset(this.getApplicationContext().getAssets(), "fonts/opensans-extrabold.ttf");
        
        setContentView(R.layout.transferlist_item);
        TextView HeaderName = (TextView) findViewById(R.id.tableroheader1);
    	
	    final ListView listView = (ListView)findViewById(R.id.transferenciaslistview1);
	    ActionBar actionBar = getActionBar();
	    actionBar.hide();

	    actionBar.setSubtitle("Transfer AC");
	    actionBar.setTitle("Warehouse");
	    actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.ForestGreen)));
	    actionBar.setDisplayShowTitleEnabled(false);
	    actionBar.setDisplayShowTitleEnabled(true);
	    actionBar.setDisplayHomeAsUpEnabled(false);
	    actionBar.show(); 

        HeaderName.setTypeface(fontbold);
	    listView.setAdapter(newTransferenceAdapter);
	    listView.setCacheColorHint(Color.TRANSPARENT);
	    listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
	    databaseHelper = new TransferenceDataBaseHelper2(this.getApplicationContext()); 
		databaseHelper.deleteAllData();

		databaseHelperPO = new TransferenceDataBaseHelperPO(this.getApplicationContext());
		databaseHelperPO.deleteAllData();

		databaseHelperCrsDck = new CrossDockingDataBaseHelper(this.getApplicationContext());
		databaseHelperCrsDck.deleteAllData();

		Intent intent = getIntent();
		this.PO=intent.getStringExtra("PO");
		this.EMP2=intent.getStringExtra("EMP2");
		this.BOD=intent.getStringExtra("BOD");
		this.USER=intent.getStringExtra("USER");
		this.BARCODE=intent.getStringExtra("BARCODE");
		HeaderName.setText("ARTÍCULO: " +PO);
    	HeaderName.setTextSize(25);
    	
 	    new LoadViewTask().execute();   
	
 	   newTransferenceAdapter = new TransferenceAdapter1(this.getApplicationContext(),databaseHelper.getTransferenciasLines(PO));
 	   listView.setAdapter(newTransferenceAdapter);
	  	
	    OnItemClickListener itemClickListener = new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View container, int position, long id) {
                // Mensaje Toast del elemento seleccionado.
            	try{
            	if(position==0){ 
            		transf=IDTransf.get(position);
            		BOD=BodDest.get(position);
					INVTID=InventTransid.get(position);
					LINENUM=LinenumidTR.get(position);
            	}else{
            		transf=IDTransf.get(position);
            		BOD=BodDest.get(position);
					INVTID=InventTransid.get(position);
					LINENUM=LinenumidTR.get(position);
            	}
            		Intent intento = new Intent(getApplicationContext(), TransferenceItemDetail.class);  
		        	intento.putExtra("PO", transf);
		       	    intento.putExtra("EX","0"); 
		       	    intento.putExtra("USER",USER); 
		       	    intento.putExtra("EMP2", EMP2);
		       	    intento.putExtra("BODDEST",BOD);
					intento.putExtra("INVTID",INVTID);
					intento.putExtra("LINENUM",LINENUM);
					intento.putExtra("CONFIG",CONFIG);
		       	    
		      	  	ListView listView = (ListView)findViewById(R.id.transferenciaslistview1);
		    	    INDEX = listView.getFirstVisiblePosition();
		    	    listView.setAdapter(null);
		    	    startActivity(intento);

            	}catch(NullPointerException exc){Toast.makeText(getApplicationContext(), "Error al seleccionar Item", Toast.LENGTH_SHORT).show();}
            }  
        };
	    	listView.setOnItemClickListener(itemClickListener);
	    }
   
	
    
    private class LoadViewTask extends AsyncTask<Void, Integer, Void>  
    {  
        @Override  
        protected void onPreExecute()  
        {  
        	progressDialog = ProgressDialog.show(TransferenceItemSummary.this,"Cargando...",  
        		    "Cargando informacion, favor espere...", false, false);
        }  

        @Override
        protected Void doInBackground(Void... params)
        {
        	StrictMode.setThreadPolicy(policy);

        	try{
        		String result1 = null;
            	InputStream is1 = null;
            	String v1 = "'"+PO+"'";
            	String v2 = "'"+EMP2+"'";
            	String v3 = "'"+BOD+"'";

        		SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");

            	ArrayList<NameValuePair> nameValuePairs1 = new ArrayList<NameValuePair>();
            	nameValuePairs1.add(new BasicNameValuePair("ITEMID",v1));
            	nameValuePairs1.add(new BasicNameValuePair("DATAAREAID",v2));
            	nameValuePairs1.add(new BasicNameValuePair("INVENTLOCATIONIDFROM",v3));

        	try
        	{
            	        HttpClient httpclient = new DefaultHttpClient();
            	        HttpPost httppost = new HttpPost("http://200.91.85.150/WAOPSPHP/Transference/getTransferenciasListByItemNew.php");
            	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs1));
            	        HttpResponse response = httpclient.execute(httppost);
            	        HttpEntity entity = response.getEntity();
            	        is1 = entity.getContent();
            	        Log.e("log_tag", "connection success ");
        	}
        	catch(Exception e)
        	{
            	        Log.e("log_tag", "Error in http connection "+e.toString());
            }

        	try{
            	        BufferedReader reader = new BufferedReader(new InputStreamReader(is1,"ISO-8859-1"),8);
            	        StringBuilder sb = new StringBuilder();
            	        String line = null;
            	        while ((line = reader.readLine()) != null)
            	        {
            	                sb.append(line + "\n");
            	        }
            	        is1.close();
						result1=sb.toString();
        	}
        	catch(Exception e)
        	{
            	       Log.e("log_tag", "Error converting result "+e.toString());
        	}
        	int counter=0;

            	try{
                    databaseHelper.deleteAllData();

            	 	JSONArray jArray = new JSONArray(result1);
            		for(int i=0;i<jArray.length();i++)
                    {
            			try{
				            		   	JSONObject no = jArray.getJSONObject(i);
				            		   	String inventtransid =no.getString("INVENTTRANSID");
				            		   	String transferid =no.getString("TRANSFERID");
				            		   	String itemid=no.getString("ITEMID");
				            		   	String  qtytransfer=no.getString("QTYTRANSFER");
				            		   	//String qtycounted=no.getString("QTYCOUNTED");
				            		    String inventlocationidfrom=no.getString("INVENTLOCATIONIDFROM");
				            		   	String inventlocationidto=no.getString("INVENTLOCATIONIDTO").toUpperCase();
				            		    String Estado=no.getString("TRANSFERSTATUS");
				            		    String dataareaid=no.getString("DATAAREAID");
				            		    String qtyavailable=no.getString("QTYTRANSFER");
				            		    String createddate=no.getString("CREATEDDATE");
										String barcode= BARCODE;
										String linenum=no.getString("LINENUM");
										String configid=no.getString("UNITID");
										String qtyremainship=no.getString("QTYREMAINSHIP");

										if(barcode.equals(""))
										{
											barcode="null";
										}
										
										//Proceso de Conversión a bultos
										String configdat=configid;
										if(configdat.charAt(0)=='B')
										{
											configdat=configdat.substring(1, configdat.length());
										}else
										{
											configdat="1";
										}
										
										Double qtybultos=Double.parseDouble(qtytransfer)/Double.parseDouble(configdat);
										Double availablebultos=qtybultos;
										String qtytransferbultos="";
										String availabletransferbultos="";
										try{
				                		    Double Qt =qtybultos;
				                		    NumberFormat nf = NumberFormat.getInstance();
				        	 	            nf.setMaximumFractionDigits(0);// set as you need
				        	 	           qtytransferbultos=nf.format(Qt).replace(",", "");
				            		    	}catch(Exception e){}
										
										try{
											Double Qt = availablebultos;
											NumberFormat nf = NumberFormat.getInstance();
											nf.setMaximumFractionDigits(0);// set as you need
											availabletransferbultos=nf.format(Qt).replace(",", "");
										}catch(Exception e){}
										
										FechaCreacionTransfer=createddate;
				            		    Disponible=qtytransferbultos;
				            		    IDTransf.add(transferid);
				            		    BodDest.add(inventlocationidto);
				            		    InventTransid.add(inventtransid);
				            		    LinenumidTR.add(linenum);
										Articulo=itemid;
										Transfer=transferid;

										databaseHelper.saveTransferenceLine(inventtransid,transferid,itemid,qtytransferbultos,"0",inventlocationidfrom,inventlocationidto.toUpperCase(),"0", Estado, dataareaid,availabletransferbultos,createddate,barcode,"0",linenum,"0","0",configid,"0",qtyremainship);

				        	            counter++;

            			}catch(Exception e)
        	          	{
            				 Log.e("log_tag", "Error cargando datos "+e.toString());
        	          	}
        	            }
            	}
            	catch(JSONException e)
            	{
            	        Log.e("log_tag", "Error parsing data "+e.toString()+Integer.toString( counter));
             	 } catch (IllegalArgumentException e) {
        			// TODO Auto-generated catch block
        			e.printStackTrace();
        		}
        		}catch(Exception e)
            	{
        	        Log.e("log_tag", "Active el VPN para aplicar esta opción.");
        		}

		        	  /*****************************************************************/
					/**Consulta a pedido de Compra según fecha de creación de transferencias**/
		          /*****************************************************************/
        	
				Cursor y =databaseHelper.getTransferenciasLines(PO);
				y.moveToFirst();
				int yc =y.getCount();
				if(y.getCount()==0){}
				else {
					StrictMode.setThreadPolicy(policy);

					try {
						String result2 = null;
						InputStream is2 = null;
						String v1 = "'" + Articulo + "'";
						String v2 = "'" + FechaCreacionTransfer + "'";
						String v3 = "'" + EMP2 + "'";
						String v4 = "'" + BOD + "'";

						ArrayList<NameValuePair> nameValuePairspo = new ArrayList<NameValuePair>();
						nameValuePairspo.add(new BasicNameValuePair("ITEMID", v1));
						nameValuePairspo.add(new BasicNameValuePair("FECHACREACION", v2));
						nameValuePairspo.add(new BasicNameValuePair("EMP2", v3));
						nameValuePairspo.add(new BasicNameValuePair("INVENTLOCATIONIDFROM", v4));

						//apartir de aqui carga ruta
						try 
						{
								HttpClient httpclient = new DefaultHttpClient();
								HttpPost httppost = new HttpPost("http://200.91.85.150/WAOPSPHP/Transference/getTransferPurchLinesListAX.php");
								httppost.setEntity(new UrlEncodedFormEntity(nameValuePairspo));
								HttpResponse response = httpclient.execute(httppost);
								HttpEntity entity = response.getEntity();
								is2 = entity.getContent();
								Log.e("log_tag", "connection success ");
						} catch (Exception e) 
						{
								Log.e("log_tag", "Error in http connection " + e.toString());
						}

						try 
						{
							BufferedReader reader = new BufferedReader(new InputStreamReader(is2, "ISO-8859-1"), 8);
							StringBuilder sb = new StringBuilder();
							String line = null;
							while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
							is2.close();
							result2 = sb.toString();
						} catch (Exception e) {
							Log.e("log_tag", "Error converting result " + e.toString());
						}

						int counter = 0;

						try {
							//databaseHelperPO.deleteAllData();

							JSONArray jArray = new JSONArray(result2);
							for (int i = 0; i < jArray.length(); i++) {
								try {
									JSONObject no = jArray.getJSONObject(i);
									String purchid = no.getString("PURCHID");
									String itemid = no.getString("ITEMID");
									String purchqty = no.getString("PURCHQTY");
									String qtyordered = no.getString("QTYORDERED");
									String purchunit = no.getString("PURCHUNIT");
									String purchreceivednow = no.getString("PURCHRECEIVEDNOW");
									String purchstatus = no.getString("PURCHSTATUS");
									String orderaccount = no.getString("ORDERACCOUNT");
									String createddate = no.getString("CREATEDDATE");
									String inventlocationid = no.getString("INVENTLOCATIONID");
									String linenum = no.getString("LINENUM");

									try 
									{
											Double Qt = Double.parseDouble(purchqty);
											NumberFormat nf = NumberFormat.getInstance();
											nf.setMaximumFractionDigits(0);// set as you need
											purchqty = nf.format(Qt).replace(",", "");
									} catch (Exception e) {}
									try
									{
										Double Qt2 = Double.parseDouble(qtyordered);
										NumberFormat nf2 = NumberFormat.getInstance();
										nf2.setMaximumFractionDigits(0);// set as you need
										qtyordered = nf2.format(Qt2).replace(",", "");
									} catch (Exception e) {}
									try
									{
										Double Qt3 = Double.parseDouble(purchreceivednow);
										NumberFormat nf3 = NumberFormat.getInstance();
										nf3.setMaximumFractionDigits(0);// set as you need
										purchreceivednow = nf3.format(Qt3).replace(",", "");
									} catch (Exception e) {}
									
									PedidoCompra = purchid;

									InventLINENUMPO.add(linenum);
									CONFIG=purchunit;

									String itemid2=PO;
									String newqtyavailable= purchqty;
									int conttransfer=0;
									y.moveToFirst();
									
									for(int z=0;z<y.getCount();z++)
									{
										Cursor r =databaseHelper.getAllTransferenciasLines();
										r.moveToPosition(z);
										String inventtransid2=r.getString(1);
										String qtyTransf=r.getString(4);
										String id1 = r.getString(0);
										String conf=purchunit;
										String statusprocessed= r.getString(9);//Campo TransferStatus
										String fechap=  r.getString(12);
										double qtyremShip=Double.parseDouble(r.getString(20));
										
										switch(statusprocessed){
										
										case "0":
											
											//if(Double.parseDouble(qtyTransf)==Double.parseDouble(qtyordered) && conttransfer==0 && createddate.equals(fechap) )
											if(Double.parseDouble(qtyTransf)==Double.parseDouble(purchqty) && conttransfer==0)
											{
												 		databaseHelper.UpdateItemPO(PedidoCompra,linenum, id1);
														conttransfer++;
														//r.moveToNext();
											}else{
												//conttransfer++;
											}
											break;
										}
										
									}
									databaseHelperPO.saveTransferencePOLine(purchid, itemid, purchqty, qtyordered, purchunit, purchreceivednow, purchstatus, orderaccount, createddate, inventlocationid, linenum,"0");

									counter++;
								}
								catch (Exception e) 
								{
									Log.e("log_tag", "Error cargando datos " + e.toString());
								}
							}
						} 
						catch (JSONException e) 
						{
							Log.e("log_tag", "Error parsing data " + e.toString() + Integer.toString(counter));
						} 
						catch (IllegalArgumentException e)
						{
							e.printStackTrace();
						}
					} 
					catch (Exception e)
					{
						Log.e("log_tag", "Active el VPN para aplicar esta opción.");
					}
					
				}
						/*Fin de consulta */
		
		
		
		 			 /*******************************************************/
					/**Consulta a envios según fecha de creación de transferencias**/
		          /*******************************************************/
		
			Cursor p =databaseHelper.getAllTransferenciasLines();
			p.moveToFirst();
			int px = p.getCount();
			if(p.getCount()==0){}
			else{

			StrictMode.setThreadPolicy(policy);

			try {
				String result3 = null;
				InputStream is3 = null;
				String v1 = "'" + Articulo + "'";
				String v2 = "'" + PedidoCompra + "'";
				String v3 = "'" + BOD + "'";

				ArrayList<NameValuePair> nameValuePairspo = new ArrayList<NameValuePair>();
				nameValuePairspo.add(new BasicNameValuePair("ITEMID", v1));
				nameValuePairspo.add(new BasicNameValuePair("PURCHID", v2));
				nameValuePairspo.add(new BasicNameValuePair("INVENTLOCATIONIDTO", v3));

				try {
					HttpClient httpclient = new DefaultHttpClient();
					HttpPost httppost = new HttpPost("http://200.91.85.150/WAOPSPHP/Transference/getTransferenciasQtyCrsDckByItem.php");
					httppost.setEntity(new UrlEncodedFormEntity(nameValuePairspo));
					HttpResponse response = httpclient.execute(httppost);
					HttpEntity entity = response.getEntity();
					is3 = entity.getContent();
					Log.e("log_tag", "connection success ");
				} catch (Exception e) {
					Log.e("log_tag", "Error in http connection " + e.toString());
				}

				try {
					BufferedReader reader = new BufferedReader(new InputStreamReader(is3, "ISO-8859-1"), 8);
					StringBuilder sb = new StringBuilder();
					String line = null;
					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is3.close();
					result3 = sb.toString();
				} catch (Exception e) {
					Log.e("log_tag", "Error converting result " + e.toString());
				}

				int counter = 0;

				try {
					//databaseHelperPO.deleteAllData();
					
					JSONArray jArray = new JSONArray(result3);
					for (int i = 0; i < jArray.length(); i++) {
						try {
							JSONObject no = jArray.getJSONObject(i);
							String shipmentid = no.getString("SHIPMENTID");
							String itemid = no.getString("ITEMID");
							String qty = no.getString("QTY");
							String transdate = no.getString("TRANSDATE");
							String inventlocationidto = no.getString("INVENTLOCATIONIDTO");
							String purchid = no.getString("PURCHID");
							String dataareaidto = no.getString("DATAAREAIDTO");
							String processed = no.getString("PROCESSED");
							String inventtransid = no.getString("INVENTTRANSID");

							try 
							{
								Double Qt = Double.parseDouble(qty);
								NumberFormat nf = NumberFormat.getInstance();
								nf.setMaximumFractionDigits(0);// set as you need
								qty = nf.format(Qt).replace(",", "");
							} catch (Exception e){}

							//Actualiza la cantidad de las líneas de la transferencia con el total disponible despachado para repartir a las PDAs.
							for(int u=0;u<p.getCount();u++)
							{
	     			    		String idf= p.getString(0);
	     		                databaseHelper.UpdateTotalDisponible(idf, qty);
	     		                p.moveToNext();
     		                }
							//Ciclo que reparte de la cantidad total disponible a las cantidades requeridas por las transferencias.
							for(int u=0;u<p.getCount();u++)
							{
								Cursor s =databaseHelper.getAllTransferenciasLines();
								s.moveToPosition(u);
								
								String idf2= s.getString(0);
								String ParingProcessed=s.getString(9);
								//double qtyremship=Double.parseDouble(s.getString(20));
								
								if(ParingProcessed.equals("1")){
										//Variable que guarda el total disponible a despachar en bultos para las transferencias.
			     			    		Double TotalDisponible = Double.parseDouble(s.getString(19));
			     			    		//Variable que trae la cantidad actual requerida por la transferencia en unidades.
										Double qtyactual = Double.parseDouble(s.getString(4));				
										//Variable que recibe el resultado de la resta de la cantidad disponible menos la cantidad requerida por la transferencia.
										newtotaldisp = TotalDisponible-qtyactual;
										//Variable que guarda la cantidad resultado de la diferencia entre el total disponible y el total disponible restado de la cantidad requerida.
										Double newqty =TotalDisponible-newtotaldisp;
										//condición si la nueva cantidad en menor a cero que respete que esa variable sea igual a cero para poder asignarla sin negativos.
										if(newqty<0){newqty=0.0;}
										String newqtyf = String.valueOf(newqty);
										//Bloque que le quita los ceros a la cantidad disponible.
										try 
										{	NumberFormat nf = NumberFormat.getInstance();
											nf.setMaximumFractionDigits(0);// set as you need
											newqtyf = nf.format(newqty).replace(",", "");
										} catch (Exception e){}
										//Actualización para cada línea de transferencia con cantidad disponible para despachar en bultos.								
										 databaseHelper.UpdateQtyTransferRequired(idf2, newqtyf);
								}
														
     		                }
							
							databaseHelperCrsDck.saveCrsDckLine(shipmentid, itemid, qty, transdate, inventlocationidto, purchid, dataareaidto, processed, inventtransid);

							counter++;

						} catch (Exception e) {
							Log.e("log_tag", "Error cargando datos " + e.toString());
						}
					}
				} catch (JSONException e) {
					Log.e("log_tag", "Error parsing data " + e.toString() + Integer.toString(counter));
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} catch (Exception e)
			{
				Log.e("log_tag", "Active el VPN para aplicar esta opción.");
			}

			}
			  		/*Fin de consulta */

			 /*******************************************************/
			/**Consulta de Items de Transferencia no procesados**/
          /*******************************************************/
			
			Cursor x =databaseHelper.getAllTransferenciasLines();
			int xy = x.getCount();
			if(x.getCount()==0){}
			else{
				try{
					
						String result4 = null;
						InputStream is4 = null;
						String v1 = "'"+PO+"'";
						String v2 = "'"+EMP2+"'";
						SimpleDateFormat sdfa2 = new SimpleDateFormat("yyyy-MM-dd");
	
						ArrayList<NameValuePair> nameValuePairs4 = new ArrayList<NameValuePair>();
						nameValuePairs4.add(new BasicNameValuePair("ITEM",v1));
						nameValuePairs4.add(new BasicNameValuePair("DATAAREAID",v2));
				try
					{
							HttpClient httpclient = new DefaultHttpClient();
							HttpPost httppost = new HttpPost("http://200.91.85.150/WAOPSPHP/Transference/getTransferenciasNotProcessedListByItemAC.php");
							httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs4));
							HttpResponse response = httpclient.execute(httppost);
							HttpEntity entity = response.getEntity();
							is4 = entity.getContent();
							Log.e("log_tag", "connection success ");	
					}
					catch(Exception e)
					{
						Log.e("log_tag", "Error in http connection "+e.toString());
					}

					try
					{
							BufferedReader reader = new BufferedReader(new InputStreamReader(is4,"ISO-8859-1"),8);
							StringBuilder sb = new StringBuilder();
							String line = null;
							while ((line = reader.readLine()) != null)
							{
								sb.append(line + "\n");
							}
							is4.close();
							result4=sb.toString();
					}
					catch(Exception e)
					{
							Log.e("log_tag", "Error converting result "+e.toString());
					}
					int counter=0;

					try{
						//databaseHelper.deleteAllData();
						JSONArray jArray = new JSONArray(result4);
						for(int i=0;i<jArray.length();i++)
						{
							try
							{
								JSONObject no = jArray.getJSONObject(i);

								String CONTADA=no.getString("QTYCOUNTED");
								String DISPONIBLE=no.getString("QTYAVAILABLE");
								String SOBRANTE=no.getString("QTYREMAIN");
								transf2 = no.getString("TRANSFERID");

								try{
									Double Qt = Double.parseDouble(CONTADA);
									NumberFormat nf = NumberFormat.getInstance();
									nf.setMaximumFractionDigits(0);// set as you need
									CONTADA=nf.format(Qt).replace(",", "");
								}catch(Exception e){}
								
								try{
									Double Qt = Double.parseDouble(DISPONIBLE);
									NumberFormat nf3 = NumberFormat.getInstance();
									nf3.setMaximumFractionDigits(0);// set as you need
									DISPONIBLE=nf3.format(Qt).replace(",", "");
								}catch(Exception e){}

								try{
									Double Qt = Double.parseDouble(SOBRANTE);
									NumberFormat nf4 = NumberFormat.getInstance();
									nf4.setMaximumFractionDigits(0);// set as you need
									SOBRANTE=nf4.format(Qt).replace(",", "");
								}catch(Exception e){}

								String inventtransid=no.getString("INVENTTRANSID");
								String itemid=no.getString("ITEMID");
								NumberFormat nf = NumberFormat.getInstance();
								nf.setMaximumFractionDigits(0);
								Cursor xyz =databaseHelper.getTransferItemDetail(transf2,inventtransid,itemid);
								if(xyz.getCount()>0)
								{
									xyz.moveToFirst();
									String id1 = xyz.getString(0);
									databaseHelper.UpdateTransferItem(CONTADA, DISPONIBLE, SOBRANTE, id1);
								}
								counter++;
							}catch(Exception e)
							{
							}
						}
					}
					catch(JSONException e)
					{
						Log.e("log_tag", "Error parsing data "+e.toString()+Integer.toString(counter));
					} catch (IllegalArgumentException e) {
						e.printStackTrace();
					}
				}catch(Exception e)
				{
					Log.e("log_tag", "Active el VPN para aplicar esta opción.");
				}
				
				/*Fin de Consulta*/

	   		}

			return null;
        }
        																																																																																																																																																																																																																																																																																																														
        @Override  
        protected void onProgressUpdate(Integer... values)  
        {  
            progressDialog.setProgress(values[0]);  
        }  
        
        @Override  
        protected void onPostExecute(Void result)      
        {  
            progressDialog.dismiss();
            
            Cursor x =databaseHelper.getTransferenciasLines(PO);
        	if(x.getCount()==0){
           		Toast.makeText(getBaseContext(), "No hay transferencias disponibles para trabajar.", Toast.LENGTH_LONG).show();
        		
				TextView DesdeA = (TextView) findViewById(R.id.qtydisponible);
                Typeface fontbold2 = Typeface.createFromAsset(TransferenceItemSummary.this.getAssets(), "fonts/opensans-semibold.ttf"); 
                DesdeA.setTypeface(fontbold2);
                DesdeA.setText("Lista para Distribución a PDAs");
                DesdeA.setTextColor(Color.BLACK);
                DesdeA.setTextSize(TypedValue.COMPLEX_UNIT_SP, 17);
           	}  
        	else
        	{
        		NumberFormat nf = NumberFormat.getInstance();
                nf.setMaximumFractionDigits(0);
                
        		TextView DesdeA = (TextView) findViewById(R.id.qtydisponible);
                Typeface fontbold2 = Typeface.createFromAsset(TransferenceItemSummary.this.getAssets(), "fonts/opensans-semibold.ttf"); 
                DesdeA.setTypeface(fontbold2);
                DesdeA.setText("Lista para Distribución a PDAs");
                DesdeA.setTextColor(Color.BLACK);
                DesdeA.setTextSize(TypedValue.COMPLEX_UNIT_SP, 17);
        	}

        		ListView listView = (ListView)findViewById(R.id.transferenciaslistview1);
        		listView.setAdapter(null);
        		newTransferenceAdapter = new TransferenceAdapter1(TransferenceItemSummary.this,databaseHelper.getAllTransferenciasLines());
    		  	listView.setAdapter(newTransferenceAdapter );
    			listView.setCacheColorHint(Color.TRANSPARENT);
            }
    
    }
  
    
    private class LoadViewTaskRefresh extends AsyncTask<Void, Integer, Void>  
    {  
        //Before running code in separate thread  

		@Override
		protected Void doInBackground(Void... params)
		{
        	StrictMode.setThreadPolicy(policy);

        	try{
        		String result1 = null;
            	InputStream is1 = null;
            	String v1 = "'"+PO+"'";
            	String v2 = "'"+EMP2+"'";
            	String v3 = "'"+BOD+"'";

        		SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");

            	ArrayList<NameValuePair> nameValuePairs1 = new ArrayList<NameValuePair>();
            	nameValuePairs1.add(new BasicNameValuePair("ITEMID",v1));
            	nameValuePairs1.add(new BasicNameValuePair("DATAAREAID",v2));
            	nameValuePairs1.add(new BasicNameValuePair("INVENTLOCATIONIDFROM",v3));

        	try
        	{
            	        HttpClient httpclient = new DefaultHttpClient();
            	        HttpPost httppost = new HttpPost("http://200.91.85.150/WAOPSPHP/Transference/getTransferenciasListByItemNew.php");
            	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs1));
            	        HttpResponse response = httpclient.execute(httppost);
            	        HttpEntity entity = response.getEntity();
            	        is1 = entity.getContent();
            	        Log.e("log_tag", "connection success ");
        	}
        	catch(Exception e)
        	{
            	        Log.e("log_tag", "Error in http connection "+e.toString());
            }

        	try{
            	        BufferedReader reader = new BufferedReader(new InputStreamReader(is1,"ISO-8859-1"),8);
            	        StringBuilder sb = new StringBuilder();
            	        String line = null;
            	        while ((line = reader.readLine()) != null)
            	        {
            	                sb.append(line + "\n");
            	        }
            	        is1.close();
						result1=sb.toString();
        	}
        	catch(Exception e)
        	{
            	       Log.e("log_tag", "Error converting result "+e.toString());
        	}
        	int counter=0;

            	try{
                    databaseHelper.deleteAllData();

            	 	JSONArray jArray = new JSONArray(result1);
            		for(int i=0;i<jArray.length();i++)
                    {
            			try{
				            		   	JSONObject no = jArray.getJSONObject(i);
				            		   	String inventtransid =no.getString("INVENTTRANSID");
				            		   	String transferid =no.getString("TRANSFERID");
				            		   	String itemid=no.getString("ITEMID");
				            		   	String  qtytransfer=no.getString("QTYTRANSFER");
				            		   	//String qtycounted=no.getString("QTYCOUNTED");
				            		    String inventlocationidfrom=no.getString("INVENTLOCATIONIDFROM");
				            		   	String inventlocationidto=no.getString("INVENTLOCATIONIDTO").toUpperCase();
				            		    String Estado=no.getString("TRANSFERSTATUS");
				            		    String dataareaid=no.getString("DATAAREAID");
				            		    String qtyavailable=no.getString("QTYTRANSFER");
				            		    String createddate=no.getString("CREATEDDATE");
										String barcode= BARCODE;
										String linenum=no.getString("LINENUM");
										String configid=no.getString("UNITID");
										String qtyremainship=no.getString("QTYREMAINSHIP");

										if(barcode.equals(""))
										{
											barcode="null";
										}
										
										//Proceso de Conversión a bultos
										String configdat=configid;
										if(configdat.charAt(0)=='B')
										{
											configdat=configdat.substring(1, configdat.length());
										}else
										{
											configdat="1";
										}
										
										Double qtybultos=Double.parseDouble(qtytransfer)/Double.parseDouble(configdat);
										Double availablebultos=qtybultos;
										String qtytransferbultos="";
										String availabletransferbultos="";
										try{
				                		    Double Qt =qtybultos;
				                		    NumberFormat nf = NumberFormat.getInstance();
				        	 	            nf.setMaximumFractionDigits(0);// set as you need
				        	 	           qtytransferbultos=nf.format(Qt).replace(",", "");
				            		    	}catch(Exception e){}
										
										try{
											Double Qt = availablebultos;
											NumberFormat nf = NumberFormat.getInstance();
											nf.setMaximumFractionDigits(0);// set as you need
											availabletransferbultos=nf.format(Qt).replace(",", "");
										}catch(Exception e){}
										
										FechaCreacionTransfer=createddate;
				            		    Disponible=qtytransferbultos;
				            		    IDTransf.add(transferid);
				            		    BodDest.add(inventlocationidto);
				            		    InventTransid.add(inventtransid);
				            		    LinenumidTR.add(linenum);
										Articulo=itemid;
										Transfer=transferid;

										databaseHelper.saveTransferenceLine(inventtransid,transferid,itemid,qtytransferbultos,"0",inventlocationidfrom,inventlocationidto.toUpperCase(),"0", Estado, dataareaid,availabletransferbultos,createddate,barcode,"0",linenum,"0","0",configid,"0",qtyremainship);

				        	            counter++;

            			}catch(Exception e)
        	          	{
            				 Log.e("log_tag", "Error cargando datos "+e.toString());
        	          	}
        	            }
            	}
            	catch(JSONException e)
            	{
            	        Log.e("log_tag", "Error parsing data "+e.toString()+Integer.toString( counter));
             	 } catch (IllegalArgumentException e) {
        			// TODO Auto-generated catch block
        			e.printStackTrace();
        		}
        		}catch(Exception e)
            	{
        	        Log.e("log_tag", "Active el VPN para aplicar esta opción.");
        		}

		        	  /*****************************************************************/
					/**Consulta a pedido de Compra según fecha de creación de transferencias**/
		          /*****************************************************************/
        	
				Cursor y =databaseHelper.getTransferenciasLines(PO);
				y.moveToFirst();
				int yc =y.getCount();
				if(y.getCount()==0){}
				else {
					StrictMode.setThreadPolicy(policy);

					try {
						String result2 = null;
						InputStream is2 = null;
						String v1 = "'" + Articulo + "'";
						String v2 = "'" + FechaCreacionTransfer + "'";
						String v3 = "'" + EMP2 + "'";
						String v4 = "'" + BOD + "'";

						ArrayList<NameValuePair> nameValuePairspo = new ArrayList<NameValuePair>();
						nameValuePairspo.add(new BasicNameValuePair("ITEMID", v1));
						nameValuePairspo.add(new BasicNameValuePair("FECHACREACION", v2));
						nameValuePairspo.add(new BasicNameValuePair("EMP2", v3));
						nameValuePairspo.add(new BasicNameValuePair("INVENTLOCATIONIDFROM", v4));

						//apartir de aqui carga ruta
						try 
						{
								HttpClient httpclient = new DefaultHttpClient();
								HttpPost httppost = new HttpPost("http://200.91.85.150/WAOPSPHP/Transference/getTransferPurchLinesListAX.php");
								httppost.setEntity(new UrlEncodedFormEntity(nameValuePairspo));
								HttpResponse response = httpclient.execute(httppost);
								HttpEntity entity = response.getEntity();
								is2 = entity.getContent();
								Log.e("log_tag", "connection success ");
						} catch (Exception e) 
						{
								Log.e("log_tag", "Error in http connection " + e.toString());
						}

						try 
						{
							BufferedReader reader = new BufferedReader(new InputStreamReader(is2, "ISO-8859-1"), 8);
							StringBuilder sb = new StringBuilder();
							String line = null;
							while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
							is2.close();
							result2 = sb.toString();
						} catch (Exception e) {
							Log.e("log_tag", "Error converting result " + e.toString());
						}

						int counter = 0;

						try {
							//databaseHelperPO.deleteAllData();

							JSONArray jArray = new JSONArray(result2);
							for (int i = 0; i < jArray.length(); i++) {
								try {
									JSONObject no = jArray.getJSONObject(i);
									String purchid = no.getString("PURCHID");
									String itemid = no.getString("ITEMID");
									String purchqty = no.getString("PURCHQTY");
									String qtyordered = no.getString("QTYORDERED");
									String purchunit = no.getString("PURCHUNIT");
									String purchreceivednow = no.getString("PURCHRECEIVEDNOW");
									String purchstatus = no.getString("PURCHSTATUS");
									String orderaccount = no.getString("ORDERACCOUNT");
									String createddate = no.getString("CREATEDDATE");
									String inventlocationid = no.getString("INVENTLOCATIONID");
									String linenum = no.getString("LINENUM");

									try 
									{
											Double Qt = Double.parseDouble(purchqty);
											NumberFormat nf = NumberFormat.getInstance();
											nf.setMaximumFractionDigits(0);// set as you need
											purchqty = nf.format(Qt).replace(",", "");
									} catch (Exception e) {}
									try
									{
										Double Qt2 = Double.parseDouble(qtyordered);
										NumberFormat nf2 = NumberFormat.getInstance();
										nf2.setMaximumFractionDigits(0);// set as you need
										qtyordered = nf2.format(Qt2).replace(",", "");
									} catch (Exception e) {}
									try
									{
										Double Qt3 = Double.parseDouble(purchreceivednow);
										NumberFormat nf3 = NumberFormat.getInstance();
										nf3.setMaximumFractionDigits(0);// set as you need
										purchreceivednow = nf3.format(Qt3).replace(",", "");
									} catch (Exception e) {}
									
									PedidoCompra = purchid;

									InventLINENUMPO.add(linenum);
									CONFIG=purchunit;

									String itemid2=PO;
									String newqtyavailable= purchqty;
									int conttransfer=0;
									y.moveToFirst();
									
									for(int z=0;z<y.getCount();z++)
									{
										Cursor r =databaseHelper.getAllTransferenciasLines();
										r.moveToPosition(z);
										String inventtransid2=r.getString(1);
										String qtyTransf=r.getString(4);
										String id1 = r.getString(0);
										String conf=purchunit;
										String statusprocessed= r.getString(9);//Campo TransferStatus
										String fechap=  r.getString(12);
										double qtyremShip=Double.parseDouble(r.getString(20));
										
										switch(statusprocessed){
										
										case "0":
											
											if(Double.parseDouble(qtyTransf)==Double.parseDouble(qtyordered) && conttransfer==0 && createddate.equals(fechap) )
											{
												 		databaseHelper.UpdateItemPO(PedidoCompra,linenum, id1);
														conttransfer++;
														//r.moveToNext();
											}else{
												//conttransfer++;
											}
											break;
										}
										
									}
									databaseHelperPO.saveTransferencePOLine(purchid, itemid, purchqty, qtyordered, purchunit, purchreceivednow, purchstatus, orderaccount, createddate, inventlocationid, linenum,"0");

									counter++;
								}
								catch (Exception e) 
								{
									Log.e("log_tag", "Error cargando datos " + e.toString());
								}
							}
						} 
						catch (JSONException e) 
						{
							Log.e("log_tag", "Error parsing data " + e.toString() + Integer.toString(counter));
						} 
						catch (IllegalArgumentException e)
						{
							e.printStackTrace();
						}
					} 
					catch (Exception e)
					{
						Log.e("log_tag", "Active el VPN para aplicar esta opción.");
					}
					
				}
						/*Fin de consulta */
		
		
		
		 			 /*******************************************************/
					/**Consulta a envios según fecha de creación de transferencias**/
		          /*******************************************************/
		
			Cursor p =databaseHelper.getAllTransferenciasLines();
			p.moveToFirst();
			int px = p.getCount();
			if(p.getCount()==0){}
			else{

			StrictMode.setThreadPolicy(policy);

			try {
				String result3 = null;
				InputStream is3 = null;
				String v1 = "'" + Articulo + "'";
				String v2 = "'" + PedidoCompra + "'";
				String v3 = "'" + BOD + "'";

				ArrayList<NameValuePair> nameValuePairspo = new ArrayList<NameValuePair>();
				nameValuePairspo.add(new BasicNameValuePair("ITEMID", v1));
				nameValuePairspo.add(new BasicNameValuePair("PURCHID", v2));
				nameValuePairspo.add(new BasicNameValuePair("INVENTLOCATIONIDTO", v3));

				try {
					HttpClient httpclient = new DefaultHttpClient();
					HttpPost httppost = new HttpPost("http://200.91.85.150/WAOPSPHP/Transference/getTransferenciasQtyCrsDckByItem.php");
					httppost.setEntity(new UrlEncodedFormEntity(nameValuePairspo));
					HttpResponse response = httpclient.execute(httppost);
					HttpEntity entity = response.getEntity();
					is3 = entity.getContent();
					Log.e("log_tag", "connection success ");
				} catch (Exception e) {
					Log.e("log_tag", "Error in http connection " + e.toString());
				}

				try {
					BufferedReader reader = new BufferedReader(new InputStreamReader(is3, "ISO-8859-1"), 8);
					StringBuilder sb = new StringBuilder();
					String line = null;
					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is3.close();
					result3 = sb.toString();
				} catch (Exception e) {
					Log.e("log_tag", "Error converting result " + e.toString());
				}

				int counter = 0;

				try {
					//databaseHelperPO.deleteAllData();
					
					JSONArray jArray = new JSONArray(result3);
					for (int i = 0; i < jArray.length(); i++) {
						try {
							JSONObject no = jArray.getJSONObject(i);
							String shipmentid = no.getString("SHIPMENTID");
							String itemid = no.getString("ITEMID");
							String qty = no.getString("QTY");
							String transdate = no.getString("TRANSDATE");
							String inventlocationidto = no.getString("INVENTLOCATIONIDTO");
							String purchid = no.getString("PURCHID");
							String dataareaidto = no.getString("DATAAREAIDTO");
							String processed = no.getString("PROCESSED");
							String inventtransid = no.getString("INVENTTRANSID");

							try 
							{
								Double Qt = Double.parseDouble(qty);
								NumberFormat nf = NumberFormat.getInstance();
								nf.setMaximumFractionDigits(0);// set as you need
								qty = nf.format(Qt).replace(",", "");
							} catch (Exception e){}

							//Actualiza la cantidad de las líneas de la transferencia con el total disponible despachado para repartir a las PDAs.
							for(int u=0;u<p.getCount();u++)
							{
	     			    		String idf= p.getString(0);
	     		                databaseHelper.UpdateTotalDisponible(idf, qty);
	     		                p.moveToNext();
     		                }
							//Ciclo que reparte de la cantidad total disponible a las cantidades requeridas por las transferencias.
							for(int u=0;u<p.getCount();u++)
							{
								Cursor s =databaseHelper.getAllTransferenciasLines();
								s.moveToPosition(u);
								
								String idf2= s.getString(0);
								String ParingProcessed=s.getString(9);
								//double qtyremship=Double.parseDouble(s.getString(20));
								
								if(ParingProcessed.equals("1")){
										//Variable que guarda el total disponible a despachar en bultos para las transferencias.
			     			    		Double TotalDisponible = Double.parseDouble(s.getString(19));
			     			    		//Variable que trae la cantidad actual requerida por la transferencia en unidades.
										Double qtyactual = Double.parseDouble(s.getString(4));				
										//Variable que recibe el resultado de la resta de la cantidad disponible menos la cantidad requerida por la transferencia.
										newtotaldisp = TotalDisponible-qtyactual;
										//Variable que guarda la cantidad resultado de la diferencia entre el total disponible y el total disponible restado de la cantidad requerida.
										Double newqty =TotalDisponible-newtotaldisp;
										//condición si la nueva cantidad en menor a cero que respete que esa variable sea igual a cero para poder asignarla sin negativos.
										if(newqty<0){newqty=0.0;}
										String newqtyf = String.valueOf(newqty);
										//Bloque que le quita los ceros a la cantidad disponible.
										try 
										{	NumberFormat nf = NumberFormat.getInstance();
											nf.setMaximumFractionDigits(0);// set as you need
											newqtyf = nf.format(newqty).replace(",", "");
										} catch (Exception e){}
										//Actualización para cada línea de transferencia con cantidad disponible para despachar en bultos.								
										 databaseHelper.UpdateQtyTransferRequired(idf2, newqtyf);
								}
														
     		                }
							
							databaseHelperCrsDck.saveCrsDckLine(shipmentid, itemid, qty, transdate, inventlocationidto, purchid, dataareaidto, processed, inventtransid);

							counter++;

						} catch (Exception e) {
							Log.e("log_tag", "Error cargando datos " + e.toString());
						}
					}
				} catch (JSONException e) {
					Log.e("log_tag", "Error parsing data " + e.toString() + Integer.toString(counter));
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} catch (Exception e)
			{
				Log.e("log_tag", "Active el VPN para aplicar esta opción.");
			}

			}
			  		/*Fin de consulta */

			 /*******************************************************/
			/**Consulta de Items de Transferencia no procesados**/
          /*******************************************************/
			
			Cursor x =databaseHelper.getAllTransferenciasLines();
			int xy = x.getCount();
			if(x.getCount()==0){}
			else{
				try{
					
						String result4 = null;
						InputStream is4 = null;
						String v1 = "'"+PO+"'";
						String v2 = "'"+EMP2+"'";
						SimpleDateFormat sdfa2 = new SimpleDateFormat("yyyy-MM-dd");
	
						ArrayList<NameValuePair> nameValuePairs4 = new ArrayList<NameValuePair>();
						nameValuePairs4.add(new BasicNameValuePair("ITEM",v1));
						nameValuePairs4.add(new BasicNameValuePair("DATAAREAID",v2));
				try
					{
							HttpClient httpclient = new DefaultHttpClient();
							HttpPost httppost = new HttpPost("http://200.91.85.150/WAOPSPHP/Transference/getTransferenciasNotProcessedListByItemAC.php");
							httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs4));
							HttpResponse response = httpclient.execute(httppost);
							HttpEntity entity = response.getEntity();
							is4 = entity.getContent();
							Log.e("log_tag", "connection success ");	
					}
					catch(Exception e)
					{
						Log.e("log_tag", "Error in http connection "+e.toString());
					}

					try
					{
							BufferedReader reader = new BufferedReader(new InputStreamReader(is4,"ISO-8859-1"),8);
							StringBuilder sb = new StringBuilder();
							String line = null;
							while ((line = reader.readLine()) != null)
							{
								sb.append(line + "\n");
							}
							is4.close();
							result4=sb.toString();
					}
					catch(Exception e)
					{
							Log.e("log_tag", "Error converting result "+e.toString());
					}
					int counter=0;

					try{
						//databaseHelper.deleteAllData();
						JSONArray jArray = new JSONArray(result4);
						for(int i=0;i<jArray.length();i++)
						{
							try
							{
								JSONObject no = jArray.getJSONObject(i);

								String CONTADA=no.getString("QTYCOUNTED");
								String DISPONIBLE=no.getString("QTYAVAILABLE");
								String SOBRANTE=no.getString("QTYREMAIN");
								transf2 = no.getString("TRANSFERID");

								try{
									Double Qt = Double.parseDouble(CONTADA);
									NumberFormat nf = NumberFormat.getInstance();
									nf.setMaximumFractionDigits(0);// set as you need
									CONTADA=nf.format(Qt).replace(",", "");
								}catch(Exception e){}
								
								try{
									Double Qt = Double.parseDouble(DISPONIBLE);
									NumberFormat nf3 = NumberFormat.getInstance();
									nf3.setMaximumFractionDigits(0);// set as you need
									DISPONIBLE=nf3.format(Qt).replace(",", "");
								}catch(Exception e){}

								try{
									Double Qt = Double.parseDouble(SOBRANTE);
									NumberFormat nf4 = NumberFormat.getInstance();
									nf4.setMaximumFractionDigits(0);// set as you need
									SOBRANTE=nf4.format(Qt).replace(",", "");
								}catch(Exception e){}

								String inventtransid=no.getString("INVENTTRANSID");
								String itemid=no.getString("ITEMID");
								NumberFormat nf = NumberFormat.getInstance();
								nf.setMaximumFractionDigits(0);
								Cursor xyz =databaseHelper.getTransferItemDetail(transf2,inventtransid,itemid);
								if(xyz.getCount()>0)
								{
									xyz.moveToFirst();
									String id1 = xyz.getString(0);
									databaseHelper.UpdateTransferItem(CONTADA, DISPONIBLE, SOBRANTE, id1);
								}
								counter++;
							}catch(Exception e)
							{
							}
						}
					}
					catch(JSONException e)
					{
						Log.e("log_tag", "Error parsing data "+e.toString()+Integer.toString(counter));
					} catch (IllegalArgumentException e) {
						e.printStackTrace();
					}
				}catch(Exception e)
				{
					Log.e("log_tag", "Active el VPN para aplicar esta opción.");
				}
				
				/*Fin de Consulta*/

	   		}

			return null;
        }

		//Update the progress
		@Override
		protected void onProgressUpdate(Integer... values)
		{
			//set the current progress of the progress dialog
			progressDialog.setProgress(values[0]);
		}

		//after executing the code in the thread
		@Override
		protected void onPostExecute(Void result)
		{
			progressDialog.dismiss();

			Cursor x =databaseHelper.getTransferenciasLines(PO);
			if(x.getCount()==0){
				Toast.makeText(getBaseContext(), "No hay transferencias disponibles para trabajar.", Toast.LENGTH_LONG).show();

				TextView DesdeA = (TextView) findViewById(R.id.qtydisponible);
				Typeface fontbold2 = Typeface.createFromAsset(TransferenceItemSummary.this.getAssets(), "fonts/opensans-semibold.ttf");
				DesdeA.setTypeface(fontbold2);
				DesdeA.setText("Lista para Distribución a PDAs");
				DesdeA.setTextColor(Color.BLACK);
				DesdeA.setTextSize(TypedValue.COMPLEX_UNIT_SP, 17);

			}
			else
			{
				NumberFormat nf = NumberFormat.getInstance();
				nf.setMaximumFractionDigits(0);// set as you need

				TextView DesdeA = (TextView) findViewById(R.id.qtydisponible);
				Typeface fontbold2 = Typeface.createFromAsset(TransferenceItemSummary.this.getAssets(), "fonts/opensans-semibold.ttf");
				DesdeA.setTypeface(fontbold2);
				DesdeA.setText("Lista para Distribución a PDAs");
				DesdeA.setTextColor(Color.BLACK);
				DesdeA.setTextSize(TypedValue.COMPLEX_UNIT_SP, 17);
			}

			ListView listView = (ListView)findViewById(R.id.transferenciaslistview1);
			listView.setAdapter(null);
			newTransferenceAdapter = new TransferenceAdapter1(TransferenceItemSummary.this,databaseHelper.getAllTransferenciasLines());
			listView.setAdapter(newTransferenceAdapter );
			listView.setCacheColorHint(Color.TRANSPARENT);

		}
    }
  
    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
        // Inflate the menu items for use in the action bar
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.calculatorandscan, menu);
        return super.onCreateOptionsMenu(menu);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) 
    {
        // Handle presses on the action bar items
    	  	int id = item.getItemId();
	    	if (id == R.id.refresh)
	    	{
	    		 Intent i = new Intent();
				 i.setClassName("com.sec.android.app.popupcalculator","com.sec.android.app.popupcalculator.Calculator");
				 startActivity(i);
	    		
	    	} else if (id == R.id.refresh) {

	    		progressDialog.dismiss(); 
	    		databaseHelper.deleteAllData();
	    		new LoadViewTaskRefresh().execute();  
	    		
	    	}
                    return super.onOptionsItemSelected(item);
        }
    
    
    @Override
    public void onResume() 
    {
        super.onResume();  
    	ListView listView = (ListView)findViewById(R.id.transferenciaslistview1);
		listView.setAdapter(null);

		newTransferenceAdapter  =new TransferenceAdapter1(TransferenceItemSummary.this,databaseHelper.getTransferenciasLines(PO));
	  	listView.setAdapter(newTransferenceAdapter);
		listView.setCacheColorHint(Color.TRANSPARENT);
		listView.setSelection(INDEX);
    }
    
    @Override
    public void onBackPressed()
    {
        //Toast.makeText(getApplicationContext(), "Para salir debe confirmar el cierre del inventario.", Toast.LENGTH_SHORT).show();
    	/* new AlertDialog.Builder(this)
         .setTitle("Salir de la Transferencia...")
         .setMessage("Estás seguro que deseas salir de la Transferencia?")
         .setNegativeButton(android.R.string.no, null)
         .setPositiveButton(android.R.string.yes, new OnClickListener() {

             public void onClick(DialogInterface arg0, int arg1) {
            	 TransferenceItemSummary .super.onBackPressed();
             }
         }).create().show();
    	
    	 }*/
    	finish();    
    	/*  new AlertDialog.Builder(this)
        .setIcon(android.R.drawable.ic_dialog_alert)
        .setTitle("Salir de la Transferencia...")
        .setMessage("Está seguro que desea salir de la Transferencia??")
        .setPositiveButton("Aceptar", new DialogInterface.OnClickListener()
    {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            finish();    
        }

    })
    .setNegativeButton("Cancelar", null)
    .show();*/
	 	    
   
    	
    }
	
}
