package com.example.waoperations.Receiving;

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 com.example.waoperations.Shipping.ShippingDatabaseHelper;




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.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class ReceivingDetail 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;
	  final Context context = this;
	  public String ID;
	  public String EXISTENTE,LOC,SKU,DATAAREAID,OFQTY,COUNTINGSTARTED,USERNAME;
	  private static final Pattern KEYCODE_PATTERN = Pattern.compile("KEYCODE_(\\w)");
	  public String Scanning="";
	  public int execute=0;
	  public EditText ED;
	  public int timerstarted=0;
	  public Boolean timercompleted=false;
	  private ReceivingDatabaseHelper databaseHelper;
      private InventoryDatabaseHelper InvDatabaseHelper;
      InventoryAdapterSummary newInventoryAdapter;
      
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		FontsOverride.setDefaultFont(this, "MONOSPACE", "fonts/opensans-light.ttf");
		setContentView(R.layout.wareceivingitem);
		databaseHelper = new ReceivingDatabaseHelper(this.getApplicationContext()); 
	    ActionBar actionBar = getActionBar();
	    actionBar.hide();
	    // more stuff here...
	    actionBar.setSubtitle("Receiving");
	    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");
		InvDatabaseHelper = new InventoryDatabaseHelper(this.getApplicationContext()); 
		InvDatabaseHelper.deleteAllData();
	    
		
		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);
		
		
      EditText edittext = (EditText) this.findViewById(R.id.qtyamount);
      edittext.setText("");
      edittext.setClickable(false);
      edittext.setFocusable(false);
	    ED = (EditText) this.findViewById(R.id.qtyamount);

	    
	 	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("Validación manual"); //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);
          alert.setView(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.
      	String srt = input.getEditableText().toString().toUpperCase();
          Cursor cursor = databaseHelper.getReceivingItem(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);
 	     
 	     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);
          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()); 
  		

	     InvDatabaseHelper = new InventoryDatabaseHelper(context); 
	  	ListView listView = (ListView)findViewById(R.id.inventorylistviewinsideputaway);
	 	listView.setAdapter(null);
    
	    StrictMode.setThreadPolicy(policy); 
	   InvDatabaseHelper.deleteAllData();
		try{
				
			String result = null;
	        InputStream is = null;
	      
	        String v1 = "'"+DATAAREAID+"'";
	    	SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");
	    	String v2 = "'BOD_01'";
			String v3 = "'"+srt+"'"; 

	        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
	        nameValuePairs.add(new BasicNameValuePair("empresa",v1));
	        nameValuePairs.add(new BasicNameValuePair("bodega",v2));
	        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/getLocationsRemaining.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());
	       // 	    Toast.makeText(getApplicationContext(), " Input reading fail", Toast.LENGTH_SHORT).show();
	   	}
	int COUNT=0;
	        	//parse json data
	        	try{

	        	 	JSONArray jArray = new JSONArray(result);
	        		for(int i=0;i<jArray.length();i++)  
		        {
	        			COUNT++;
	        			try{
	        		   	JSONObject no = jArray.getJSONObject(i);    
	        		    String loc=no.getString("Location");
	        		    String sku=no.getString("itemID");
	        	        String qty2=no.getString("qty");
	        		    try{
	        		    Double Qt = Double.parseDouble(qty2);
	        		    NumberFormat nf = NumberFormat.getInstance();
		 	            nf.setMaximumFractionDigits(0);// set as you need
		 	           qty2=nf.format(Qt).replace(",", "");
	        		    }catch(Exception e){}
	        		    
	        		    String type=no.getString("dim");
	        		   InvDatabaseHelper.saveInventoryLine(loc, sku, "", qty2, type, "","", "");
	 	            	}
	        	catch(JSONException e)
	        	{
	        	Log.e("log_tag", "Error parsing data "+e.toString()+Integer.toString(COUNT));
	        	}
	        			
	        			   ViewGroup.LayoutParams params = listView.getLayoutParams();
	        		       
	        			if(COUNT==0){
	        				params.height = 67;
	        			}else{
	        				params.height =67*COUNT;}
	        			
	        	 		listView.setLayoutParams(params);
	        	 	    listView.requestLayout();
		        }}
	        	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.");
	        	}
	
	
		 newInventoryAdapter = new InventoryAdapterSummary(context,InvDatabaseHelper.getInventoryItemLines(srt)); 			
   	 listView.setAdapter(newInventoryAdapter);
   	
 		 
  		
  		
 	     }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("CANCELAR", 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");
	      	        //intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
	      	        startActivityForResult(intent, 0);
	                return true;
	            	}else{
	            		  if(Scanning.equals("")){}
						  else{
							  String NOMBRESKU="";
				
					             TextView buscarheader = (TextView) findViewById(R.id.buscarheader);
					    	     Cursor cursor = databaseHelper.getReceivingItemBarcode(PONUMBER,Scanning);
					    	     if(cursor.getCount()>0){
					    	     cursor.moveToFirst();
				
						    	 NOMBRESKU=cursor.getString(2);
					    	     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++;
					    		    SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			                		COUNTINGSTARTED = sd.format(new Date()); 
			                        EditText myEditText = (EditText) ED.findViewById(R.id.qtyamount);
			                        myEditText.setClickable(true);
			                        myEditText.setFocusable(true);
			                        myEditText.setFocusableInTouchMode(true);
			                        myEditText.requestFocus();
			                        
			                        
			                        InvDatabaseHelper = new InventoryDatabaseHelper(context); 
						    	  	ListView listView = (ListView)findViewById(R.id.inventorylistviewinsideputaway);
						    	 	listView.setAdapter(null);
						         
						     	    StrictMode.setThreadPolicy(policy); 
						     	   InvDatabaseHelper.deleteAllData();
						     		try{
						    				
						    			String result = null;
						    	        InputStream is = null;
						    	      
						    	        String v1 = "'"+DATAAREAID+"'";
						    	    	SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");
						    	    	String v2 = "'BOD_01'";
						    			String v3 = "'"+NOMBRESKU+"'"; 

						    	        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
						    	        nameValuePairs.add(new BasicNameValuePair("empresa",v1));
						    	        nameValuePairs.add(new BasicNameValuePair("bodega",v2));
						    	        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/getLocationsRemaining.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");
						    	        	              //  Toast.makeText(getApplicationContext(), "Input Reading pass", Toast.LENGTH_SHORT).show();
						    	        	        }
						    	        	        is.close();
						    	        	        result=sb.toString();
						    	   	}
						    	   	catch(Exception e)
						    	   	{
						    	        	       Log.e("log_tag", "Error converting result "+e.toString());
						    	       // 	    Toast.makeText(getApplicationContext(), " Input reading fail", Toast.LENGTH_SHORT).show();
						    	   	}
						    	int counter=0;
						    	        	//parse json data
						    	        	try{

						    	        	 	JSONArray jArray = new JSONArray(result);
						    	        		for(int i=0;i<jArray.length();i++)  
						    		        {
						    	        			counter++;
						    	        			try{
						    	        		   	JSONObject no = jArray.getJSONObject(i);    
						    	        		    String loc=no.getString("Location");
						    	        		    String sku=no.getString("itemID");
						    	        	        String qty2=no.getString("qty");
						    	        		    try{
						    	        		    Double Qt = Double.parseDouble(qty2);
						    	        		    NumberFormat nf = NumberFormat.getInstance();
						    		 	            nf.setMaximumFractionDigits(0);// set as you need
						    		 	           qty2=nf.format(Qt).replace(",", "");
						    	        		    }catch(Exception e){}
						    	        		    
						    	        		    String type=no.getString("dim");
						    	        		   InvDatabaseHelper.saveInventoryLine(loc, sku, "", qty2, type, "","", "");
						    	 	            	}
						    	        	catch(JSONException e)
						    	        	{
						    	        	Log.e("log_tag", "Error parsing data "+e.toString()+Integer.toString(counter));
						    	        	}
						    	        			
						    	        			   ViewGroup.LayoutParams params = listView.getLayoutParams();
						    	        		       
						    	        			if(counter==0){
						    	        				params.height = 67;
						    	        			}else{
						    	        				params.height =67*counter;}
						    	        			
						    	        	 		listView.setLayoutParams(params);
						    	        	 	    listView.requestLayout();
						    		        }}
						    	        	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.");
						    	        	}
						     	
						     	
						     		 newInventoryAdapter = new InventoryAdapterSummary(context,InvDatabaseHelper.getInventoryItemLines(NOMBRESKU)); 			
						        	 listView.setAdapter(newInventoryAdapter);
						        	
						      		 
						    	     
						    	     
						    	     
						    	     
			                        
			                        
			                        
			                        
					    	     }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{
					  
						  String NOMBRESKU="";

				             TextView buscarheader = (TextView) findViewById(R.id.buscarheader);
				    	     Cursor cursor = databaseHelper.getReceivingItemBarcode(PONUMBER,Scanning);
				    	     if(cursor.getCount()>0){
				    	     cursor.moveToFirst();
				    		 NOMBRESKU=cursor.getString(2);
				    	     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));
				     	     
					       	 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);
		                        myEditText.setClickable(true);
		                        myEditText.setFocusable(true);
		                        myEditText.setFocusableInTouchMode(true);
		                        myEditText.requestFocus();
		                        
		                        
		                        
		                        InvDatabaseHelper = new InventoryDatabaseHelper(context); 
					    	  	ListView listView = (ListView)findViewById(R.id.inventorylistviewinsideputaway);
					    	 	listView.setAdapter(null);
					         
					     	    StrictMode.setThreadPolicy(policy); 
					     	   InvDatabaseHelper.deleteAllData();
					     		try{
					    				
					    			String result = null;
					    	        InputStream is = null;
					    	      
					    	        String v1 = "'"+DATAAREAID+"'";
					    	    	SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");
					    	    	String v2 = "'BOD_01'";
					    			String v3 = "'"+NOMBRESKU+"'"; 

					    	        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
					    	        nameValuePairs.add(new BasicNameValuePair("empresa",v1));
					    	        nameValuePairs.add(new BasicNameValuePair("bodega",v2));
					    	        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/getLocationsRemaining.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");
					    	        	              //  Toast.makeText(getApplicationContext(), "Input Reading pass", Toast.LENGTH_SHORT).show();
					    	        	        }
					    	        	        is.close();
					    	        	        result=sb.toString();
					    	   	}
					    	   	catch(Exception e)
					    	   	{
					    	        	       Log.e("log_tag", "Error converting result "+e.toString());
					    	       // 	    Toast.makeText(getApplicationContext(), " Input reading fail", Toast.LENGTH_SHORT).show();
					    	   	}
					    	int counter=0;
					    	        	//parse json data
					    	        	try{

					    	        	 	JSONArray jArray = new JSONArray(result);
					    	        		for(int i=0;i<jArray.length();i++)  
					    		        {
					    	        			counter++;
					    	        			try{
					    	        		   	JSONObject no = jArray.getJSONObject(i);    
					    	        		    String loc=no.getString("Location");
					    	        		    String sku=no.getString("itemID");
					    	        	        String qty2=no.getString("qty");
					    	        		    try{
					    	        		    Double Qt = Double.parseDouble(qty2);
					    	        		    NumberFormat nf = NumberFormat.getInstance();
					    		 	            nf.setMaximumFractionDigits(0);// set as you need
					    		 	           qty2=nf.format(Qt).replace(",", "");
					    	        		    }catch(Exception e){}
					    	        		    
					    	        		    String type=no.getString("dim");
					    	        		    
					    	        		   InvDatabaseHelper.saveInventoryLine(loc, sku, "", qty2, type, "","", "");
					    	 	            	}
					    	        	catch(JSONException e)
					    	        	{
					    	        	Log.e("log_tag", "Error parsing data "+e.toString()+Integer.toString(counter));
					    	        	}
					    	        			
					    	        			   ViewGroup.LayoutParams params = listView.getLayoutParams();
					    	        		       
					    	        			if(counter==0){
					    	        				params.height = 67;
					    	        			}else{
					    	        				params.height =67*counter;}
					    	        			
					    	        	 		listView.setLayoutParams(params);
					    	        	 	    listView.requestLayout();
					    		        }}
					    	        	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.");
					    	        	}
					     	
					     	
					     		 newInventoryAdapter = new InventoryAdapterSummary(context,InvDatabaseHelper.getInventoryItemLines(NOMBRESKU)); 			
					        	 listView.setAdapter(newInventoryAdapter);
					        	
					      		 
					    	     
					    	     
					    	     
					    	     
		                        
		                        
		                        
				    	     }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.getReceivingItemBarcode(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("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;
		    	     }

		            
				    }
				    
		 }}

		 public void onComplete(View view) {  
				
		         if(COUNTER==0){
		       	Toast.makeText(getApplicationContext(), "Escanee o digite artículo a recibir.", Toast.LENGTH_SHORT).show();
				   Intent intentemoslo = new Intent(getApplicationContext() ,VoiceHelper.class);
   			   intentemoslo.putExtra("voz","Escanee o digite artículo a recibir");  
   			   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){
		             Boolean TERMINUS=false;
		 		if(this.hasContent(edittext)==true){
		 			
		 		     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());
		 			
		 			Spinner paises = (Spinner)findViewById(R.id.countries);
		 	        String paisrec = paises.getSelectedItem().toString();
		 			databaseHelper.UpdateReceivingItem(nf.format(totalreceived).replace(",", ""),paisrec, ID);
		 			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("COUNTED","'"+n.getString(4).replace(".","").replace(",", ".")+"'"));
		 			  	//SUBE ON HAND NO DIFERENCIA
		 			 	nameValuePairs.add(new BasicNameValuePair("IOH","'"+n.getString(3)+"'"));
		 			    nameValuePairs.add(new BasicNameValuePair("EMP","'"+DATAAREAID+"'"));
		 			  	nameValuePairs.add(new BasicNameValuePair("TRANSID","'"+n.getString(9)+"'"));
		 			    nameValuePairs.add(new BasicNameValuePair("ITEMID","'"+n.getString(2)+"'"));
		 			    nameValuePairs.add(new BasicNameValuePair("DATE","'"+dat+"'"));
		 			    nameValuePairs.add(new BasicNameValuePair("BEGINDATE","'"+COUNTINGSTARTED+"'"));
		 			    nameValuePairs.add(new BasicNameValuePair("COUNTEDBY","'"+USERNAME+"'"));
		 			    nameValuePairs.add(new BasicNameValuePair("JID","'"+PONUMBER+"'"));
		 			    nameValuePairs.add(new BasicNameValuePair("CONFIGID","'"+n.getString(5)+"'"));
		 			    nameValuePairs.add(new BasicNameValuePair("CONREC","'"+n.getString(7)+"'"));
		 			    nameValuePairs.add(new BasicNameValuePair("TTYPE","'"+n.getString(10)+"'"));
		 			 
		 			   
		 			    StrictMode.setThreadPolicy(policy); 
		 			        	//http post
		 			        	try{
		 			        	        HttpClient httpclient = new DefaultHttpClient();
		 			        	        HttpPost httppost = new HttpPost("http://10.10.100.13/UpdateReceivingList.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 recibido.", Toast.LENGTH_SHORT).show();	 
					   Intent intentemoslo = new Intent(getApplicationContext() ,VoiceHelper.class);
	     			   intentemoslo.putExtra("voz","Artículo recibido");  
	     				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/getReceivingNotProcessedList.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 COUNTRYRECEIVED=no.getString("COUNTRYRECEIVED");
	     			    
	     			    	        double receiveamount=0;
	     			    		    try{
	     			        		    Double Qt = Double.parseDouble(COUNTED);
	     			        		    receiveamount=Qt;
	     			        		    NumberFormat nf2 = NumberFormat.getInstance();
	     				 	            nf2.setMaximumFractionDigits(0);// set as you need
	     				 	        COUNTED=nf2.format(Qt).replace(",", "");
	     			        		    
	     			        		}catch(Exception e){}

	     			    		
	     			      		    String itrans=no.getString("INVENTTRANSID");
	     			      		    String itemid=no.getString("ITEMID");
	     				            NumberFormat nf3 = NumberFormat.getInstance();
	     				            nf3.setMaximumFractionDigits(0);// set as you need
	     				        	Cursor xyz =databaseHelper.getItemDetail(PONUMBER,itrans,itemid);
	     				    		if(xyz.getCount()>0){
	     				    		xyz.moveToFirst();
	     			                databaseHelper.UpdateReceivingItem(COUNTED, COUNTRYRECEIVED, 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{
					  
			               String NOMBRESKU="";
				             TextView buscarheader = (TextView) findViewById(R.id.buscarheader);
				    	     Cursor cursor = databaseHelper.getReceivingItemBarcode(PONUMBER,Scanning);
				    	     if(cursor.getCount()>0){
				    	     cursor.moveToFirst();
				    	     ID= cursor.getString(0);
				    	     NOMBRESKU=cursor.getString(2);
				    	     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()); 	
				    			

				    		
				    		  	ListView listView = (ListView)findViewById(R.id.inventorylistviewinsideputaway);
				    		 	listView.setAdapter(null);
				    	    
				    		    StrictMode.setThreadPolicy(policy); 
				    		   InvDatabaseHelper.deleteAllData();
				    			try{
				    					
				    				String result = null;
				    		        InputStream is = null;
				    		      
				    		        String v1 = "'"+DATAAREAID+"'";
				    		    	SimpleDateFormat sdfa = new SimpleDateFormat("yyyy-MM-dd");
				    		    	String v2 = "'BOD_01'";
				    				String v3 = "'"+NOMBRESKU+"'"; 

				    		        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
				    		        nameValuePairs.add(new BasicNameValuePair("empresa",v1));
				    		        nameValuePairs.add(new BasicNameValuePair("bodega",v2));
				    		        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/getLocationsRemaining.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");
				    		        	              //  Toast.makeText(getApplicationContext(), "Input Reading pass", Toast.LENGTH_SHORT).show();
				    		        	        }
				    		        	        is.close();
				    		        	        result=sb.toString();
				    		   	}
				    		   	catch(Exception e)
				    		   	{
				    		        	       Log.e("log_tag", "Error converting result "+e.toString());
				    		       // 	    Toast.makeText(getApplicationContext(), " Input reading fail", Toast.LENGTH_SHORT).show();
				    		   	}
				    		int COUNT=0;
				    		        	//parse json data
				    		        	try{

				    		        	 	JSONArray jArray = new JSONArray(result);
				    		        		for(int i=0;i<jArray.length();i++)  
				    			        {
				    		        			COUNT++;
				    		        			try{
				    		        		   	JSONObject no = jArray.getJSONObject(i);    
				    		        		    String loc=no.getString("Location");
				    		        		    String sku=no.getString("itemID");
				    		        	        String qty2=no.getString("qty");
				    		        		    try{
				    		        		    Double Qt = Double.parseDouble(qty2);
				    		        		    NumberFormat nf = NumberFormat.getInstance();
				    			 	            nf.setMaximumFractionDigits(0);// set as you need
				    			 	           qty2=nf.format(Qt).replace(",", "");
				    		        		    }catch(Exception e){}
				    		        		    
				    		        		    String type=no.getString("dim");
				    		        		   InvDatabaseHelper.saveInventoryLine(loc, sku, "", qty2, type, "","", "");
				    		 	            	}
				    		        	catch(JSONException e)
				    		        	{
				    		        	Log.e("log_tag", "Error parsing data "+e.toString()+Integer.toString(COUNT));
				    		        	}
				    		        			
				    		        			   ViewGroup.LayoutParams params = listView.getLayoutParams();
				    		        		       
				    		        			if(COUNT==0){
				    		        				params.height = 67;
				    		        			}else{
				    		        				params.height =67*COUNT;}
				    		        			
				    		        	 		listView.setLayoutParams(params);
				    		        	 	    listView.requestLayout();
				    			        }}
				    		        	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.");
				    		        	}
			
				    			 newInventoryAdapter = new InventoryAdapterSummary(context,InvDatabaseHelper.getInventoryItemLines(NOMBRESKU)); 			
				    	   	     listView.setAdapter(newInventoryAdapter);
				    	   	
				    	 		 
					    	     
					    	     
					    	     
					    	     
				    			
				    	     }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();  
			}
	  }

					
				});

			}
		 
		
}
