package com.example.waoperations.Shipping;




import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

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.bimsdk.usb.UsbConnect;
import com.bimsdk.usb.io.OnDataReceive;

import com.example.waoperations.FontsOverride;
import com.example.waoperations.R;
import com.example.waoperations.VoiceHelper;
import com.example.waoperations.Inventory.InventoryAdapterSummary;
import com.example.waoperations.Inventory.InventoryDatabaseHelper;
import com.example.waoperations.R.array;
import com.example.waoperations.R.color;
import com.example.waoperations.R.id;
import com.example.waoperations.R.layout;
import com.example.waoperations.R.menu;




import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.StrictMode;
import android.os.Vibrator;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.speech.RecognizerIntent;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class ShippingDetail extends Activity {
	  private static final int REQUEST_CODE = 1234;
	  StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
	  public int COUNTER =0;
	  public String PONUMBER;
	  public double pickedqty=0;
	  final Context context = this;
	  public String ID;
	  public String EXISTENTE,LOC,SKU,DATAAREAID,OFQTY,COUNTINGSTARTED,USERNAME,BOD;
	  private static final Pattern KEYCODE_PATTERN = Pattern.compile("KEYCODE_(\\w)");
	  public String Scanning="";
	  public int execute=0;
	    public EditText ED;
	  public int timerstarted=0;
	  
	  PickingAdapterSummary newPickingAdapterSummary;
	  private InventoryDatabaseHelper PickingSummaryDatabaseHelper;
	  
	  public Boolean timercompleted=false;
	  private ShippingDatabaseHelper databaseHelper;
	  
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		FontsOverride.setDefaultFont(this, "MONOSPACE", "fonts/opensans-light.ttf");
		setContentView(R.layout.washippingitem);
		databaseHelper = new ShippingDatabaseHelper(this.getApplicationContext()); 
	    ActionBar actionBar = getActionBar();
	    actionBar.hide();
	    // more stuff here...
	    actionBar.setSubtitle("Shipping");
	    actionBar.setTitle("Warehouse");
	    actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.ForestGreen)));
	    actionBar.setDisplayShowTitleEnabled(false);  // required to force redraw, without, gray color
	    actionBar.setDisplayShowTitleEnabled(true);
	    actionBar.setDisplayHomeAsUpEnabled(false);
	    actionBar.show(); 

		Intent intent = getIntent();
		this.PONUMBER = intent.getStringExtra("PO");
		this.EXISTENTE = intent.getStringExtra("EX");
		this.DATAAREAID = intent.getStringExtra("DATA");
		this.USERNAME = intent.getStringExtra("USER");
		this.BOD = intent.getStringExtra("BOD");
		
        EditText edittext = (EditText) this.findViewById(R.id.qtyamount);
        edittext.setText("");
        edittext.setClickable(false);
        edittext.setFocusable(false);
	    ED = (EditText) this.findViewById(R.id.qtyamount);

		 String[] paises = new String[]{"KR","CN","US","MX","GB","SV","TW","IT","DE","PL","IN","RU","IL","MS","CZ","BR","ID","FR","PL","CA","AR","CH","CY","MA","TR","at","ZA","ES","CO","JP","NL","TN","TH","tu","UA","UK","bg","IS","MY","BU","AU","RS","BA","VN","BE"};
   		 Spinner equipment = (Spinner) findViewById(R.id.countries);
   		 ArrayAdapter adapter2 = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, paises);
   		
   		 // Specify the layout to use when the list of choices appears
   		 adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
   		 // Apply the adapter to the spinner
   		 equipment.setAdapter(adapter2);

	    
   		PickingSummaryDatabaseHelper = new InventoryDatabaseHelper(context); 
   		  	final ListView listView = (ListView)findViewById(R.id.pickinglistviewinsideshipping);
   		 	listView.setAdapter(null);

   	     
   	 	    StrictMode.setThreadPolicy(policy); 
   	 	PickingSummaryDatabaseHelper.deleteAllData();
	    
	 	final TextView view = (TextView) findViewById(R.id.buscarheader);
		
		view.setOnClickListener(new View.OnClickListener() {
        //When you click the button, Alert dialog will be showed
        public void onClick(View v) {
       /* Alert Dialog Code Start*/ 	
        
        	AlertDialog.Builder alert = new AlertDialog.Builder(context);
        	alert.setTitle("Valide ítem"); //Set Alert dialog title here
        	alert.setMessage("Digite ítem:"); //Message here
 
            // Set an EditText view to get user input 
            final EditText input = new EditText(context);
            final AutoCompleteTextView text = new AutoCompleteTextView(context);
            
        	ArrayList<String> listItems=new ArrayList<String>();
            Cursor m = databaseHelper.getAllShippingLines();
            while(m.moveToNext()){
            	listItems.add(m.getString(2));
            }
            
 	        ArrayAdapter adapter = new ArrayAdapter<String>(ShippingDetail.this, android.R.layout.simple_list_item_activated_1, listItems);
           adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

  // Create an ArrayAdapter using the string array and a default spinner layout
		// Specify the layout to use when the list of choices appears
	// Apply the adapter to the spinner
		    text.setAdapter(adapter);
            alert.setView(text);
           
        	alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        	public void onClick(DialogInterface dialog, int whichButton) {
        	//You will get as string input data in this variable.
        	// here we convert the input to a string and show in a toast.
        	String srt = text.getEditableText().toString();
            Cursor cursor = databaseHelper.getShippingItem(PONUMBER,srt);
   	     if(cursor.getCount()>0){
   	     cursor.moveToFirst();
   	     ID= cursor.getString(0);
   	     TextView qtyreceived = (TextView) findViewById(R.id.article);
   	     TextView qty = (TextView) findViewById(R.id.ofqty);
   	     
   	   
   	     
   	     TextView cont = (TextView) findViewById(R.id.countryname);
   	     cont.setText("País: "+cursor.getString(6));
   	     qtyreceived.setText(cursor.getString(4));
   	     qty.setText("de "+cursor.getString(3)+" "+cursor.getString(5));
    	   
     	    view.setText(cursor.getString(2));
            view.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));	
   	    	COUNTER++;
	        EditText myEditText = (EditText) ED.findViewById(R.id.qtyamount);

			Double cant = Double.parseDouble(cursor.getString(3));
    		Double cantrec = Double.parseDouble(cursor.getString(4));
    		Double remaining= cant-cantrec;
    		NumberFormat nf = NumberFormat.getInstance();
    		
    		
	        nf.setMaximumFractionDigits(0);// set as you need
    		myEditText.setText(nf.format(remaining));
            myEditText.setClickable(true);
            myEditText.setFocusable(true);
            myEditText.setFocusableInTouchMode(true);
            myEditText.requestFocus();
   		    SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    		COUNTINGSTARTED = sd.format(new Date()); 
    		
    		  try{
       			
       			String result = null;
       	    	InputStream is = null;
       	  
       	    	String v1 = "'"+DATAAREAID+"'";
       			SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");


       		String v2 = "'"+BOD+"'"; 
       		String v3 = "'"+PONUMBER+"'"; 
      		String v4 = "'"+cursor.getString(2)+"'"; 

       	    	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
       	     	nameValuePairs.add(new BasicNameValuePair("empresa",v1));
       	    	nameValuePairs.add(new BasicNameValuePair("UID",v3));
       	 	nameValuePairs.add(new BasicNameValuePair("ITEMID",v4));
       	    	
       	//apartir de aqui carga ruta
       		try
       		{
       	    	        HttpClient httpclient = new DefaultHttpClient();
       	    	        HttpPost httppost = new HttpPost("http://10.10.100.13/getPickingNotProcessedLocationList.php");
       	    	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
       	    	        HttpResponse response = httpclient.execute(httppost); 
       	    	        HttpEntity entity = response.getEntity();
       	    	        is = entity.getContent();

       	    	        Log.e("log_tag", "connection success ");
       	    	     //   Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
       		}
       	catch(Exception e)
       		{
       	    	        Log.e("log_tag", "Error in http connection "+e.toString());
       	    	//        Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show();
       	    	//  	Toast.makeText(getApplicationContext(), "No se encuentra conectado a la red.Verifique conexiÃƒÂ³n de VPN.", Toast.LENGTH_SHORT).show();
       		}
       	    	//convert response to string
       		try{
       			
       	    	        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"ISO-8859-1"),8);
       	    	        StringBuilder sb = new StringBuilder();
       	    	        String line = null;
       	    	        while ((line = reader.readLine()) != null) 
       	    	        {
       	    	                sb.append(line + "\n");
       	    	        }
       	    	        is.close();
       	    	        result=sb.toString();
       		}
       		catch(Exception e)
       		{
       	    	       Log.e("log_tag", "Error converting result "+e.toString());
       		}
       	  	int counter=0;
 	    	//parse json data
 	    	try{
 	            //databaseHelper.deleteAllData();
 	    	  
 	    	   String locationold="";
 	    	double totalpicked=0;
 	    	 	JSONArray jArray = new JSONArray(result);
 	    		for(int i=0;i<jArray.length();i++)  
 	            {
 	    			try{
 	    		   	JSONObject no = jArray.getJSONObject(i);

 	    	        String COUNTED=no.getString("COUNTED");
 	    	      
 	    	       double receiveamount=0;
 	    		    try{
 	        		    Double Qt = Double.parseDouble(COUNTED);
 	        		    receiveamount=Qt;
 	        	
 		 	            nf.setMaximumFractionDigits(0);// set as you need
 		 	        COUNTED=nf.format(Qt).replace(",", "");
 	        		    
 	        		}catch(Exception e){}
 	    		    
 	    		    
 	      		    String loc=no.getString("WMSLOCATIONID");
 	      		    String sku=no.getString("ITEMID");
 	      	        String transdate=no.getString("TRANSDATE");
 	      	        if(loc.equals(locationold)){
 	      	        }
 	      	        else{
 	 	      	        totalpicked=totalpicked+receiveamount;	 	      	        	
 	      	        }
 	      	        
 	      	        locationold=loc;
 	      	        
 	      	        try{
 	      	        transdate=transdate.substring(9, 28);}catch(Exception e){}
 	      	        String countedby=no.getString("COUNTEDBY");
 	         	    PickingSummaryDatabaseHelper.saveInventoryLine(loc, sku, countedby+" "+transdate, COUNTED,"", "","", "");
 		            nf.setMaximumFractionDigits(0);// set as you need

 		            counter++;
 	    			}catch(Exception e)
 		          	{
 		          	}
 		            	 }
 	    		
 	    		
 	  	   ViewGroup.LayoutParams params = listView.getLayoutParams();
	       
			if(counter==0){
				params.height = 67;
				pickedqty=0;
			}else{
				params.height =67*counter;
				pickedqty=totalpicked;
				TextView qtyheader = (TextView) findViewById(R.id.qtyheader);
				qtyheader.setText("Cantidad: ("+totalpicked+" "+cursor.getString(5)+" alistadas.)");	
    			
			}
   			
   	 		listView.setLayoutParams(params);
   	 	    listView.requestLayout();
       	  
       	    	}
       	    	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.");
       		}
    		
    		  newPickingAdapterSummary = new PickingAdapterSummary(context,PickingSummaryDatabaseHelper.getInventoryItemLines(srt)); 			
    	    	 listView.setAdapter(newPickingAdapterSummary);

    		
   	     }else{
   	    	view.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));	
   	  	Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    	// Vibrate for 400 milliseconds
    	v.vibrate(400);
   	        COUNTER=0;
   	     }
        	} // End of onClick(DialogInterface dialog, int whichButton)
        }); //End of alert.setPositiveButton
        	alert.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
        	  public void onClick(DialogInterface dialog, int whichButton) {
        	  // Canceled.
        	  dialog.cancel();
        	  }
        }); //End of alert.setNegativeButton
        	AlertDialog alertDialog = alert.create();
        	alertDialog.show();
       /* Alert Dialog Code End*/        
     }// End of onClick(View v)
  });

		
		
		

		
		GetData();
		if (!UsbConnect.isConnect(this)) {
			UsbConnect.Connect(this);
		}
		
	}

	  @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);
	    }

	  public boolean onOptionsItemSelected(MenuItem item) {
	        // Handle presses on the action bar items
	        switch (item.getItemId()) {
	            case R.id.add:
	            	if(execute==0){
	                Intent intent = new Intent(
	      	        "com.google.zxing.client.android.SCAN");
	      	        startActivityForResult(intent, 0);
	                return true;
	            	}else{
	            		  if(Scanning.equals("")){}
						  else{
					             TextView buscarheader = (TextView) findViewById(R.id.buscarheader);
					    	     Cursor cursor = databaseHelper.getShippingItemBarcode(PONUMBER,Scanning);
					    	     if(cursor.getCount()>0){
					    	     cursor.moveToFirst();
					    	     ID= cursor.getString(0);
					    	     TextView qtyreceived = (TextView) findViewById(R.id.article);
					    	     TextView qty = (TextView) findViewById(R.id.ofqty);
					    	     qtyreceived.setText(cursor.getString(4));
					    	     qty.setText("de "+cursor.getString(3)+" "+cursor.getString(5));
					    	     TextView cont = (TextView) findViewById(R.id.countryname);
					       	     cont.setText("País: "+cursor.getString(6));
						       	 buscarheader.setText(cursor.getString(2));
					    	   	 buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));	
					    	   	 COUNTER++;
					    		 SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			                	 COUNTINGSTARTED = sd.format(new Date()); 
			                		 
			                		EditText myEditText = (EditText) ED.findViewById(R.id.qtyamount);
			                		Double cant = Double.parseDouble(cursor.getString(3));
			                		Double cantrec = Double.parseDouble(cursor.getString(4));
			                		Double remaining= cant-cantrec;
			                		NumberFormat nf = NumberFormat.getInstance();
			        		        nf.setMaximumFractionDigits(0);// set as you need
			                		myEditText.setText(nf.format(remaining));
			                        myEditText.setClickable(true);
			                        myEditText.setFocusable(true);
			                        myEditText.setFocusableInTouchMode(true);
			                        myEditText.requestFocus();
			                        
			            		  	final ListView listView = (ListView)findViewById(R.id.pickinglistviewinsideshipping);
			               		 	listView.setAdapter(null);

			               	     
			               	 	    StrictMode.setThreadPolicy(policy); 
			               	 	PickingSummaryDatabaseHelper.deleteAllData();
			               	 	
			                  	  try{
			                 			
			                 			String result = null;
			                 	    	InputStream is = null;
			                 	  
			                 	    	String v1 = "'"+DATAAREAID+"'";
			                 			SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");


			                 		String v2 = "'"+BOD+"'"; 
			                 		String v3 = "'"+PONUMBER+"'"; 
			                		String v4 = "'"+cursor.getString(2)+"'"; 

			                 	    	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			                 	     	nameValuePairs.add(new BasicNameValuePair("empresa",v1));
			                 	    	nameValuePairs.add(new BasicNameValuePair("UID",v3));
			                 	 	nameValuePairs.add(new BasicNameValuePair("ITEMID",v4));
			                 	    	
			                 	//apartir de aqui carga ruta
			                 		try
			                 		{
			                 	    	        HttpClient httpclient = new DefaultHttpClient();
			                 	    	        HttpPost httppost = new HttpPost("http://10.10.100.13/getPickingNotProcessedLocationList.php");
			                 	    	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			                 	    	        HttpResponse response = httpclient.execute(httppost); 
			                 	    	        HttpEntity entity = response.getEntity();
			                 	    	        is = entity.getContent();

			                 	    	        Log.e("log_tag", "connection success ");
			                 	    	     //   Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
			                 		}
			                 	catch(Exception e)
			                 		{
			                 	    	        Log.e("log_tag", "Error in http connection "+e.toString());
			                 	    	//        Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show();
			                 	    	//  	Toast.makeText(getApplicationContext(), "No se encuentra conectado a la red.Verifique conexiÃƒÂ³n de VPN.", Toast.LENGTH_SHORT).show();
			                 		}
			                 	    	//convert response to string
			                 		try{
			                 			
			                 	    	        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"ISO-8859-1"),8);
			                 	    	        StringBuilder sb = new StringBuilder();
			                 	    	        String line = null;
			                 	    	        while ((line = reader.readLine()) != null) 
			                 	    	        {
			                 	    	                sb.append(line + "\n");
			                 	    	        }
			                 	    	        is.close();
			                 	    	        result=sb.toString();
			                 		}
			                 		catch(Exception e)
			                 		{
			                 	    	       Log.e("log_tag", "Error converting result "+e.toString());
			                 		}
			                 	int counter=0;
			                 	    	//parse json data
			                 	    	try{
			                 	            //databaseHelper.deleteAllData();
			                 	    	  
			                 	    	   String locationold="";
			                 	    	double totalpicked=0;
			                 	    	 	JSONArray jArray = new JSONArray(result);
			                 	    		for(int i=0;i<jArray.length();i++)  
			                 	            {
			                 	    			try{
			                 	    		   	JSONObject no = jArray.getJSONObject(i);

			                 	    	        String COUNTED=no.getString("COUNTED");
			                 	    	      
			                 	    	       double receiveamount=0;
			                 	    		    try{
			                 	        		    Double Qt = Double.parseDouble(COUNTED);
			                 	        		    receiveamount=Qt;
			                 	        	
			                 		 	            nf.setMaximumFractionDigits(0);// set as you need
			                 		 	        COUNTED=nf.format(Qt).replace(",", "");
			                 	        		    
			                 	        		}catch(Exception e){}
			                 	    		    
			                 	    		    
			                 	      		    String loc=no.getString("WMSLOCATIONID");
			                 	      		    String sku=no.getString("ITEMID");
			                 	      	        String transdate=no.getString("TRANSDATE");
			                 	      	        if(loc.equals(locationold)){
			                 	      	        }
			                 	      	        else{
			                 	 	      	        totalpicked=totalpicked+receiveamount;	 	      	        	
			                 	      	        }
			                 	      	        
			                 	      	        locationold=loc;
			                 	      	        
			                 	      	        try{
			                 	      	        transdate=transdate.substring(9, 28);}catch(Exception e){}
			                 	      	        String countedby=no.getString("COUNTEDBY");
			                 	         	    PickingSummaryDatabaseHelper.saveInventoryLine(loc, sku, countedby+" "+transdate, COUNTED,"", "","", "");
			                 		            nf.setMaximumFractionDigits(0);// set as you need

			                 		            counter++;
			                 	    			}catch(Exception e)
			                 		          	{
			                 		          	}
			                 		            	 }
			                 	    		
			                 	    		
			                 	  	   ViewGroup.LayoutParams params = listView.getLayoutParams();
			          		       
			             			if(counter==0){
			             				params.height = 67;
			             				pickedqty=0;
			             			}else{
			             				params.height =67*counter;
			             				pickedqty=totalpicked;
			             				TextView qtyheader = (TextView) findViewById(R.id.qtyheader);
			            				qtyheader.setText("Cantidad: ("+totalpicked+" "+cursor.getString(5)+" alistadas.)");	
			            			
			             			}
			             			

			             	 		listView.setLayoutParams(params);
			             	 	    listView.requestLayout();
			                 	  
			                 	    	}
			                 	    	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.");
			                 		}
			              		
			              		  newPickingAdapterSummary = new PickingAdapterSummary(context,PickingSummaryDatabaseHelper.getInventoryItemLines(cursor.getString(2))); 			
			              	    	 listView.setAdapter(newPickingAdapterSummary);

			                        
			                        
			                        
			                        
					    	     }else{
					    	     buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));	
					    	  	 Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		                    	 // Vibrate for 400 milliseconds
		                    	 v.vibrate(400);
					    	     COUNTER=0;
					    	     execute=0;
					    	     Scanning="";
	            		
	            	}}}
	            case R.id.refresh:
	           	 if(execute==0){
            		 Intent i = new Intent(); 
                     i.setClassName("com.sec.android.app.popupcalculator","com.sec.android.app.popupcalculator.Calculator"); 
                  startActivity(i);
                  
            	 }else{
           		  if(Scanning.equals("")){}
					  else{

				             TextView buscarheader = (TextView) findViewById(R.id.buscarheader);
				    	     Cursor cursor = databaseHelper.getShippingItemBarcode(PONUMBER,Scanning);
				    	     if(cursor.getCount()>0){
				    	     cursor.moveToFirst();
				    	     ID= cursor.getString(0);
				    	     TextView qtyreceived = (TextView) findViewById(R.id.article);
				    	     TextView qty = (TextView) findViewById(R.id.ofqty);
				    	     qtyreceived.setText(cursor.getString(4));
				    	     qty.setText("de "+cursor.getString(3)+" "+cursor.getString(5));
				    	     TextView cont = (TextView) findViewById(R.id.countryname);
				       	     cont.setText("PaÃƒÂ­s: "+cursor.getString(6));
					       	 buscarheader.setText(cursor.getString(2));
				    	   	 buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));	
				    	   	 COUNTER++;
				    		    SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		                		COUNTINGSTARTED = sd.format(new Date()); 
		                        EditText myEditText = (EditText) ED.findViewById(R.id.qtyamount);
		                		Double cant = Double.parseDouble(cursor.getString(3));
		                		Double cantrec = Double.parseDouble(cursor.getString(4));
		                		Double remaining= cant-cantrec;
		                		NumberFormat nf = NumberFormat.getInstance();
		        		        nf.setMaximumFractionDigits(0);// set as you need
		                		myEditText.setText(nf.format(remaining));
		                		
		                        myEditText.setClickable(true);
		                        myEditText.setFocusable(true);
		                        myEditText.setFocusableInTouchMode(true);
		                        myEditText.requestFocus();

		                      	final ListView listView = (ListView)findViewById(R.id.pickinglistviewinsideshipping);
		               		 	listView.setAdapter(null);

		               	 	    StrictMode.setThreadPolicy(policy); 
		               	 	PickingSummaryDatabaseHelper.deleteAllData();
		               	 	
		                  	  try{
		                 			
		                 			String result = null;
		                 	    	InputStream is = null;
		                 	  
		                 	    	String v1 = "'"+DATAAREAID+"'";
		                 			SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");


		                 		String v2 = "'"+BOD+"'"; 
		                 		String v3 = "'"+PONUMBER+"'"; 
		                		String v4 = "'"+cursor.getString(2)+"'"; 

		                 	    	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		                 	     	nameValuePairs.add(new BasicNameValuePair("empresa",v1));
		                 	    	nameValuePairs.add(new BasicNameValuePair("UID",v3));
		                 	 	nameValuePairs.add(new BasicNameValuePair("ITEMID",v4));
		                 	    	
		                 	//apartir de aqui carga ruta
		                 		try
		                 		{
		                 	    	        HttpClient httpclient = new DefaultHttpClient();
		                 	    	        HttpPost httppost = new HttpPost("http://10.10.100.13/getPickingNotProcessedLocationList.php");
		                 	    	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		                 	    	        HttpResponse response = httpclient.execute(httppost); 
		                 	    	        HttpEntity entity = response.getEntity();
		                 	    	        is = entity.getContent();

		                 	    	        Log.e("log_tag", "connection success ");
		                 	    	     //   Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
		                 		}
		                 	catch(Exception e)
		                 		{
		                 	    	        Log.e("log_tag", "Error in http connection "+e.toString());
		                 	    	//        Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show();
		                 	    	//  	Toast.makeText(getApplicationContext(), "No se encuentra conectado a la red.Verifique conexiÃƒÂ³n de VPN.", Toast.LENGTH_SHORT).show();
		                 		}
		                 	    	//convert response to string
		                 		try{
		                 			
		                 	    	        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"ISO-8859-1"),8);
		                 	    	        StringBuilder sb = new StringBuilder();
		                 	    	        String line = null;
		                 	    	        while ((line = reader.readLine()) != null) 
		                 	    	        {
		                 	    	                sb.append(line + "\n");
		                 	    	        }
		                 	    	        is.close();
		                 	    	        result=sb.toString();
		                 		}
		                 		catch(Exception e)
		                 		{
		                 	    	       Log.e("log_tag", "Error converting result "+e.toString());
		                 		}
		                 	  	int counter=0;
	                 	    	//parse json data
	                 	    	try{
	                 	            //databaseHelper.deleteAllData();
	                 	    	  
	                 	    	   String locationold="";
	                 	    	double totalpicked=0;
	                 	    	 	JSONArray jArray = new JSONArray(result);
	                 	    		for(int i=0;i<jArray.length();i++)  
	                 	            {
	                 	    			try{
	                 	    		   	JSONObject no = jArray.getJSONObject(i);

	                 	    	        String COUNTED=no.getString("COUNTED");
	                 	    	      
	                 	    	       double receiveamount=0;
	                 	    		    try{
	                 	        		    Double Qt = Double.parseDouble(COUNTED);
	                 	        		    receiveamount=Qt;
	                 	        	
	                 		 	            nf.setMaximumFractionDigits(0);// set as you need
	                 		 	        COUNTED=nf.format(Qt).replace(",", "");
	                 	        		    
	                 	        		}catch(Exception e){}
	                 	    		    
	                 	    		    
	                 	      		    String loc=no.getString("WMSLOCATIONID");
	                 	      		    String sku=no.getString("ITEMID");
	                 	      	        String transdate=no.getString("TRANSDATE");
	                 	      	        if(loc.equals(locationold)){
	                 	      	        }
	                 	      	        else{
	                 	 	      	        totalpicked=totalpicked+receiveamount;	 	      	        	
	                 	      	        }
	                 	      	        
	                 	      	        locationold=loc;
	                 	      	        
	                 	      	        try{
	                 	      	        transdate=transdate.substring(9, 28);}catch(Exception e){}
	                 	      	        String countedby=no.getString("COUNTEDBY");
	                 	         	    PickingSummaryDatabaseHelper.saveInventoryLine(loc, sku, countedby+" "+transdate, COUNTED,"", "","", "");
	                 		            nf.setMaximumFractionDigits(0);// set as you need

	                 		            counter++;
	                 	    			}catch(Exception e)
	                 		          	{
	                 		          	}
	                 		            	 }
	                 	    		
	                 	    		
	                 	  	   ViewGroup.LayoutParams params = listView.getLayoutParams();
	          		       
	             			if(counter==0){
	             				params.height = 67;
	             				pickedqty=0;
	             			}else{
	             				params.height =67*counter;
	             				pickedqty=totalpicked;
	             				TextView qtyheader = (TextView) findViewById(R.id.qtyheader);
	             				qtyheader.setText("Cantidad: ("+totalpicked+" "+cursor.getString(5)+" alistadas.)");	
		            			
	             			}
		             			
		             	 		listView.setLayoutParams(params);
		             	 	    listView.requestLayout();
		                 	  
		                 	    	}
		                 	    	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.");
		                 		}
		              		
		              		  newPickingAdapterSummary = new PickingAdapterSummary(context,PickingSummaryDatabaseHelper.getInventoryItemLines(cursor.getString(2))); 			
		              	    	 listView.setAdapter(newPickingAdapterSummary);

				    	     }else{
				    	     buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));	
				    	  	 Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
	                    	 // Vibrate for 400 milliseconds
	                    	 v.vibrate(400);
	                 
				    	     COUNTER=0;
				    	     execute=0;
				    	     Scanning="";
           	}}}
	            	

	            default:
	                return super.onOptionsItemSelected(item);
	        }
	    }
	    
	  @SuppressWarnings("deprecation")
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
			 if (requestCode == 0) {
				    if (resultCode == RESULT_OK) {
                       
				     final String  contents = data.getStringExtra("SCAN_RESULT"); // This will contain your scan result
		             String format = data.getStringExtra("SCAN_RESULT_FORMAT");
		             TextView buscarheader = (TextView) this.findViewById(R.id.buscarheader);
		    	     Cursor cursor = databaseHelper.getShippingItemBarcode(PONUMBER,contents);
		    	     if(cursor.getCount()>0){
		    	     cursor.moveToFirst();
		    	     ID= cursor.getString(0);
		    	     TextView qtyreceived = (TextView) this.findViewById(R.id.article);
		    	     TextView qty = (TextView) this.findViewById(R.id.ofqty);
		    	     
		    	     qtyreceived.setText(cursor.getString(4));
		    	     qty.setText("de "+cursor.getString(3)+" "+cursor.getString(5));
		     	    
			       	 buscarheader.setText(cursor.getString(2));

		    	   	 buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));	
		    	   	 COUNTER++;
		    	        EditText myEditText = (EditText) ED.findViewById(R.id.qtyamount);
	                    myEditText.setClickable(true);
	                    myEditText.setFocusable(true);
	                    myEditText.setFocusableInTouchMode(true);
	                    myEditText.requestFocus();
		    		    SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                		COUNTINGSTARTED = sd.format(new Date()); 	
		    	     }else{
		    	     buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));
		    	  	Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                	// Vibrate for 400 milliseconds
                	v.vibrate(400);
		    	     COUNTER=0;
		    	     }

		            
				    }
				    
		 }}

	public void onComplete(View view) {  
				
		         if(COUNTER==0){
		       	Toast.makeText(getApplicationContext(), "Escanee o digite artículo a enviar.", Toast.LENGTH_SHORT).show();
				   Intent intentemoslo = new Intent(getApplicationContext() ,VoiceHelper.class);
     			   intentemoslo.putExtra("voz","Escanee o digite artículo a enviar");  
     			   startService(intentemoslo);	
     				Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                	// Vibrate for 400 milliseconds
                	v.vibrate(400);
		         }else{
		         EditText edittext = (EditText) this.findViewById(R.id.qtyamount);
		         TextView qtyreceived = (TextView) this.findViewById(R.id.article);
		         if(COUNTER==1){
		        	 
		        	 
		        	 
		        	//ACÃƒï¿½ VA LA NUEVA REVISIÃƒâ€œN 

		             Boolean TERMINUS=false;
		 		if(this.hasContent(edittext)==true){
		 		
		 			Cursor po = databaseHelper.getItemByID(ID);
	 				po.moveToFirst();
	 				
		 		    NumberFormat nf = NumberFormat.getInstance();
		            nf.setMaximumFractionDigits(0);// set as you need
		            
		 			Double totalreceived=Double.parseDouble(edittext.getText().toString().trim())+Double.parseDouble(qtyreceived.getText().toString().trim());
		 			if(totalreceived>pickedqty){
		 		 		AlertDialog.Builder alert = new AlertDialog.Builder(context);
		 	        	alert.setTitle("Shipping"); //Set Alert dialog title here
		 	        	alert.setMessage("La cantidad a enviar no puede exceder la cantidad alistada."); //Message here
		 	            // Set an EditText view to get user input 
		 	        	alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
		 	        	public void onClick(DialogInterface dialog, int whichButton) {
		 	        	//You will get as string input data in this variable.
		 	        	// here we convert the input to a string and show in a toast.
		 	     
		 	   
		 	        	} // End of onClick(DialogInterface dialog, int whichButton)

		 	        }); //End of alert.setNegativeButton
		 	        	AlertDialog alertDialog = alert.create();
		 	        	alertDialog.show();
		 	   	
		 			}else
		 			if(totalreceived>Double.parseDouble(po.getString(3))){
		 			  	Toast.makeText(getApplicationContext(), "La cantidad a enviar no puede exceder el límite establecido.", Toast.LENGTH_SHORT).show();	 
						   Intent intentemoslo = new Intent(getApplicationContext() ,VoiceHelper.class);
		     			   intentemoslo.putExtra("voz","La cantidad a enviar no puede exceder el lÃƒÂ­mite establecido");  
		     			   startService(intentemoslo);	
		     				Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		                	// Vibrate for 400 milliseconds
		                	v.vibrate(400);	

		 			}else{
		 			databaseHelper.UpdateShippingItem(nf.format(totalreceived).replace(",", ""), ID);
		 			Spinner paises = (Spinner)findViewById(R.id.countries);
		 	        String paisrec = paises.getSelectedItem().toString();
		 			try{
		 				Cursor n = databaseHelper.getItemByID(ID);
		 				n.moveToFirst();
		 				
		 			 	String result = null;
		 			 	InputStream is = null;
		 			 	
		                //Double diferencia=Double.parseDouble(n.getString(7))-Double.parseDouble(n.getString(5));
		                NumberFormat format = NumberFormat.getInstance();
		                format.setMaximumFractionDigits(0);// set as you need
		        		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			    		String dat = sd.format(new Date()); 
			    		
		 			 	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		 			  	nameValuePairs.add(new BasicNameValuePair("COUNT","'"+n.getString(4)+"'"));
		 			  	//SUBE ON HAND NO DIFERENCIA
		 			 	nameValuePairs.add(new BasicNameValuePair("IOH","'"+n.getString(3)+"'"));
		 			    nameValuePairs.add(new BasicNameValuePair("EMP","'"+DATAAREAID+"'"));
		 			  	nameValuePairs.add(new BasicNameValuePair("LINE","'"+n.getString(10)+"'"));
		 			    nameValuePairs.add(new BasicNameValuePair("SKU","'"+n.getString(2)+"'"));
		 			    nameValuePairs.add(new BasicNameValuePair("DATE","'"+dat+"'"));
		 			    nameValuePairs.add(new BasicNameValuePair("BEGINDATE","'"+COUNTINGSTARTED+"'"));
		 			    nameValuePairs.add(new BasicNameValuePair("USER","'"+USERNAME+"'"));
		 			    nameValuePairs.add(new BasicNameValuePair("PO","'"+PONUMBER+"'"));
		 			    nameValuePairs.add(new BasicNameValuePair("ORDERID","'"+n.getString(11)+"'"));
		 			    nameValuePairs.add(new BasicNameValuePair("CON","'"+n.getString(6)+"'"));
		 			    nameValuePairs.add(new BasicNameValuePair("CONREC","'"+paisrec+"'"));
		 			    StrictMode.setThreadPolicy(policy); 
		 			        	//http post
		 			        	try{
		 			        	        HttpClient httpclient = new DefaultHttpClient();
		 			        	        HttpPost httppost = new HttpPost("http://10.10.100.13/UpdateShippingList.php");
		 			        	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		 			        	        HttpResponse response = httpclient.execute(httppost); 
		 			        	        HttpEntity entity = response.getEntity();
		 			        	        is = entity.getContent();
		 			        	        Log.e("log_tag", "connection success ");
		 			        	       TERMINUS=true;  
		 			        	      //  Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
		 			        	   }
		 			        	catch(Exception e)
		 			        	{
		 			        		  TERMINUS=false;
		 			        	        Log.e("log_tag", "Error in http connection "+e.toString());
		 			        	        Toast.makeText(getApplicationContext(), "Error de conexión", Toast.LENGTH_SHORT).show();
		 			        	}
		 			        	//convert response to string
		 			        	try{
		 			        	        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
		 			        	        StringBuilder sb = new StringBuilder();
		 			        	        String line = null;
		 			        	        while ((line = reader.readLine()) != null) 
		 			        	        {
		 			        	                sb.append(line + "\n");
		 			        	        }
		 			        	        is.close();
		 			        	        result=sb.toString();
		 			        	}
		 			        	catch(Exception e)
		 			        	{
		 			        	       Log.e("log_tag", "Error converting result "+e.toString());
		 			           	}
		 			        	try{
		 			        	            	JSONObject json_data = new JSONObject(result);
		 			        	            	
		 			        	                //CharSequence w= (CharSequence) json_data.get("re");
		 			        	  			//    Toast toasta=Toast.makeText(getApplicationContext(), w, 2000);
		 							  	      //  toasta.setGravity(Gravity.CENTER,0,0);
		 							  	    //    toasta.show();	
		 			        	     }
		 			        	catch(JSONException e)
		 			        	   {
		 			        	        Log.e("log_tag", "Error parsing data "+e.toString());
		 			        	     //   Toast.makeText(getApplicationContext(), "JsonArray fail", Toast.LENGTH_SHORT).show();
		 			        	    }}catch(Exception e){}
		 					        	
		 					        
		 			 if(TERMINUS){
			 		       Toast.makeText(getApplicationContext(), "Artículo enviado.", Toast.LENGTH_SHORT).show();	 
						   Intent intentemoslo = new Intent(getApplicationContext() ,VoiceHelper.class);
		     			   intentemoslo.putExtra("voz","Artículo enviado");  
		     				edittext.setText("0");
		     			   startService(intentemoslo);	
			 			 }
	     			   
	     			  try{
	     					
	     					String result = null;
	     			    	InputStream is = null;
	     			  
	     			    	String v1 = "'"+DATAAREAID+"'";
	     					SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");
	     				    String v3 = "'"+PONUMBER+"'"; 

	     			    	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
	     			     	nameValuePairs.add(new BasicNameValuePair("empresa",v1));
	     			    	nameValuePairs.add(new BasicNameValuePair("UID",v3));
	     			    	
	     			//apartir de aqui carga ruta
	     				try
	     				{
	     			    	        HttpClient httpclient = new DefaultHttpClient();
	     			    	        HttpPost httppost = new HttpPost("http://10.10.100.13/getShippingNotProcessedList.php");
	     			    	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
	     			    	        HttpResponse response = httpclient.execute(httppost); 
	     			    	        HttpEntity entity = response.getEntity();
	     			    	        is = entity.getContent();

	     			    	        Log.e("log_tag", "connection success ");
	     			    	     //   Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
	     				}
	     			catch(Exception e)
	     				{
	     			    	        Log.e("log_tag", "Error in http connection "+e.toString());
	     			    	//        Toast.makeText(getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show();
	     			    	  	Toast.makeText(getApplicationContext(), "No se encuentra conectado a la red.Verifique conexiÃƒÂ³n de VPN.", Toast.LENGTH_SHORT).show();
	     				}
	     			    	//convert response to string
	     				try{
	     					
	     			    	        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"ISO-8859-1"),8);
	     			    	        StringBuilder sb = new StringBuilder();
	     			    	        String line = null;
	     			    	        while ((line = reader.readLine()) != null) 
	     			    	        {
	     			    	                sb.append(line + "\n");
	     			    	        }
	     			    	        is.close();
	     			    	        result=sb.toString();
	     				}
	     				catch(Exception e)
	     				{
	     			    	       Log.e("log_tag", "Error converting result "+e.toString());
	     				}
	     			int counter=0;
	     			    	//parse json data
	     			    	try{
	     			            //databaseHelper.deleteAllData();

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

	     			    	        String COUNTED=no.getString("COUNTED");
	     			    	        String orderid=no.getString("ORDERID");
	     			    
	     			    	        double receiveamount=0;
	     			    		    try{
	     			        		    Double Qt = Double.parseDouble(COUNTED);
	     			        		    receiveamount=Qt;
	     			        		    NumberFormat nf3 = NumberFormat.getInstance();
	     				 	            nf3.setMaximumFractionDigits(0);// set as you need
	     				 	        COUNTED=nf3.format(Qt).replace(",", "");
	     			        		    
	     			        		}catch(Exception e){}
	     			      		    String itrans=no.getString("INVENTDIMID");
	     			      		    String itemid=no.getString("ITEMID");
	     				            NumberFormat nf2 = NumberFormat.getInstance();
	     				            nf2.setMaximumFractionDigits(0);// set as you need
	     				        	Cursor xyz =databaseHelper.getItemDetail(PONUMBER,itrans,itemid,orderid);
	     				    		if(xyz.getCount()>0){
	     				    		xyz.moveToFirst();
	     			                databaseHelper.UpdateShippingItem(COUNTED, xyz.getString(0));
	     			                }
	     				            counter++;
	     			    			}catch(Exception e)
	     				          	{
	     				          	}
	     				            	 }
	     			  
	     			    	}
	     			    	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.");
	     				}
	     			   
	     			try {
	     		
	     			} catch (Exception e) {
	     			    e.printStackTrace();
	     			}

		 			
	     			if(TERMINUS){     	
	   		 		 this.recreate();
	   	     			}else{
	   	     				
	   	     				 new AlertDialog.Builder(context)
	   		     			    .setTitle("Error de conexión")
	   		     			    .setMessage(" Verifique que esté conectado a la red e intente de nuevo.")
	   		     			    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
	   		     			        public void onClick(DialogInterface dialog, int which) { 
	   		     			            // continue with delete
	   		     			        }
	   		     			     })
	   		     			    .setNegativeButton("CANCELAR", new DialogInterface.OnClickListener() {
	   		     			        public void onClick(DialogInterface dialog, int which) { 
	   		     			            // do nothing
	   		     			        }
	   		     			     })
	   		     			    .setIcon(android.R.drawable.ic_dialog_alert)
	   		     			     .show();
	   		     				 
	   		     				   Intent intentemoslo = new Intent(getApplicationContext() ,VoiceHelper.class);
	   			     			   intentemoslo.putExtra("voz","Error de conexión. Verifique que esté conectado a la red e intente de nuevo.");  
	   			     			   startService(intentemoslo);	
	   			     				Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
	   			                	// Vibrate for 400 milliseconds
	   			                	v.vibrate(400);
	   	     			}}
		 		}else{	

				       	Toast.makeText(getApplicationContext(), "Digite la cantidad para avanzar.", Toast.LENGTH_SHORT).show();	 
						   Intent intentemoslo = new Intent(getApplicationContext() ,VoiceHelper.class);
		     			   intentemoslo.putExtra("voz","Digite la cantidad para avanzar");  
		     			   startService(intentemoslo);	
		     				Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		                	// Vibrate for 400 milliseconds
		                	v.vibrate(400);
		         }
		         }}
				}	  
		    
			private boolean hasContent(EditText et) {
			       return (et.getText().toString().trim().length() > 0);
			}
	  
			@Override
			public boolean onKeyDown(int keyCode, KeyEvent event) {
					
				    	execute=1;
				    	
				        String key = KeyEvent.keyCodeToString(keyCode);
				        
				        // key will be something like "KEYCODE_A" - extract the "A"

				        // use pattern to convert int keycode to some character
				        Matcher matcher = KEYCODE_PATTERN.matcher(key);
				        
				        if (matcher.matches()) {
				            // append character to textview
				        	 Scanning=Scanning+matcher.group(1);
				        //	Toast.makeText(getApplicationContext(), "No se encuentra conectado a la red.Verifique conexiÃƒÂ³n de VPN.", Toast.LENGTH_SHORT).show();
				          //
				        }
				        // let the default implementation handle the event
				 
				        return super.onKeyDown(keyCode, event);
				    }
					
			private void GetData() {
				
				//Receive data from bluetooth scanner
			
			
				UsbConnect.SetOnDataReceive(new OnDataReceive() {
					@Override
					public void DataReceive(byte[] data , boolean flg) {
					
						
					    Scanning=Scanning+new String(data).trim();
						 
						  if(timerstarted==0&&(Scanning.equals("")==false)){
							  timerstarted=1;
						 	new CountDownTimer(300, 300) {       
								   public void onTick(long millisUntilFinished) {          
								}       

								public void onFinish() {  timercompleted=true; 	
								if(timercompleted==true){	
						
						
					  if(Scanning.equals("")){}
					  else{
					  
			
				             TextView buscarheader = (TextView) findViewById(R.id.buscarheader);
				    	     Cursor cursor = databaseHelper.getShippingItemBarcode(PONUMBER,Scanning);
				    	     if(cursor.getCount()>0){
				    	     cursor.moveToFirst();
				    	     ID= cursor.getString(0);
				    	     TextView qtyreceived = (TextView) findViewById(R.id.article);
				    	     TextView qty = (TextView) findViewById(R.id.ofqty);
				    	     qtyreceived.setText(cursor.getString(4));
				    	     qty.setText("of "+cursor.getString(3)+" "+cursor.getString(5));
					       	 buscarheader.setText(cursor.getString(2));
				    	   	 buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.GreenYellow)));	
				    	   	 COUNTER++;
				    	        EditText myEditText = (EditText) ED.findViewById(R.id.qtyamount);
			                    myEditText.setClickable(true);
			                    myEditText.setFocusable(true);
			                    myEditText.setFocusableInTouchMode(true);
			                    myEditText.requestFocus();
				    		    SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				    			COUNTINGSTARTED = sd.format(new Date()); 	
				    	     }else{
				    	     buscarheader.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.IndianRed)));	
				    	  	 Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
	                    	 // Vibrate for 400 milliseconds
	                    	 v.vibrate(400);
				    	     COUNTER=0;
				    	     }
						  
						  
					  }
	                  timerstarted=0;
		      	      Scanning="";
		      	      timercompleted=false;
				  }
				
			
			
			
			}}.start();  
			}
	  }

					
				});

			}
		 
		
}
