InventarioMainBoard.java 100 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085
package com.focasoftware.deboinventario;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Set;

/**
 * Activity que muestra los inventarios din๏ฟฝmicos y comunes en curso para
 * llevarlos a cabo, exportarlos o importar nuevos.
 * 
 * @author GuillermoR
 * 
 */
public class InventarioMainBoard extends Activity implements DialogPersoSimple, Wifi {

	// *************************
	// *************************
	// **** ATRIBUTOS ****
	// *************************
	// *************************
	//
	/**
	 * Datos del contexto de la actividad
	 */
	@NonNull
    private Context ctxt = this;

	private CheckBox CheckBorrar;

	private boolean borrar;
	/**
	 * Instancia de un administrador de Base de datos
	 */
	private BaseDatos bdd;

	@NonNull
    BaseDatos bd = new BaseDatos(ctxt);
	/**
	 * Lista para almacenar cuales son los inventarios seleccionados con los que
	 * se trabajara
	 */
	@NonNull
    private ArrayList<Integer> listaInventariosSeleccionados = new ArrayList<Integer>();
	/**
	 * 
	 */
	@NonNull
    private HashMap<Integer, ArrayList<HashMap<String, Integer>>> matrizArticulosCadaInventario = new HashMap<Integer, ArrayList<HashMap<String, Integer>>>();
	/**
	 * Tabla prinicipal donde se muestran los inventarios actuales
	 */
	private TableLayout tablaPrincipal;
	/**
	 * Botones para importar y exportar los inventarios
	 */
	private Button botonExportar, botonImportar, Exportar_BD, Importar_BD;
	// private Button botonInvDinamico;
	/**
	 * Boton para volver a la pantalla inicial (icono : X )
	 */
	private ImageView botonSalir;
	/**
	 * Dialogos para mostrar opciones de importacion y exportacion para elegir
	 * los medios
	 */
	private DialogPersoComplexExport dialogoPrincipioExport,
			dialogoPrincipioImport;
	/**
	 * Dialogo de aviso para borrar inventarios comunes, se muestra cuando
	 * presionamos de forma prolongada un boton de un inventario com๏ฟฝn
	 */
	private DialogPersoComplexSiNo dialogoBorrarInventario;// ,
															// dialogoCreacionInvDinamico;
	/**
	 * Dialogo que se muestra para preguntar si desea seguir trabajando con el
	 * inventario dinamico actual o empezar de cero
	 */
	private DialogPersoComplexSiNo dialogoContinuarInventario;
	/**
	 * Dialogo para confirmar la decisi๏ฟฝn de borrar el inventario din๏ฟฝmico
	 * actual y crear uno nuevo desde cero
	 */
	private DialogPersoComplexSiNo dialogoBorrarInventarioDinamico;
	// private DialogPersoComplexSiNoOpcs dialogoCreacionInvDinamico;
	/**
	 * ProgresDialogs para mostrar progresos de procesos como exportacion e
	 * importacion
	 */
	private ProgressDialog popupCarga, popupEspera;

	/**
	 * Variables auxiliares
	 */
	private int pasoInventario;
	private double pasoArticulo;
	private double carga = (double) 0;

	private int inventarios_elegidos = 0;

	/**
	 * Dialog donde se informa que se han realizado todas las mediciones para
	 * que proceda a exportar
	 */
	private AlertDialog.Builder dialogoFin;

	boolean isEnabled;
	/**
	 * Variable para saber si hay que borrar despues de exportar
	 */
	boolean borrarDespues = false;

	// Agregados 3/5/2012
	/**
	 * Para manejo especial de inventario dinamico
	 */
	boolean hayDinamicos = false;
	/**
	 * HashMaps para manejo especial de los inventarios din๏ฟฝmicos se guarda la
	 * informacion de los mismos ahi
	 */

	/**
	 * Variables de control para saber que tipo de unidad se tiene conectada
	 * tanto para esta clase como para la UsbProvider
	 */

	@NonNull
    public String unidad_final_import = "Dispositivo";

	@NonNull
    public String unidad_final_export = "Dispositivo";

	// se lanza al principio de la clase, para que quede confirurado para la
	// clase usbProvider
	// se verifica el inicio de la ruta configurada sea la correcta /udisk/,
	// /flash/,/sdcard/
	@NonNull
    public String TipoDispositivoImport() {

		// se retorna el resultado y se seteea para que este disponible en
		// cualquier momento
		ParametrosInventario.Dispositivo_Import = unidad_final_import;
		return unidad_final_import;
	}

	// idem anterior
	@NonNull
    public String TipoDispositivoExport() {

		ParametrosInventario.Dispositivo_Export = unidad_final_export;
		return unidad_final_export;
	}

	@NonNull
    private String Dispositivo_Import = TipoDispositivoImport();
	@NonNull
    private String Dispositivo_Export = TipoDispositivoExport();

	@Nullable
    HashMap<String, String> hashmapInventarioVenta;
	@Nullable
    HashMap<String, String> hashmapInventarioDeposito;
	
	// Parametro para mostrar inventarios de deposito o ventas
	private int condR = 0;

	/* Variables para saber si esta marcado Inventario por ventas o Inventario deposito */
	private RadioButton CheckedInventariosVentas;
	private RadioButton CheckedInventariosDeposito;

	// *****************************
	// *****************************
	// **** CONSTRUCTORES **********
	// *****************************
	// *****************************

	/**
	 * Se ejecuta al iniciar la activity
	 * <p>
	 * 1๏ฟฝ Carga de la UI
	 * <p>
	 * 2๏ฟฝ Refresh de la tabla principal
	 * <p>
	 * 3๏ฟฝ HANDLERS de los botones
	 */

    @NonNull
    GestorLogEventos log = new GestorLogEventos();

	public void onCreate(Bundle savedInstanceState) {
		// 1๏ฟฝ Carga de la UI
		// Creaci๏ฟฝn p๏ฟฝgina desde el documento XML
		super.onCreate(savedInstanceState);
		setContentView(R.layout.xml_mainboard);

		log.setUbicacion(ParametrosInventario.CARPETA_LOGTABLET);
		log.tipo_0 = Parametros.PREF_LOG_EVENTOS;
		log.tipo_2 = Parametros.PREF_LOG_PROCESOS;
		log.tipo_3 = Parametros.PREF_LOG_MENSAJES;
		log.tipo_4 = Parametros.PREF_LOG_EXCEPCIONES;
		log.log("[-- 240 --]" + "Inicia _Inventario Main Board", 2);

		// Recuperamos tabla:
		tablaPrincipal = (TableLayout) findViewById(R.id.IMB_tabla);

	    // Recuperamos los botones:
		botonExportar = (Button) findViewById(R.id.IMB_boton_exportar);
		botonSalir = (ImageView) findViewById(R.id.IMB_boton_salir);
		botonImportar = (Button) findViewById(R.id.IMB_boton_importar);
		Exportar_BD = (Button) findViewById(R.id.Exportar_BD);
		Importar_BD = (Button) findViewById(R.id.Importar_BD);
		CheckedInventariosVentas = (RadioButton) findViewById(R.id.CheckInventariosVentas);
		CheckedInventariosDeposito = (RadioButton) findViewById(R.id.CheckInventariosDepositos);

		Exportar_BD.setOnLongClickListener(new View.OnLongClickListener() {

			public boolean onLongClick(View v) {
				log.log("Se presiono el boton Exportar BD", 3);
				String titulo = "EXPORTACION DE BASE DE DATOS";
				String mensaje = "Se exporto la base de datos";
				showSimpleDialogOK(titulo, mensaje).show();
				try {
					File sourceFile = new File(ParametrosInventario.URL_CARPETA_DATABASES + "DB_INVENT");
					File destFile = new File(ParametrosInventario.CARPETA_LOGDATOS + "DB_INVENT.sqlite");
					copyFile(sourceFile, destFile);
					Log.e("mensaje, sourceFile", sourceFile.toString());
					Log.e("mensaje, destFile", destFile.toString());
				} catch (Exception e) {
					log.log(e.toString(), 4);
					showSimpleDialogOK("EXPORTACION DE BASE DE DATOS", "Se interrumpio, intentelo nuevamente.\nSi el error persiste, reporte el archivo log a Servicio Tecnico").show();
				}
				log.log("Exportacion Realizada con exito", 3);
				return false;
			}

		});

		Importar_BD.setOnLongClickListener(new View.OnLongClickListener() {

			public boolean onLongClick(View v) {
				log.log("Se presiono el boton Importar BD", 3);
				String titulo = "IMPORTACION DE BASE DE DATOS";
				String mensaje = "Se importo la base de datos";
				showSimpleDialogOK(titulo, mensaje).show();
				try {
					File destFile = new File(
							ParametrosInventario.URL_CARPETA_DATABASES
									+ "DB_INVENT");
					File sourceFile = new File(
							ParametrosInventario.CARPETA_LOGDATOS
									+ "DB_INVENT.sqlite");
					copyFile(sourceFile, destFile);
					Log.e("mensaje, sourceFile", sourceFile.toString());
					Log.e("mensaje, destFile", destFile.toString());
				} catch (Exception e) {
					log.log(e.toString(), 4);
					showSimpleDialogOK(
							"IMPORTACION DE BASE DE DATOS",
							"Se interrumpio, intentelo nuevamente.\n"
									+ "Si el error persiste, reporte el archivo log a Servicio Tecnico")
							.show();
				}

				log.log("Importacion Realizada con exito", 3);
				return false;
			}

		});

		log.log("Fin exportar ", 3);

		// Apagamos el Wifi:
		desactivarWifi();

		// 2 REFRESH DE LA PAGINA PRINCIPAL:
		try {
			refreshTablaPrincipal();
		} catch (ExceptionBDD e1) {

			log.log("[-- 260 --]" + e1.toString(), 2);
			e1.printStackTrace();
			Toast.makeText(ctxt, e1.toString(), Toast.LENGTH_LONG).show();
		} catch (Exception e1) {

			log.log("[-- 265 --]" + e1.toString(), 4);
			e1.printStackTrace();
			Toast.makeText(ctxt, e1.toString(), Toast.LENGTH_LONG).show();
		}

		// 3 HANDLERS de los botones:
		botonExportar.setOnLongClickListener(new View.OnLongClickListener() {

			public boolean onLongClick(View v) {

				log.log("[-- 276 --]" + "Presiono Exportar", 0);
				BaseDatos bdd = new BaseDatos(ctxt);
				int numero_inventarios_cerrados = 0;
				ArrayList<Integer> inventarios_a_exportar ;
//String prueba = "";
				try {
				//	numero_inventarios_cerrados = bdd
				//			.selectInventariosCerradosEnBdd().size();

					inventarios_a_exportar = bdd.selectInventariosCerradosEnBdd();

					//	inventarios_elegidos = inventarios_a_exportar.get(0);
					numero_inventarios_cerrados = inventarios_a_exportar.size();
					if(numero_inventarios_cerrados>=1) {
						inventarios_elegidos = inventarios_a_exportar.get(0);
					}
					System.out.println("::: InventarioMainBoard 351 numero_inventarios_cerrados " + numero_inventarios_cerrados);
				} catch (ExceptionBDD e) {
					log.log("[-- 285 --]" + e.toString(), 4);log.log("[-- 286 --]" + "Error, la exportacion se cancelo", 3);
					e.printStackTrace();
					Toast.makeText(ctxt, "Error, la exportacion se cancelo", Toast.LENGTH_LONG).show();
					return false;
				}

				if (numero_inventarios_cerrados <= 0) {
					log.log("[-- 297 --]" + "Ningun inventario cerrado, la exportacion se cancelo", 3);
					Toast.makeText(ctxt, "Ningun inventario cerrado, la exportacion se cancelo", Toast.LENGTH_LONG).show();
					return false;
				}else if(numero_inventarios_cerrados>=2){
					log.log("[-- 297 --]" + "Debe seleccionar un solo inventario, la exportacion se cancelo", 3);
					Toast.makeText(ctxt, "No puede realizarse la exportacion, solamente debe haber un inventario cerrado para exportar.", Toast.LENGTH_LONG).show();
					return false;
				}

				lanzarMenuEspera();

				View.OnClickListener listenerWifi = new View.OnClickListener() {

					public void onClick(View v) {
						log.log("[-- 311 --]" + "Se presiono el boton Wifi ", 0);
						borrarDespues = dialogoPrincipioExport.isBorrar_luego();
						dialogoPrincipioExport.dismiss();
						Intent intentWifi = new Intent(InventarioMainBoard.this, WiFiControlador.class);
						startActivityForResult(intentWifi, Parametros.REQUEST_WIFI_EXPORT);
					}
				};

				View.OnClickListener listenerUsb = new View.OnClickListener() {

					public void onClick(View v) {

						log.log("[-- 327 --]" + "Se presiono el boton USB ", 0);
						// dialogoPrincipioExport.cancel();
						// dialogoPrincipioExport.hide();
						dialogoPrincipioExport.dismiss();

						int contador = 3;

						try {
							do {
								export_usb(dialogoPrincipioExport.isBorrar_luego());
								contador--;
							} while (!control_buena_exportacion()
									&& contador >= 0);
						} catch (ExceptionBDD e) {
							showSimpleDialogOK(
									"Error",
									"Generacion del documento XML imposible: "
											+ e.getComentario()).show();
							cerrarMenuEspera();
							return;
						} catch (Exception e) {
							showSimpleDialogOK(
									"Error",
									"Imposible exportar en el "
											+ Dispositivo_Export
											+ ". Verifique que este correcamente "
											+ "conectado").show();
							cerrarMenuEspera();
							return;
						}

						// Si hubo vencimiento del contador:
						if ((!control_buena_exportacion())
								|| contador < 0) {
							// Entra aca, por que?
							showSimpleDialogOK(
									"ERROR DE EXPORTACION",
									"Los archivos XML de exportacion del "
											+ Dispositivo_Export
											+ ", no han podido ser creados con exito.")
									.show();
							return;
						}

						cerrarMenuEspera();
					}
				};

				View.OnClickListener listenerNegativo = new View.OnClickListener() {

					public void onClick(View v) {
						dialogoPrincipioExport.cancel();
						cerrarMenuEspera();
					}
				};

				int radioProductosContabilizados = ParametrosInventario.ProductosNoContabilizados;
				System.out.println("::: InventarioMainBoard 453 Seleccion invetario cerrado radio valor " +radioProductosContabilizados );
if(radioProductosContabilizados==2){
	dialogoPrincipioExport = new DialogPersoComplexExport(
			ctxt,
			"MEDIO DE EXPORTACION",
			"Usted esta a punto de exportar los datos de INVENTARIOS.\n"
					+ "La opcion de  AJUSTAR PRODUCTOS NO INCLUIDOS puede demorar varios minutos.\n\n"
					+ "Por favor, elija el medio con el cual usted desea exportar los datos:\n"
					+ "Los inventarios dinamicos se borraran",
			true, listenerWifi, listenerUsb, listenerNegativo);
	dialogoPrincipioExport.show();
}else{
	dialogoPrincipioExport = new DialogPersoComplexExport(
			ctxt,
			"MEDIO DE EXPORTACION",
			"Usted esta a punto de exportar los datos de INVENTARIOS.\n"
					+ "Este proceso puede requerir algunos minutos.\n\n"
					+ "Por favor, elija el medio con el cual usted desea exportar los datos:\n"
					+ "Los inventarios dinamicos se se borraran",
			true, listenerWifi, listenerUsb, listenerNegativo);
	dialogoPrincipioExport.show();

}

				/*dialogoPrincipioExport = new DialogPersoComplexExport(
						ctxt,
						"MEDIO DE EXPORTACION",
						"Usted esta a punto de exportar los datos de INVENTARIOS.\n"
								+ "Este proceso puede requerir algunos minutos.\n\n"
								+ "Por favor, elija el medio con el cual usted desea exportar los datos:\n"
								+ "Los inventarios dinamicos se se borraran",
						true, listenerWifi, listenerUsb, listenerNegativo);
				dialogoPrincipioExport.show();
*/
				return true;
			}
		});

		botonImportar.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {

				log.log("[-- 396 --]" + "Se presiono Importar", 0);
				// Control de la cantidad de inventario ya en curso:
				try {
					bdd = new BaseDatos(ctxt);
					System.out.println("::: Inventariomainboard 467 antes del wifi sector 1");
					if (bdd.selectInventariosNumerosEnBdd().size() > ParametrosInventario.PREF_MAX_COMPRA_ABIERTAS) {
						showSimpleDialogOK(
								"Alerta",
								"La cantidad de inventarios cargados es muy importante y puede perjudicar el buen funcionamiento de su tablet Android.\n\n"
										+ "Por favor, se recomiende proceder a la exportacion de los inventarios terminados y borrar los inventarios vencidos."
										+ "que no superen los 10 inventarios");
					}
				} catch (ExceptionBDD e) {

					log.log("[-- 409 --]" + e.toString(), 4);

				}

				View.OnClickListener listenerWifi = new View.OnClickListener() {

					public void onClick(View v) {
						System.out.println("::: Inventario mainboard antes del wifi sector 2");
						log.log("[-- 417 --]" + "Se presiono wifi", 0);
						dialogoPrincipioImport.dismiss();

						Intent intentWifi = new Intent(
								InventarioMainBoard.this, WiFiControlador.class);
						startActivityForResult(intentWifi,
								Parametros.REQUEST_WIFI_IMPORT);
					}
				};

				View.OnClickListener listenerUsb = new View.OnClickListener() {

					public void onClick(View v) {
						dialogoPrincipioImport.dismiss();

						log.log("[-- 432 --]" + "Se presiono exportar por usb",
								0);
						System.out.println("InventarioMainBoard 499 ExportarUSB");
						Intent intentUSB = new Intent(InventarioMainBoard.this,
								UsbProvider.class);
						// intentUSB.putExtra(Parametros.extra_uri_usb,
						// Parametros.PREF_USB_IMPORT);
						intentUSB.putExtra(Parametros.extra_uri_usb,
								ParametrosInventario.CARPETA_ATABLET);
						// intentUSB.putExtra(Parametros.extra_uri_usb,
						// "/data/data/com.foca.deboInventario/test/");
						startActivityForResult(intentUSB,
								Parametros.REQUEST_USB);
						finish();
					}
				};

				View.OnClickListener listenerNegativo = new View.OnClickListener() {

					public void onClick(View v) {
						log.log("[-- 450 --]" + "Se presiono cancelar", 0);
						dialogoPrincipioImport.cancel();
						// cerrarMenuEspera();
					}
				};

				dialogoPrincipioImport = new DialogPersoComplexExport(
						ctxt,
						"CARGAR UN NUEVO INVENTARIO",
						"Usted esta a punto de cargar un nuevo INVENTARIOS.\n\n"
								+ "Por favor, elija el medio con el cual usted desea importar " +
								"los datos del nuevo inventario:\n",
						false, listenerWifi, listenerUsb, listenerNegativo);
				dialogoPrincipioImport.show();

				log.log("[-- 464 --]"
						+ "Se mu8estra un pop up con las opcioners de importacion",
						3);
			}
		});

		botonSalir.setOnTouchListener(new View.OnTouchListener() {

			public boolean onTouch(View v, @NonNull MotionEvent event) {
				log.log("[-- 473 --]" + "Se presiono salir", 0);
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					ImageView imageV = (ImageView) v;
					imageV.setBackgroundColor(getResources().getColor(
							R.color.orange));
				} else if (event.getAction() == MotionEvent.ACTION_UP) {
					ImageView imageV = (ImageView) v;
					imageV.setBackgroundColor(Color.TRANSPARENT);

					finish();
				}
				return true;
			}
		});
	}

	/**
	 * Podemos regresar desde: Exportacion, importacion, inventario normal o
	 * dinmico
	 *
	 * 1 Volvemos de Pagina inventario o Dinmico :refrescamos la tabla y
	 * controlamos si hay alguno para cerrar
	 *
	 * 2 Si volvemos de WIFI import todo bien, vamos a seleccionar Inventario
	 *
	 * 3 Si hubo un error con WIFI import da la opcin de cargar por USB
	 * <p>
	 * 4 Si volvemos de WIFI Export todo OK vamos a hacer exportacion por WIFI
	 * <p>
	 * 5 Si volvemos de WIFI export con error damos la opcion de hacerlo por
	 * USB
	 */

	public void onActivityResult(int requestCode, int resultCode, @Nullable Intent intentRespondido) {
		try {
			super.onActivityResult(requestCode, resultCode, intentRespondido);
			Bundle bundle = null;
			if (intentRespondido != null) {
				bundle = intentRespondido.getExtras();
			}

			/*
			 * if (requestCode == ParametrosInventario.REQUEST_INVENTARIO &&
			 * resultCode == RESULT_OK) { int numeroInventario =
			 * bundle.getInt(ParametrosInventario.extra_numeroInventario); int
			 * idLineaSeleccionada = ParametrosInventario.ID_LINEAS +
			 * numeroInventario;
			 * TableRow estaLinea = (TableRow)findViewById(idLineaSeleccionada);
			 * estaLinea.setBackgroundColor(Color.GREEN);
			 * refreshLinea(estaLinea);
			 * controlFin();
			 * } else if (requestCode == ParametrosInventario.REQUEST_INVENTARIO
			 * && resultCode == RESULT_CANCELED) { int numeroInventario =
			 * bundle.getInt(ParametrosInventario.extra_numeroInventario); int
			 * idLineaSeleccionada = ParametrosInventario.ID_LINEAS +
			 * numeroInventario;
			 * TableRow estaLinea = (TableRow)findViewById(idLineaSeleccionada);
			 * refreshLinea(estaLinea);
			 * controlFin();
			 */
			// 1 Volvemos de Pagina inventario o Dinmico:refrescamos la tabla
			// y
			// controlamos si hay alguno para cerrar
			if (requestCode == ParametrosInventario.REQUEST_INVENTARIO) {
				try {

					refreshTablaPrincipal();

					controlFin();
				} catch (ExceptionBDD e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else if (requestCode == ParametrosInventario.REQUEST_INVENTARIO_DINAMICO) {
				try {
					refreshTablaPrincipal();

					controlFin();
				} catch (ExceptionBDD e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else if (requestCode == Parametros.REQUEST_WIFI_IMPORT && resultCode == RESULT_OK) {
				// cerrarMenuEspera();
				// 2 Si volvemos de WIFI import todo bien, vamos a seleccionar
				// Inventario
				Intent intentInventario = new Intent(ctxt, SeleccionInventarios.class);
				startActivity(intentInventario);
				finish();

			} else if (requestCode == Parametros.REQUEST_WIFI_IMPORT) {
				// cerrarMenuEspera();
				// 3 Si hubo un error con WIFI import da la opcin de cargar
				// por USB
				desactivarWifi();
				showSimpleDialogSiNo("Error de conexion a la red", "La red hasta el servidor no ha podido ser establecida (1).\n\nUsted desea importar sus datos por medio de un Dispositivo (conectelo en aquel caso)?", UsbProvider.class).show();
			} else if (requestCode == Parametros.REQUEST_WIFI_EXPORT && resultCode == RESULT_OK) {
				// 4 Si volvemos de WIFI Export todo OK vamos a hacer
				// exportacion por WIFI
				ExportarDatos unaExportacion = new ExportarDatos();
				unaExportacion.execute(ctxt);

			} else if (requestCode == Parametros.REQUEST_WIFI_EXPORT) {
				// 5 Si volvemos de WIFI export con error damos la opcion de
				// hacerlo por USB
				cerrarMenuEspera();
				desactivarWifi();
				showSimpleDialogSiNo("Error de conexion a la red", "La red hasta el servidor no ha podido ser establecida (2).\n\nUsted desea exportar sus datos por medio de un Dispositivo (conectelo en aquel caso)?", null).show();
			}

		} catch (Exception e) {

			log.log("[-- 492 --]" + e.toString(), 4);
			e.printStackTrace();
			showSimpleDialogOK("Error", e.toString()).show();
		}
	}

	// ***********************
	// ***********************
	// **** METODOS ****
	// ***********************
	// ***********************
	//

	/**
	 * Creamos el thread que va a ejecutar el trabajo pesado (en una nueva clase
	 * ) No se usa aparentemente en esta activity
	 */
	protected class CargarDatosArticulos extends AsyncTask<Context, Integer, String> {

		/**
		 * Tarea a realizar en background
		 */
		@Nullable
        protected String doInBackground(Context... arg0) {
			System.out.println("::: InventarioMainboard 700 CargarDatosArticulos doInBackground");
			popupSubir(2);

			// Cargamos la base de datos:
			BaseDatos bdd = new BaseDatos(ctxt);
			bdd = new BaseDatos(ctxt);

			popupStart();

			// Recuperamos los inventarios cargados:
			try {
				listaInventariosSeleccionados = bdd
						.selectInventariosNumerosEnBdd();
			} catch (ExceptionBDD e2) {

				log.log("[-- 633 --]" + e2.toString(), 0);
				e2.printStackTrace();
			}

			// Para cada inventario vemos si tiene articulos ya cargados o no.
			// Los inventarios que figuran sin articulos => hay que rellenarlos.

			// A ver si continuamos datos ya presentes en bdd o si empezamos de
			// nuevo:
			boolean bddYaCargada = true;
			try {
				if (bdd.selectArticulosCodigosEnBdd() == null) {
					bddYaCargada = false;
				}
			} catch (ExceptionBDD e1) {

				e1.printStackTrace();
				bddYaCargada = false;
			}

			popupSubir(5);

			// Carga de los datos si y solamente si la base est vaca:
			if (bddYaCargada == false) {

				try {
					popupSubir(10);

					// Primero se actualizan las panreferencias en la tablet
					// Android:
					/*
					 * SharedPreferences settings =
					 * PreferenceManager.getDefaultSharedPreferences(ctxt);
					 * SharedPreferences.Editor editor = settings.edit();
					 * editor.
					 * putBoolean(ParametrosInventario.preferencias_en_curso,
					 * true); editor.commit();
					 */
					popupSubir(15);

					// Descargamos los detalles de todas las inventarios
					// seleccionadas:
					HttpReader readerHttp = null;
					try {
						readerHttp = new HttpReader(
								Parametros.PREF_URL_CONEXION_SERVIDOR,
								ParametrosInventario.FONCION_CARGAR_ARTICULOS,
								listaInventariosSeleccionados);
					} catch (ExceptionHttpExchange e) {

						log.log("[-- 686 --]" + e.toString(), 4);
						e.printStackTrace();
					}

					popupSubir(20);
					// Para cada inventario, guardamos sus detalles en una super
					// matriz de matriz de matriz ( matriz^3 ):
					int countSeguridad = 3;
					LinkedHashMap<Integer, LinkedHashMap<HashMap<String, Integer>, HashMap<String, String>>> hashmapDetallesTodosInventarios = readerHttp
							.readDetallesInventarios();


					while (countSeguridad > 0
							&& hashmapDetallesTodosInventarios.size() <= 0) {
						hashmapDetallesTodosInventarios = readerHttp
								.readDetallesInventarios();
						System.out.println("::: InventarioMainboard 780");
						countSeguridad--;
						popupSubir(20 + 4 - countSeguridad);
					}

					popupSubir(25);

					// Empezamos la lectura de la base de datos:
					Set<Integer> setNumerosInventarios = hashmapDetallesTodosInventarios
							.keySet();
					Iterator<Integer> ite = setNumerosInventarios.iterator();

					pasoInventario = (int) Math.floor((95 - 30)
							/ setNumerosInventarios.size());
					carga = 30;

					popupSubir(30);

					// Iteracin la enumeracin de las inventarios:
					while (ite.hasNext() == true) {

						// Recuperamos el numero de la inventario:
						int numeroInventario = ite.next();

						// Para este inventario, leemos todos los articulos que
						// contiene:
						ArrayList<HashMap<String, Integer>> listaCodigosArticulos = new ArrayList<HashMap<String, Integer>>();

						Set<HashMap<String, Integer>> setCodigosArticulos = hashmapDetallesTodosInventarios
								.get(numeroInventario).keySet();
						Iterator<HashMap<String, Integer>> ite2 = setCodigosArticulos
								.iterator();
						long cantidadArticulosEsteInventario = setCodigosArticulos
								.size();
						pasoArticulo = (double) ((double) pasoInventario / (double) cantidadArticulosEsteInventario);

						// Iteracin la enumeracin de los medidores de esta
						// inventario:
						while (ite2.hasNext() == true) {
							HashMap<String, Integer> codigosArticulo = ite2
									.next();
							listaCodigosArticulos.add(codigosArticulo);

							// Recuperamos los datos del ARTICULO con su par de
							// codigos de identificacion (sector, codigo):
							HashMap<String, String> datosUnArticulo = hashmapDetallesTodosInventarios
									.get(numeroInventario).get(codigosArticulo);

							// A partir de este hashmap recuperamos el objeto
							// ARTICULO:
							System.out.println("::: InventarioMainboard 830 recupera objeto");
							Articulo articulo = new Articulo(
									Integer.parseInt(datosUnArticulo
											.get(ParametrosInventario.bal_bdd_articulo_sector)),
									Integer.parseInt(datosUnArticulo
											.get(ParametrosInventario.bal_bdd_articulo_codigo)),
											Integer.parseInt(datosUnArticulo
													.get(ParametrosInventario.bal_bdd_articulo_balanza)),
													Integer.parseInt(datosUnArticulo
															.get(ParametrosInventario.bal_bdd_articulo_decimales)),
									new ArrayList<String>(
											Arrays.asList(datosUnArticulo
													.get(ParametrosInventario.bal_bdd_articulo_codigo_barra)
													.split(","))),
													new ArrayList<String>(
															Arrays.asList(datosUnArticulo
																	.get(ParametrosInventario.bal_bdd_articulo_codigo_barra_completo)
																	.split(","))),
									Integer.parseInt(datosUnArticulo
											.get(ParametrosInventario.bal_bdd_articulo_inventario)),
									datosUnArticulo
											.get(ParametrosInventario.bal_bdd_articulo_descripcion),
									Double.parseDouble(datosUnArticulo
										.get(ParametrosInventario.bal_bdd_articulo_existencia_venta)),
									Double.parseDouble(datosUnArticulo
											.get(ParametrosInventario.bal_bdd_articulo_existencia_deposito)),
											Integer.parseInt(datosUnArticulo
													.get(ParametrosInventario.bal_bdd_articulo_depsn)),
									Double.parseDouble(datosUnArticulo
											.get(ParametrosInventario.bal_bdd_articulo_precio_venta)),
									Double.parseDouble(datosUnArticulo
											.get(ParametrosInventario.bal_bdd_articulo_precio_costo)));
							bdd.insertArticuloEnBdd(articulo);

							// Aumentamos la barra del popup:
							carga += pasoArticulo;
							popupSubir((int) carga);

						} // end while (ite2.hasNext() == true)

						// Guardamos en memoria la lista de los articulos de
						// este inventario:
						matrizArticulosCadaInventario.put(numeroInventario,
								listaCodigosArticulos);
						// carga += pasoArticulo;
						// popupSubir(proximoPaso);

					} // end while (ite.hasNext() == true)

					// Borramos la memoria:
					hashmapDetallesTodosInventarios.clear();

					// Terminar el thead:
					popupSubir(99);
					wait(500);

				} catch (Exception e) {

					log.log("[-- 794 --]" + e.toString(), 4);
					e.printStackTrace();
				} catch (ExceptionBDD e) {

					log.log("[-- 798 --]" + e.toString(), 4);
					e.printStackTrace();
				} finally {
					popupEnd();
				}
			} else {
				// En el caso en el cual la base ya esta cargada con datos:
				matrizArticulosCadaInventario.clear();

				for (int numInventario : listaInventariosSeleccionados) {
					try {
					
						matrizArticulosCadaInventario
								.put(numInventario,
										bdd.selectArticulosCodigosConNumeroInventario(numInventario));
					} catch (ExceptionBDD e) {

						log.log("[-- 814 --]" + e.toString(), 4);
						e.printStackTrace();
					}
				}
				popupEnd();
			}

			return null;
		}

		protected void onPostExecute(String result) {

			super.onPostExecute(result);

			// Cargamos la tabla principal con los datos eventualmente ya
			// cargados:
			try {
				refreshTablaPrincipal();

				controlFin();
			} catch (NumberFormatException e1) {
				e1.printStackTrace();
			} catch (ExceptionBDD e1) {
				e1.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	} // fin de "protected class CargarDatosinventarios"

	/**
	 * Metodo que llena la tabla de inventarios principal Trata de manera
	 * especial a los inventarios dinamicos de los otros ya que muestra siempre
	 * el boton de inventario dinmico por que siempre esta o se puede crear,
	 * pero es uno solo
	 * <p>
	 * 1 Limpiamos la vista
	 * <p>
	 * 2 Control de la integridad de cada inventario
	 * <p>
	 * 3 Cargamos los datos presentes (eventualmente) en la base de datos
	 * <p>
	 * 4 Configuracin de los botones
	 * <p>
	 * 5 Si tenemos elementos, construccin de todos los botones de inventarios
	 * comunes de la pagina
	 * <p>
	 * 6 Creacion de estructuras y la linea del inventario dinmico
	 * 
	 * @throws ExceptionBDD
	 * @throws Exception
	 */
	private void refreshTablaPrincipal() throws ExceptionBDD, Exception {
		// Variables:
		System.out.println("::: InventarioMain RefresTablaPrincipal 951");
		HashMap<Integer, HashMap<String, String>> matrizInventarios = new HashMap<Integer, HashMap<String, String>>();
		HashMap<Integer, HashMap<String, String>> matrizInventariosDinamicos = new HashMap<Integer, HashMap<String, String>>();

		// 1 Limpiamos la vista:
		tablaPrincipal.removeAllViews();

		// 2 Control de la integridad de cada inventario:
		control_integridad_tablas();

		// 3 Cargamos los datos presentes (eventualmente) en la base de datos:
		BaseDatos bdd = new BaseDatos(ctxt);
		// Por que lo creamos dos veces?
		bdd = new BaseDatos(ctxt);
		try {
			matrizInventarios = bdd.selectInventariosEnBdd();
		} catch (ExceptionBDD e2) {

			log.log("[-- 882 --]" + e2.toString() + " NO HAY INVENTARIOS", 4);
			e2.printStackTrace();
		}
		// 4 Configuracin de los botones:
		if (matrizInventarios.size() <= 0) {
			botonExportar.setEnabled(false);
			botonImportar.setEnabled(true);
			// return;
		} else if (matrizInventarios.size() >= ParametrosInventario.PREF_MAX_COMPRA_ABIERTAS) {
			botonExportar.setEnabled(true);
			botonImportar.setEnabled(false);
		} else {
			botonExportar.setEnabled(true);
			botonImportar.setEnabled(true);
		}

		// 5 Si tenemos elementos, construccin de todos los botones de
		// inventarios
		// comunes de la pagina:
		ArrayList<Integer> lista_claves = new ArrayList<Integer>();
		for (int i : matrizInventarios.keySet()) {
			lista_claves.add(i);
		}
		Collections.sort(lista_claves);
		Iterator<Integer> iterator_inventarios_id = lista_claves.iterator();
		System.out.println("::::: InventarioMainboard 1010 ");
		while (iterator_inventarios_id.hasNext() == true) {

			// Recupermos los datos:
			final int id_inventario = iterator_inventarios_id.next();
			
			if (id_inventario > 0) {
				final HashMap<String, String> hashmapUnInventario = matrizInventarios
						.get(id_inventario);

				// Consulta de la completud del inventario:
				ArrayList<Integer> listaEstadisticas = bdd
						.selectEstadisticasConIdInventario(id_inventario);
				int cantidadArticulosEnInventario = listaEstadisticas.get(0);
				int articulosYaContadosEnInventario = listaEstadisticas.get(1);

				// CREACIN DE LA LINEA:
				LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
				TableRow nuevaLinea = (TableRow) inflater.inflate(
						R.layout.z_lineaprogressbar_mainboard, null);
				nuevaLinea
						.setId(ParametrosInventario.ID_LINEAS + id_inventario);

				// Elemento 1 = boton:
				Button b = (Button) nuevaLinea.findViewById(R.id.LPB2_boton);
				if (id_inventario >= 0) {
					b.setText("Inventario " + String.valueOf(id_inventario));
				} else {
					b.setText("Inv. dinamico "
							+ String.valueOf(Math.abs(id_inventario)));
				}
				b.setId(ParametrosInventario.ID_BOTONES + id_inventario);
				
				System.out.println("::: InventarioMainboard 1044 Ver id_inventario " + id_inventario);

				// Elemento 2 = texto del NOMBRE:
				TextView textoNombre = (TextView) nuevaLinea
						.findViewById(R.id.LPB2_nombre);
				textoNombre.setText(hashmapUnInventario.get(
						ParametrosInventario.bal_bdd_inventario_descripcion)
						.trim());

				// Elemento 3 = texto de la FECHA de CREACION:
				TextView textoFecha = (TextView) nuevaLinea
						.findViewById(R.id.LPB2_inicio);
				textoFecha.setText(hashmapUnInventario.get(
						ParametrosInventario.bal_bdd_inventario_fechaInicio)
						.trim());

				// Elemento 4 = PROGRESS-BAR:
				TextView tv_progressbar = (TextView) nuevaLinea
						.findViewById(R.id.LPB2_texto_progressbar);
				String texto_estadisticas_progresion = String
						.valueOf(articulosYaContadosEnInventario)
						+ " de "
						+ String.valueOf(cantidadArticulosEnInventario);
				tv_progressbar.setText(texto_estadisticas_progresion);

				try {
					ProgressBar pb = (ProgressBar) nuevaLinea
							.findViewById(R.id.LPB2_progressbar);
					int newValue = 0;
					if (cantidadArticulosEnInventario != 0) {
						newValue = (int) Math
								.floor((double) articulosYaContadosEnInventario
										/ (double) cantidadArticulosEnInventario
										* (double) 100);
					}
				
					pb.setProgress(newValue);
				} catch (Exception e) {
					e.printStackTrace();
				}

				// Elemento 5 = CANDADO:
				ImageView candado = (ImageView) nuevaLinea
						.findViewById(R.id.LPB2_estado);
				if (Integer.parseInt(hashmapUnInventario
						.get(ParametrosInventario.bal_bdd_inventario_estado)) == 1) {
					System.out.println("::: InventarioMainboard 1080 candado");
					candado.setImageDrawable(getResources().getDrawable(
							R.drawable.candado_ab));
				} else {
					System.out.println("::: InventarioMainboard 1084 candado");
					candado.setImageDrawable(getResources().getDrawable(
							R.drawable.candado_cer));
				}

				// Creacin del handler:
				b.setOnClickListener(new View.OnClickListener() {
					public void onClick(@NonNull View v) {

						log.log("[-- 994 --]" + "Presion un inventario ", 0);
						BaseDatos bdd = new BaseDatos(ctxt);

						try {
							if (bdd.estaAbiertoInventarioConId(v.getId()
									- ParametrosInventario.ID_BOTONES) == true) {
								ClicBoton((Button) v);
							} else {
								log.log("[-- 1002 --]"
										+ "Inventario cerrado con candado", 3);
								Toast.makeText(ctxt,
										"Inventario cerrado con candado",
										Toast.LENGTH_LONG).show();
							}
						} catch (ExceptionBDD e) {

							log.log("[-- 1009 --]" + e.toString(), 4);
							e.printStackTrace();
							Toast.makeText(ctxt,
									"Inventario cerrado con candado",
									Toast.LENGTH_LONG).show();
						}

					}
				});

				b.setOnLongClickListener(new View.OnLongClickListener() {

					public boolean onLongClick(@NonNull View v) {

						log.log("[-- 1043 --]"
								+ "Se hizo un clic largo sobre un ionventario",
								0);
						try {
							final int id_invent_con_boton = v.getId()
									- ParametrosInventario.ID_BOTONES;
							BaseDatos bdd = new BaseDatos(ctxt);

							if (bdd.estaAbiertoInventarioConId(id_invent_con_boton) == true) {
								View.OnClickListener listenerPositivo = new View.OnClickListener() {

									public void onClick(View v) {

										log.log("[-- --]"
												+ "Se presion el boton para borrar el inventario",
												0);
										// Aqui borramos el inventario:
										BaseDatos bdd = new BaseDatos(ctxt);
										try {
											bdd.borrarInventarioConArticulos(id_invent_con_boton);
										} catch (ExceptionBDD e) {

											log.log("[-- 1065 --]"
													+ e.toString(), 4);
											e.printStackTrace();
										}

										try {
											refreshTablaPrincipal();
										} catch (ExceptionBDD e) {

											log.log("[-- 1073 --]"
													+ e.toString(), 4);
											e.printStackTrace();
										} catch (Exception e) {

											log.log("[-- 1077 --]"
													+ e.toString(), 4);
											e.printStackTrace();
										}

										dialogoBorrarInventario.dismiss();
									}
								};

								View.OnClickListener listenerNegativo = new View.OnClickListener() {

									public void onClick(View v) {

										log.log("[-- --]"
												+ "Se presiono cancelar", 0);
										dialogoBorrarInventario.cancel();
									}
								};

								dialogoBorrarInventario = new DialogPersoComplexSiNo(
										ctxt,
										"SUPRIMIR INVENTARIO",
										"Usted esta a punto de suprimir el inventario n"
												+ String.valueOf(id_invent_con_boton)
												+ "\n\n"
												+ "Esta seguro de querer suprimir este inventario?",
										DialogPerso.ALERTAR, listenerPositivo,
										listenerNegativo);
								dialogoBorrarInventario.show();
							} else {
								Toast.makeText(
										ctxt,
										"Supresion imposible: inventario cerrado con candado",
										Toast.LENGTH_LONG).show();
							}

						} catch (ExceptionBDD e) {

							log.log("[-- 1114 --]" + e.toString(), 4);
							e.printStackTrace();
							Toast.makeText(ctxt,
									"Inventario cerrado con candado",
									Toast.LENGTH_LONG).show();

							log.log("[-- 1120 --]"
									+ "Inventario cerrado con candado", 3);
						}

						return true;
					}

				});

				// Creacin de los handlers:
				candado.setOnClickListener(new View.OnClickListener() {

					public void onClick(View v) {
						log.log("[-- 1133 --]" + "Se presiono el candado", 0);

						try {
							ImageView iv = (ImageView) v;

							BaseDatos bdd = new BaseDatos(ctxt);

							if (Integer.parseInt(hashmapUnInventario
									.get(ParametrosInventario.bal_bdd_inventario_estado)) == ParametrosInventario.INVENTARIO_ABIERTO) {

								bdd.updateInventario(
										Integer.parseInt(hashmapUnInventario
												.get(ParametrosInventario.bal_bdd_inventario_numero)),
										ParametrosInventario.INVENTARIO_CERRADO);
								hashmapUnInventario
										.put(ParametrosInventario.bal_bdd_inventario_estado,
												String.valueOf(ParametrosInventario.INVENTARIO_CERRADO));
								iv.setImageDrawable(getResources().getDrawable(
										R.drawable.candado_cer));
							} else {
								bdd.updateInventario(
										Integer.parseInt(hashmapUnInventario
												.get(ParametrosInventario.bal_bdd_inventario_numero)),
										ParametrosInventario.INVENTARIO_ABIERTO);
								hashmapUnInventario
										.put(ParametrosInventario.bal_bdd_inventario_estado,
												String.valueOf(ParametrosInventario.INVENTARIO_ABIERTO));
								iv.setImageDrawable(getResources().getDrawable(
										R.drawable.candado_ab));
							}
						} catch (Exception e) {

							log.log("[-- 1164 --]" + e.toString(), 4);
							e.printStackTrace();
						} catch (ExceptionBDD e) {

							log.log("[-- 1168 --]" + e.toString(), 4);
							e.printStackTrace();
						}
					}
				});

				// AGREGAMOS LA LINEA A LA TABLA:
				tablaPrincipal.addView(nuevaLinea);

			} else {
				
				System.out.println("::::: InvMain 1253 " + matrizInventarios);
				// Meter los dinamicos en un arreglo
				matrizInventariosDinamicos.put(id_inventario,
						matrizInventarios.get(id_inventario));
			}  

		} // end while

		/**
		 * Trabajo que se hace para los inventarios dinmicos similar a los
		 * otros pero con un tratamiento especial por que es un boton que esta
		 * siempre y fijo y tiene una funcionalidad definida
		 */
		// 6 Creacion de estructuras y la linea del inventario dinmico
		// HashMap<String,String>
		// hashmapInventarioVenta,hashmapInventarioDeposito;

		// Verificamos que no hayan inventarios dinamicos para crear una linea
		// vacia
		if (matrizInventariosDinamicos.size() == 0) {
			hayDinamicos = false;
		} else {
			// Caso en el que hay inventarios dinamicos de antes
			hayDinamicos = true;
		}
		System.out.println("::: INVDIN 1300 //////////////////////");
		
		hashmapInventarioVenta = matrizInventariosDinamicos
				.get(ParametrosInventario.ID_INV_DIN_VTA);
		hashmapInventarioDeposito = matrizInventariosDinamicos
				.get(ParametrosInventario.ID_INV_DIN_DEP);

		// ArrayList<Integer> lista_claves_dinamicos = new ArrayList<Integer>();
		//
		// if(hayDinamicos) {
		// //Variable para los id de los inventarios dinamicos
		//
		// for (int i : matrizInventariosDinamicos.keySet()){
		// lista_claves_dinamicos.add(i);
		// }
		// Collections.sort(lista_claves_dinamicos);
		// }
		boolean condicionRadio = ParametrosInventario.InventariosVentas;
		
		int id_inv_ficticio = 0;
		if(condicionRadio){
//			// Esta seleccionado ventas, esto debe continuar sin los campos de deposito
			id_inv_ficticio = -1;
		}else{
//			// Esta seleccionado deposito, esto debe continuar sin los campos de ventas
			id_inv_ficticio = -2;
		}
		
		//Se agrega para que lea el parametro y se pase el valor del inventario correcto o seleccinado
		// No deberia tener un numero generico
//		int id_inv_ficticio = -1;
		
		// Crear la linea del inventario dinamico ficticio
		// Consulta de la completud del inventario, como es una linea ficticia,
		// es 0
		ArrayList<Integer> listaEstadisticas = new ArrayList<Integer>();
		int articulosTotalesQueInventariar = 0, articulosNonInventariados = 0;

		int cantidadArticulosEnInventario = 0, articulosYaContadosEnInventario = 0;
		// Si es ficticio es 0
		if (hayDinamicos) {
			
			ArrayList<Integer> listaEstadisticasVenta;
			ArrayList<Integer> listaEstadisticasDepo;
			
			// Buscar info en la base de datos y completar las variables
			if(condicionRadio == true){
				
				listaEstadisticasVenta = bdd
						.selectEstadisticasConIdInventario(ParametrosInventario.ID_INV_DIN_VTA);

				cantidadArticulosEnInventario = listaEstadisticasVenta.get(0);
				articulosYaContadosEnInventario = listaEstadisticasVenta.get(1);
			}else{
				listaEstadisticasDepo = bdd
						.selectEstadisticasConIdInventario(ParametrosInventario.ID_INV_DIN_DEP);
				cantidadArticulosEnInventario = listaEstadisticasDepo.get(0);
				articulosYaContadosEnInventario = listaEstadisticasDepo.get(1);
			}
//			ArrayList<Integer> listaEstadisticasVenta = bdd
//					.selectEstadisticasConIdInventario(ParametrosInventario.ID_INV_DIN_VTA);
//
//			ArrayList<Integer> listaEstadisticasDepo = bdd
//					.selectEstadisticasConIdInventario(ParametrosInventario.ID_INV_DIN_DEP);
//
//			cantidadArticulosEnInventario = listaEstadisticasVenta.get(0)
//					+ listaEstadisticasDepo.get(0);
//
//			articulosYaContadosEnInventario = listaEstadisticasVenta.get(1)
//					+ listaEstadisticasDepo.get(1);

			
		} else {
			listaEstadisticas.add(articulosTotalesQueInventariar);
			listaEstadisticas.add(articulosTotalesQueInventariar
					- articulosNonInventariados);
			listaEstadisticas.add(articulosNonInventariados);
			cantidadArticulosEnInventario = listaEstadisticas.get(0);
			articulosYaContadosEnInventario = listaEstadisticas.get(1);
		}
		System.out.println("::: INVDIN 1347 cantidadArticulosEnInventario "+ cantidadArticulosEnInventario);
		System.out.println("::: INVDIN 1347 articulosYaContadosEnInventario "+ articulosYaContadosEnInventario);
		
		
		
		System.out.println("::: INVDIN 1347 Creacion de la linea ");
		// CREACIN DE LA LINEA:
		LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
		TableRow nuevaLinea = (TableRow) inflater.inflate(
				R.layout.z_lineaprogressbar_mainboard, null);
		nuevaLinea.setId(ParametrosInventario.ID_LINEAS + id_inv_ficticio);
		// nuevaLinea.setId(ParametrosInventario.ID_LINEA_DINAMICO);
		System.out.println("::: INVDIN 1347 Creacion de la linea id_inv_ficticio " + id_inv_ficticio);
		// Elemento 1 = boton:
		Button b = (Button) nuevaLinea.findViewById(R.id.LPB2_boton);
		b.setText("Inventarios Dinamicos ");
		b.setId(ParametrosInventario.ID_BOTONES + id_inv_ficticio);

		// Elemento 2 = texto del NOMBRE:
		TextView textoNombre = (TextView) nuevaLinea
				.findViewById(R.id.LPB2_nombre);
		textoNombre.setText("Inventario Dinmico");

		// Elemento 3 = texto de la FECHA de CREACION:
		TextView textoFecha = (TextView) nuevaLinea
				.findViewById(R.id.LPB2_inicio);
		if (hayDinamicos) {
			// Buscar la fecha menor de los dos inventarios
			String fecha="";
//			boolean condicionRadio = ParametrosInventario.InventariosVentas;
			if(condicionRadio == true){
				// Esta seleccionado ventas, esto debe continuar sin los campos de deposito
				condR=-1;
			}else{
				// Esta seleccionado deposito, esto debe continuar sin los campos de ventas
				condR=-2;
			}
			System.out.println("::: InventarioMainBoard 1367 condR == " + condR);
			if(condR == -1){
				String fechaIVta = hashmapInventarioVenta.get(
						ParametrosInventario.bal_bdd_inventario_fechaInicio).trim();
				fecha = hashmapInventarioVenta.get(
						ParametrosInventario.bal_bdd_inventario_fechaInicio)
						.trim();
			}else if(condR == -2){
				String fechaIDep = hashmapInventarioDeposito.get(
						ParametrosInventario.bal_bdd_inventario_fechaInicio).trim();
				fecha = hashmapInventarioDeposito.get(
						ParametrosInventario.bal_bdd_inventario_fechaInicio)
						.trim();
			}
			
			// SimpleDateFormat sdf= new
			// SimpleDateFormat("yyyy-MM-ddm hh:mm:ss");

			// Date fechaVenta=sdf.parse(fechaIVta);
			// Date fechaDepo=sdf.parse(fechaIDep);

			// if(fechaVenta.compareTo(fechaDepo)<0) {
			// fecha=hashmapInventarioVenta.get(ParametrosInventario.bal_bdd_inventario_fechaInicio).trim();
			// }else {
			// fecha=hashmapInventarioDeposito.get(ParametrosInventario.bal_bdd_inventario_fechaInicio).trim();
			// }

			
/*
 * Esto estaba asi pero se arma de otra forma para separar los inventarios
 * Damian 10/11/2015
 * 			
			if (fechaIVta.compareTo(fechaIDep) < 0) {
				fecha = hashmapInventarioVenta.get(
						ParametrosInventario.bal_bdd_inventario_fechaInicio)
						.trim();
			} else {
				fecha = hashmapInventarioDeposito.get(
						ParametrosInventario.bal_bdd_inventario_fechaInicio)
						.trim();
			}
*
*
*
*/

			textoFecha.setText(fecha);
		} else {
			textoFecha.setText("");
		}

		// Elemento 4 = PROGRESS-BAR:
		TextView tv_progressbar = (TextView) nuevaLinea
				.findViewById(R.id.LPB2_texto_progressbar);
		String texto_estadisticas_progresion = String
				.valueOf(articulosYaContadosEnInventario)
				+ " de "
				+ String.valueOf(cantidadArticulosEnInventario);
		tv_progressbar.setText(texto_estadisticas_progresion);

		try {
			ProgressBar pb = (ProgressBar) nuevaLinea
					.findViewById(R.id.LPB2_progressbar);
			int newValue = 0;
			if (cantidadArticulosEnInventario != 0) {
				newValue = (int) Math
						.floor((double) articulosYaContadosEnInventario
								/ (double) cantidadArticulosEnInventario
								* (double) 100);
			}
			pb.setProgress(newValue);
		} catch (Exception e) {

			log.log("[-- 1326 --]" + e.toString(), 4);
			e.printStackTrace();
		}

		// Elemento 5 = CANDADO:
		ImageView candado = (ImageView) nuevaLinea
				.findViewById(R.id.LPB2_estado);
		if (hayDinamicos) {
			// Se verifica que esten los dos cerrados
			int estadoCandadoDepo = 0;
			int estadoCandadoVta = 0;
			System.out.println("::: InventarioMainBoard 1451 Antes de ir a bd");
			if(condR == -1){
				
				estadoCandadoVta = Integer.parseInt(hashmapInventarioVenta
						.get(ParametrosInventario.bal_bdd_inventario_estado));
				
				if (estadoCandadoVta == 1){
					candado.setImageDrawable(getResources().getDrawable(
							R.drawable.candado_ab));
				} else {
					candado.setImageDrawable(getResources().getDrawable(
							R.drawable.candado_cer));
				}
				
			}else if(condR == -2){
				
				estadoCandadoDepo = Integer.parseInt(hashmapInventarioDeposito
						.get(ParametrosInventario.bal_bdd_inventario_estado));
				
				if (estadoCandadoDepo == 1){
					candado.setImageDrawable(getResources().getDrawable(
							R.drawable.candado_ab));
				} else {
					candado.setImageDrawable(getResources().getDrawable(
							R.drawable.candado_cer));
				}
				
			}
			
//			if (estadoCandadoVta == 1){
//				candado.setImageDrawable(getResources().getDrawable(
//						R.drawable.candado_ab));
//			}if (estadoCandadoDepo == 1){
//				candado.setImageDrawable(getResources().getDrawable(
//						R.drawable.candado_ab));
//			} else {
//				candado.setImageDrawable(getResources().getDrawable(
//						R.drawable.candado_cer));
//			}
/*
 * 
 * Esto se comenta y modifica para la division de los inventarios ventas y depositos
 * Damian 10/11/2015			
			
			int estadoCandadoVta = Integer.parseInt(hashmapInventarioVenta
					.get(ParametrosInventario.bal_bdd_inventario_estado));
			int estadoCandadoDepo = Integer.parseInt(hashmapInventarioDeposito
					.get(ParametrosInventario.bal_bdd_inventario_estado));
			if ((estadoCandadoVta == 1) && (estadoCandadoDepo == 1)) {
				candado.setImageDrawable(getResources().getDrawable(
						R.drawable.candado_ab));
			} else {
				candado.setImageDrawable(getResources().getDrawable(
						R.drawable.candado_cer));
			}
*
*
*
*/			
		} else {
			// Se dibuja abierto
			candado.setImageDrawable(getResources().getDrawable(
					R.drawable.candado_ab));
		}
		// Creacin del handler del boton:
		b.setOnClickListener(new View.OnClickListener() {
			public void onClick(@NonNull View v) {
				BaseDatos bdd = new BaseDatos(ctxt);

				if (hayDinamicos) {
					
//					if(condR==-1){
						try {
//System.out.println("::: InventarioMainboard 1524 vta que id es el q pasa -1 " + v.getId() );
							if(condR==-1){
								if (bdd.estaAbiertoInventarioConId(v.getId()
										- ParametrosInventario.ID_BOTONES) == true) {
									ClicBotonDinamico((Button) v);
								} else {

									log.log("[-- --]"
											+ "Inventario cerrado con candado", 3);
									Toast.makeText(ctxt,
											"Inventario cerrado con candado",
											Toast.LENGTH_LONG).show();
								}
							}else if(condR==-2){
								if (bdd.estaAbiertoInventarioConId(v.getId()
										- ParametrosInventario.ID_BOTONES) == true) {
									ClicBotonDinamico((Button) v);
								} else {

									log.log("[-- --]"
											+ "Inventario cerrado con candado", 3);
									Toast.makeText(ctxt,
											"Inventario cerrado con candado",
											Toast.LENGTH_LONG).show();
								}
							}
							
//							if (bdd.estaAbiertoInventarioConId(v.getId()
//									- ParametrosInventario.ID_BOTONES) == true) {
//								ClicBotonDinamico((Button) v);
//							} else {
//
//								log.log("[-- --]"
//										+ "Inventario cerrado con candado", 3);
//								Toast.makeText(ctxt,
//										"Inventario cerrado con candado",
//										Toast.LENGTH_LONG).show();
//							}
							
							
						} catch (ExceptionBDD e) {

							log.log("[-- 1372 --]" + e.toString(), 3);
							e.printStackTrace();
							Toast.makeText(ctxt, "Inventario cerrado con candado",
									Toast.LENGTH_LONG).show();
						}
//					}else if(condR==-2){
//						try {
//							System.out.println("::: InventarioMainboard 1545 dep que id es el q pasa -2 " + v.getId() );
//							if (bdd.estaAbiertoInventarioConId(v.getId()
//									- ParametrosInventario.ID_BOTONES) == true) {
//								ClicBotonDinamico((Button) v);
//							} else {
//
//								log.log("[-- --]"
//										+ "Inventario cerrado con candado", 3);
//								Toast.makeText(ctxt,
//										"Inventario cerrado con candado",
//										Toast.LENGTH_LONG).show();
//							}
//						} catch (ExceptionBDD e) {
//
//							log.log("[-- 1372 --]" + e.toString(), 3);
//							e.printStackTrace();
//							Toast.makeText(ctxt, "Inventario cerrado con candado",
//									Toast.LENGTH_LONG).show();
//						}
//					}
//					try {
//						if (bdd.estaAbiertoInventarioConId(v.getId()
//								- ParametrosInventario.ID_BOTONES) == true) {
//							ClicBotonDinamico((Button) v);
//						} else {
//
//							log.log("[-- --]"
//									+ "Inventario cerrado con candado", 3);
//							Toast.makeText(ctxt,
//									"Inventario cerrado con candado",
//									Toast.LENGTH_LONG).show();
//						}
//					} catch (ExceptionBDD e) {
//
//						log.log("[-- 1372 --]" + e.toString(), 3);
//						e.printStackTrace();
//						Toast.makeText(ctxt, "Inventario cerrado con candado",
//								Toast.LENGTH_LONG).show();
//					}
				} else {
					ClicBotonDinamico((Button) v);
				}

			}
		});

		// Creacin de los handlers:
		candado.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				try {
					ImageView iv = (ImageView) v;

					int estadoCandadoVta = 0;
					int estadoCandadoDepo = 0;

					BaseDatos bdd = new BaseDatos(ctxt);

					if (hayDinamicos) {
						// Se verifica que esten los dos cerrados
if(condR == -1){
	
	estadoCandadoVta = Integer.parseInt(hashmapInventarioVenta
			.get(ParametrosInventario.bal_bdd_inventario_estado));
	
}else if(condR == -2){
	
	estadoCandadoDepo = Integer.parseInt(hashmapInventarioDeposito
			.get(ParametrosInventario.bal_bdd_inventario_estado));
	
}

/*
 * 
 * Se modifico para separar los inventarios 
 * Damian 10/11/2015
						estadoCandadoVta = Integer.parseInt(hashmapInventarioVenta
								.get(ParametrosInventario.bal_bdd_inventario_estado));
						estadoCandadoDepo = Integer.parseInt(hashmapInventarioDeposito
								.get(ParametrosInventario.bal_bdd_inventario_estado));
 * 
 * 
 * 
 */
						// estadoCandadoVta=bdd.getEstadoInventarioDinamico(ParametrosInventario.ID_INV_DIN_VTA);
						// estadoCandadoDepo=bdd.getEstadoInventarioDinamico(ParametrosInventario.ID_INV_DIN_DEP);
					} else {
						// Se dibuja abierto
					System.out.println("::: InventarioMainBoard 1604 aca no hace nada!!!!");
						/*
						 * ACA NO HAY NADA
						 * NOSE SI AGREGAR
						 */
					}
System.out.println("::: InventarioMainBoard 1667 estadoCandadoVta " + estadoCandadoVta);
System.out.println("::: InventarioMainBoard 1667 estadoCandadoDepo " + estadoCandadoDepo);
//System.out.println("::: InventarioMainBoard 1667 abierto " + ParametrosInventario.INVENTARIO_ABIERTO);
//System.out.println("::: InventarioMainBoard 1667 cerrado " + ParametrosInventario.INVENTARIO_CERRADO);
System.out.println("::: InventarioMainBoard 1667 inventario_estado " +ParametrosInventario.bal_bdd_inventario_estado);					



if(condR == -1){
	System.out.println("::: InventarioMainboard 1640");
	System.out.println("::: InventarioMainboard 1640 " + ParametrosInventario.INVENTARIO_ABIERTO);
	System.out.println("::: InventarioMainboard 1640 " + estadoCandadoVta);
	if (estadoCandadoVta == ParametrosInventario.INVENTARIO_ABIERTO){
		// Actualizamos, cerrando el inventario dinamico de
		// venta
		System.out.println("::: InventarioMainboard 1645");
		bdd.updateInventario(
				ParametrosInventario.ID_INV_DIN_VTA,
				ParametrosInventario.INVENTARIO_CERRADO);
		hashmapInventarioVenta
				.put(ParametrosInventario.bal_bdd_inventario_estado,
						String.valueOf(ParametrosInventario.INVENTARIO_CERRADO));
		iv.setImageDrawable(getResources().getDrawable(
				R.drawable.candado_cer));
		System.out.println("::: InventarioMainboard 1654");
	} else {
		// Los guardo como abiertos
		System.out.println("::: InventarioMainboard 1657");
		bdd.updateInventario(
				ParametrosInventario.ID_INV_DIN_VTA,
				ParametrosInventario.INVENTARIO_ABIERTO);
		hashmapInventarioVenta
				.put(ParametrosInventario.bal_bdd_inventario_estado,
						String.valueOf(ParametrosInventario.INVENTARIO_ABIERTO));
		iv.setImageDrawable(getResources().getDrawable(
				R.drawable.candado_ab));
		System.out.println("::: InventarioMainboard 1666");
	}
	
}else if(condR == -2){
	System.out.println("::: InventarioMainboard 1670");
	System.out.println("::: InventarioMainboard 1670 " + ParametrosInventario.INVENTARIO_ABIERTO);
	System.out.println("::: InventarioMainboard 1670 " + estadoCandadoDepo);
	if (estadoCandadoDepo == ParametrosInventario.INVENTARIO_ABIERTO) {
		// Actualizamos, cerrando el inventario dinamico de
		// deposito
		System.out.println("::: InventarioMainboard 1674");
		bdd.updateInventario(
				ParametrosInventario.ID_INV_DIN_DEP,
				ParametrosInventario.INVENTARIO_CERRADO);
		hashmapInventarioDeposito
				.put(ParametrosInventario.bal_bdd_inventario_estado,
						String.valueOf(ParametrosInventario.INVENTARIO_CERRADO));
		System.out.println("::: InventarioMainboard 1681");
		iv.setImageDrawable(getResources().getDrawable(
				R.drawable.candado_cer));
		
	}else {
		System.out.println("::: InventarioMainboard 1686");
		bdd.updateInventario(
				ParametrosInventario.ID_INV_DIN_DEP,
				ParametrosInventario.INVENTARIO_ABIERTO);
		hashmapInventarioDeposito
				.put(ParametrosInventario.bal_bdd_inventario_estado,
						String.valueOf(ParametrosInventario.INVENTARIO_ABIERTO));
		iv.setImageDrawable(getResources().getDrawable(
				R.drawable.candado_ab));
	}
	
	
}
/*
 * 
 * Se modifico para la division de inventarios
 * Damian 10/11/2015
					if ((estadoCandadoVta == ParametrosInventario.INVENTARIO_ABIERTO)
							&& (estadoCandadoDepo == ParametrosInventario.INVENTARIO_ABIERTO)) {
						// Actualizamos, cerrando el inventario dinamico de
						// venta y el de deposito
						bdd.updateInventario(
								ParametrosInventario.ID_INV_DIN_VTA,
								ParametrosInventario.INVENTARIO_CERRADO);
						bdd.updateInventario(
								ParametrosInventario.ID_INV_DIN_DEP,
								ParametrosInventario.INVENTARIO_CERRADO);
						hashmapInventarioVenta
								.put(ParametrosInventario.bal_bdd_inventario_estado,
										String.valueOf(ParametrosInventario.INVENTARIO_CERRADO));
						hashmapInventarioDeposito
								.put(ParametrosInventario.bal_bdd_inventario_estado,
										String.valueOf(ParametrosInventario.INVENTARIO_CERRADO));
						iv.setImageDrawable(getResources().getDrawable(
								R.drawable.candado_cer));
					} else {
						// Los guardo como abiertos
						bdd.updateInventario(
								ParametrosInventario.ID_INV_DIN_VTA,
								ParametrosInventario.INVENTARIO_ABIERTO);
						bdd.updateInventario(
								ParametrosInventario.ID_INV_DIN_DEP,
								ParametrosInventario.INVENTARIO_ABIERTO);
						hashmapInventarioVenta
								.put(ParametrosInventario.bal_bdd_inventario_estado,
										String.valueOf(ParametrosInventario.INVENTARIO_ABIERTO));
						hashmapInventarioDeposito
								.put(ParametrosInventario.bal_bdd_inventario_estado,
										String.valueOf(ParametrosInventario.INVENTARIO_ABIERTO));
						iv.setImageDrawable(getResources().getDrawable(
								R.drawable.candado_ab));
					}
*
*
*
*/
					
				} catch (Exception e) {

					log.log("[-- 1449 --]" + e.toString(), 4);

					e.printStackTrace();
				} catch (ExceptionBDD e) {

					log.log("[-- 1454 --]" + e.toString(), 4);
					e.printStackTrace();
				}
			}
		});

		// AGREGAMOS LA LINEA A LA TABLA:
		tablaPrincipal.addView(nuevaLinea);

		desactivarWifi();

	}// Fin de la funcin

	/**
	 * Cuando se presione el boton "back" se cierra
	 */

	public void onBackPressed() {
		finish();
	}

	public boolean onKeyDown(int keyCode, @NonNull KeyEvent event) {

		log.log("[-- 1477 --]" + "Se presiono la tecla: " + keyCode, 1);
		if (keyCode == KeyEvent.KEYCODE_HOME && event.getRepeatCount() == 0) {
			finish();
		}

		return super.onKeyDown(keyCode, event);
	}

	/**
	 * Metodo para mostrar un popup cuando se importan los inventarios
	 */
	private void popupStart() {
		popupCarga = new ProgressDialog(ctxt);
		popupCarga.setCancelable(false);
		popupCarga.setMessage("Importando los datos de inventarios...");
		popupCarga.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		popupCarga.setProgress(0);
		popupCarga.setMax(100);
		popupCarga.show();

		log.log("[-- 1479 --]" + "Inicia pop up cuando termina la importacion",
				2);
	}

	/**
	 * Sube un porcentaje el popUp de progreso
	 * 
	 * @param hastaXPorciento
	 */
	private void popupSubir(int hastaXPorciento) {
		popupCarga.setProgress(hastaXPorciento);
	}

	private void popupEnd() {
		popupCarga.dismiss();
	}

	/**
	 * Metodo que manejea el funcionamiento de los botones de la tabla al
	 * hacerles click en el caso comun, entra a la activity
	 * PaginaInventario.java, pasando como parmetro el valor del numero de
	 * inventario asociado al boton
	 * 
	 * @param boton
	 */
	private void ClicBoton(@NonNull Button boton) {
		int numeroInventarioAsociadoAlBoton = (boton.getId() - ParametrosInventario.ID_BOTONES);
		Intent intentInventario = new Intent(ctxt, PaginaInventario.class);
		intentInventario.putExtra(ParametrosInventario.extra_numeroInventario,
				numeroInventarioAsociadoAlBoton);
		// intentInventario.putExtra(ParametrosInventario.extra_bandera_invs_dinamicos,
		// ParametrosInventario.extra_valor_bandera_invs_dinamicos_no);
		startActivityForResult(intentInventario,
				ParametrosInventario.REQUEST_INVENTARIO);
	}

	/**
	 * El boton de inventario dinmico entra a la activity
	 * PaginaInventarioDinamico.java adems se agrega la funcionalidad de que se
	 * cargue la pantalla de confirmacin de continuar con el inventario o
	 * borrar y empezar con uno nuevo
	 * <p>
	 * 1 Si hay inventarios creados debe preguntar por eliminar o seguir con el
	 * anterior
	 * <p>
	 * &nbsp; &nbsp;1.1 Genera un dialog que pregunta si se continua con el
	 * inventario o se borra y genera algo nuevo
	 * <p>
	 * &nbsp; &nbsp;&nbsp; &nbsp;1.1.1 En caso positivo pasa al inventario
	 * actual
	 * <p>
	 * &nbsp; &nbsp;&nbsp; &nbsp;1.1.2 En caso negativo muestra otro cartel para
	 * verificar si borra
	 * <p>
	 * &nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;1.1.2.1 En caso de que quiera
	 * borrar se elimina y genera uno nuevo pasando a la Pagina correspondiente
	 * <p>
	 * &nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;1.1.2.2 En caso de que no quiera
	 * borrar, se vuelve a la pantalla principal
	 * <p>
	 * 2 Si no hay inventarios , Se deben crear 2 inventarios (uno para venta y
	 * otro para deposito)
	 * <p>
	 * &nbsp; &nbsp;2.1 Creo los objetos para los dos inventarios nuevos
	 * <p>
	 * &nbsp; &nbsp;2.2 Insertamos en la base de datos
	 * <p>
	 * &nbsp; &nbsp;2.3 Pasamos a la pantalla de administracin de inventario
	 * dinamico
	 * 
	 * @param boton
	 */
	private void ClicBotonDinamico(Button boton) {
		// 1 Si hay inventarios creados debe preguntar por eliminar o seguir
		// con
		// el anterior
		if (hayDinamicos) {
			// 1.1.1 En caso positivo pasa al inventario actual
			View.OnClickListener listenerPositivo = new View.OnClickListener() {

				public void onClick(View v) {
					// Lo que hace con el boton del si

					log.log("[-- --]"
							+ "Presiono para ir a los inventarios dinamicos", 0);
					dialogoContinuarInventario.dismiss();

					Intent intentInventario = new Intent(ctxt,
							PaginaInventarioDinamico.class);
					intentInventario.putExtra(
							ParametrosInventario.extra_numeroInventario,
							ParametrosInventario.ID_INV_DIN_VTA);
					// intentInventario.putExtra(ParametrosInventario.extra_numeroInventarioDinDepo,
					// ParametrosInventario.ID_INV_DIN_DEP);
					// intentInventario.putExtra(ParametrosInventario.extra_bandera_invs_dinamicos,
					// ParametrosInventario.extra_valor_bandera_invs_dinamicos_si);

					startActivityForResult(intentInventario,
							ParametrosInventario.REQUEST_INVENTARIO_DINAMICO);
				}
			};
			// 1.1.2 En caso negativo muestra otro cartel para verificar si
			// borra
			View.OnClickListener listenerNegativo = new View.OnClickListener() {

				public void onClick(View v) {
					// Lo que hace con el no
					// Debe preguntar nuevamente para eliminar el inventario
					// guardado
					// Abrir otra ventana y preguntar si realmente quiere
					// eliminar los datos

					dialogoContinuarInventario.dismiss();

					// 1.1.2.1 En caso de que quiera borrar se elimina y genera
					// uno nuevo pasando a la
					// Pagina correspondiente
					View.OnClickListener listenerPositivo = new View.OnClickListener() {

						public void onClick(View v) {

							log.log("[-- 1617 --]" + "Se presiono el boton si",
									0);
							BaseDatos bdd = new BaseDatos(ctxt);

							// Lo que hace con el boton del si

							dialogoBorrarInventarioDinamico.dismiss();

							// Creamos los inventarios dinamicos
							Inventario inventarioDinamicoVenta = new Inventario(
									ParametrosInventario.ID_INV_DIN_VTA,
									"Inv. dinamico "
											+ String.valueOf(ParametrosInventario.ID_INV_DIN_VTA)
											+ " de venta",
									new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
											.format(new Date()),
									"",
									ParametrosInventario.INVENTARIO_ABIERTO,
									ParametrosInventario.COD_LUGAR_INVENTARIO_VENTA);

							Inventario inventarioDinamicoDepo = new Inventario(
									ParametrosInventario.ID_INV_DIN_DEP,
									"Inv. dinamico "
											+ String.valueOf(ParametrosInventario.ID_INV_DIN_DEP)
											+ " de deposito",
									new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
											.format(new Date()),
									"",
									ParametrosInventario.INVENTARIO_ABIERTO,
									ParametrosInventario.COD_LUGAR_INVENTARIO_DEPO);

							try {
								// Borrar datos del inventario
								bdd.borrarInventarioConArticulos(ParametrosInventario.ID_INV_DIN_VTA);
								bdd.borrarInventarioConArticulos(ParametrosInventario.ID_INV_DIN_DEP);
								// Crearlo de nuevo
								bdd.insertInventarioEnBdd(inventarioDinamicoVenta);
								bdd.insertInventarioEnBdd(inventarioDinamicoDepo);
								Toast.makeText(
										ctxt,
										"Se crearon los inventarios dinamicos nuevos",
										Toast.LENGTH_LONG).show();
							} catch (ExceptionBDD e) {

								log.log("[-- 1660 --]" + e.toString(), 4);
								// TODO Auto-generated catch block
								e.printStackTrace();
								Toast.makeText(
										ctxt,
										"Problema al borrar los inventarios de la BD"
												+ e.getMessage(),
										Toast.LENGTH_LONG).show();
							}

							Intent intentInventario = new Intent(ctxt,
									PaginaInventarioDinamico.class);
							intentInventario
									.putExtra(
											ParametrosInventario.extra_numeroInventario,
											ParametrosInventario.ID_INV_DIN_VTA);
							// intentInventario.putExtra(ParametrosInventario.extra_numeroInventarioDinDepo,
							// ParametrosInventario.ID_INV_DIN_DEP);
							// intentInventario.putExtra(ParametrosInventario.extra_bandera_invs_dinamicos,
							// ParametrosInventario.extra_valor_bandera_invs_dinamicos_si);

							startActivityForResult(
									intentInventario,
									ParametrosInventario.REQUEST_INVENTARIO_DINAMICO);
						}
					};

					// 1.1.2.2 En caso de que no quiera borrar, se vuelve a la
					// pantalla principal
					View.OnClickListener listenerNegativo = new View.OnClickListener() {

						public void onClick(View v) {
							log.log("[-- 1692 --]" + "Se presiono el boton no",
									0);
							// Lo que hace con el no
							// Debe preguntar nuevamente para eliminar el
							// inventario guardado
							// Abrir otra ventana y preguntar si realmente
							// quiere eliminar los datos

							dialogoBorrarInventarioDinamico.dismiss();

						}
					};

					dialogoBorrarInventarioDinamico = new DialogPersoComplexSiNo(
							ctxt,
							"Nuevo Inventario Dinamico",
							"Si genera un nuevo inventario se borrara cualquier " +
							"inventario dinamico en curso que se estuviera realizando aun no exportado.\nCUIDADO:"
									+ "Los datos no han sido exportados al sistema DEBO BackOffice para ser "
									+ "procesados para el correcto control de stock y se borraran",
							DialogPerso.ALERTAR, listenerPositivo,
							listenerNegativo);
//					dialogoBorrarInventarioDinamico = new DialogPersoComplexSiNo(
//							ctxt,
//							"Nuevo Inventario Dinmico",
//							"Esta seguro que desea generar un inventario dinmico nuevo?\nCUIDADO:"
//									+ "Los datos no han sido exportados al sistema DEBO BackOffice para ser "
//									+ "procesados para el correcto control de stock y se borraran",
//							DialogPerso.ALERTAR, listenerPositivo,
//							listenerNegativo);
					dialogoBorrarInventarioDinamico.show();
				}
			};
			// 1.1 Genera un dialog que pregunta si se continua con el
			// inventario o se
			// borra y genera algo nuevo
			dialogoContinuarInventario = new DialogPersoComplexSiNo(
					ctxt,
					"Continuar Inventario Dinamico",
					"Desea continuar trabajando con el inventario dinamico actual?",
					DialogPerso.VALIDAR, listenerPositivo, listenerNegativo);

			dialogoContinuarInventario.show();

		} else {
			// 2 Si no hay inventarios , Se deben crear 2 inventarios (uno para
			// venta y otro para deposito)
			// Logica de creacion de los inventarios dinamicos, las ponemos aca

			// Proceso de creacin del inventario nuevo:

			bdd = new BaseDatos(ctxt);

			// 2.1 Creo los objetos para los dos inventarios nuevos
			final Inventario inventarioDinamicoVenta = new Inventario(
					ParametrosInventario.ID_INV_DIN_VTA,
					"Inv. dinamico "
							+ String.valueOf(ParametrosInventario.ID_INV_DIN_VTA)
							+ " de venta", new SimpleDateFormat(
							"yyyy-MM-dd HH:mm:ss").format(new Date()), "",
					ParametrosInventario.INVENTARIO_ABIERTO,
					ParametrosInventario.COD_LUGAR_INVENTARIO_VENTA);

			final Inventario inventarioDinamicoDepo = new Inventario(
					ParametrosInventario.ID_INV_DIN_DEP,
					"Inv. dinamico "
							+ String.valueOf(ParametrosInventario.ID_INV_DIN_DEP)
							+ " de deposito", new SimpleDateFormat(
							"yyyy-MM-dd HH:mm:ss").format(new Date()), "",
					ParametrosInventario.INVENTARIO_ABIERTO,
					ParametrosInventario.COD_LUGAR_INVENTARIO_DEPO);

			// 2.2 Insertamos en la base de datos:
			try {
//				if (ParametrosInventario.InventariosVentas == true) {
				bdd.insertInventarioEnBdd(inventarioDinamicoVenta);
				bdd.insertInventarioEnBdd(inventarioDinamicoDepo);
				Toast.makeText(ctxt,
						"Se crearon los inventarios dinamicos nuevos",
						Toast.LENGTH_LONG).show();
				try {
					refreshTablaPrincipal();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} catch (ExceptionBDD e) {
				log.log("[-- 1769 --]" + e.toString(), 4);
				showSimpleDialogOK("Error",
						"La creacion del inventario fue cancelada").show();
			}

			// 2.3 Pasamos a la pantalla de administracion de inventario
			// dinamico
			Intent intentInventario = new Intent(ctxt,
					PaginaInventarioDinamico.class);
			intentInventario.putExtra(
					ParametrosInventario.extra_numeroInventarioDinVta,
					ParametrosInventario.ID_INV_DIN_VTA);
			// intentInventario.putExtra(ParametrosInventario.extra_numeroInventarioDinDepo,
			// ParametrosInventario.ID_INV_DIN_DEP);
			// intentInventario.putExtra(ParametrosInventario.extra_bandera_invs_dinamicos,
			// ParametrosInventario.extra_valor_bandera_invs_dinamicos_si);
			startActivityForResult(intentInventario,
					ParametrosInventario.REQUEST_INVENTARIO_DINAMICO);
		}

	}

	/**
	 * Refresca una linea de la tabla
	 */
	public void refreshLinea(@NonNull TableRow unaLinea) throws ExceptionBDD {
		try {
			int numeroInventario = unaLinea.getId()
					- ParametrosInventario.ID_LINEAS;
			// Consulta de la completud de la inventario:
			ArrayList<Integer> listaEstadisticas = bdd
					.selectEstadisticasConIdInventario(numeroInventario);
			int cantidadArticulosEnInventario = listaEstadisticas.get(0);
			int articulosYaContadosEnInventario = listaEstadisticas.get(1);
			int articulosNoContadosTodavia = listaEstadisticas.get(2);

			RelativeLayout unRelativeLayout = (RelativeLayout) unaLinea
					.getChildAt(1);
			ProgressBar unaProgressBar = (ProgressBar) unRelativeLayout
					.getChildAt(0);
			TextView unTextoDeProgressBar = (TextView) unRelativeLayout
					.getChildAt(1);
			TextView unTextoDeProgresion = (TextView) unaLinea.getChildAt(2);

			int newValue = (int) Math
					.floor((double) articulosYaContadosEnInventario
							/ (double) cantidadArticulosEnInventario
							* (double) 100);
			unaProgressBar.setProgress(newValue);

			unTextoDeProgressBar.setText(String.valueOf(newValue) + " %");

			unTextoDeProgresion.setText(String
					.valueOf(articulosYaContadosEnInventario)
					+ " / "
					+ String.valueOf(cantidadArticulosEnInventario));

			if (articulosNoContadosTodavia == 0) {
				unaLinea.setBackgroundColor(Color.GREEN);
			} else {
				unaLinea.setBackgroundColor(Color.TRANSPARENT);
			}
		} catch (Exception e) {

			log.log("[-- 1834 --]" + e.toString(), 0);
			e.printStackTrace();
		}
	}

	/**
	 * Verifica si estan todos los inventarios terminados en la BD para avisar
	 * que se exporten posteriormente
	 * 
	 * @return
	 * @throws ExceptionBDD
	 */
	private boolean estanTerminadosTodosLosInventarios() throws ExceptionBDD {
		boolean result = true;
		BaseDatos bdd = new BaseDatos(ctxt);
		listaInventariosSeleccionados = bdd.selectInventariosNumerosEnBdd();

		for (int numInventario : listaInventariosSeleccionados) {
			if (bdd.selectEstadisticasConIdInventario(numInventario).get(2) > 0) {
				result = false;
			}
		}

		return result;
	}

	/**
	 * Controla si se han medido todos los inventarios y si es necesario
	 * exportarlos
	 * 
	 * @throws ExceptionBDD
	 */
	private void controlFin() throws ExceptionBDD {
		if (estanTerminadosTodosLosInventarios()) {
			botonExportar.setEnabled(true);

			dialogoFin = new AlertDialog.Builder(this);
			dialogoFin
					.setTitle("Fin de las mediciones")
					.setMessage(
							"Todas los inventarios han sido procesados exitosamente.\n"
									+ "Por favor, dirijase hacia el central de control para descargar los datos de los inventarios al servidor.")
					.setCancelable(false)
					.setNeutralButton("OK",
							new DialogInterface.OnClickListener() {
								public void onClick(@NonNull DialogInterface dialog, int which) {
									dialog.dismiss();
								}
							});
			AlertDialog alert = dialogoFin.create();
			alert.show();
		}
	}

	/**
	 * Tarea asincronica de exportacion de los datos
	 * 
	 * @author GuillermoR
	 * 
	 */
	protected class ExportarDatos extends AsyncTask<Context, Integer, RespuestasExportar> {

		private static final boolean Referencia = false;

		/**
		 * Devuelve un objeto Respuestas exportar con info de la exportacion
		 * realiza la tarea de exportar los datos por WIFI
		 * <p>
		 * 1 Fabricamos la lista de todos los inventarios que estn cerrados
		 * <p>
		 * 2 se realiza la exportacin de los datos en las BD
		 * <p>
		 * 3 Exportamos los estados de los inventarios
		 * <p>
		 * 4 Si borrar estuvo activado se borra o si es dinamico el inventario
		 * <p>
		 * 5 Comprobamos que todo paso bien
		 * <p>
		 * 6 Exportamos las fotos
		 * <p>
		 * &nbsp; &nbsp;6.1 Verificamos que todo se hiso bien
		 * <p>
		 * 7 Exportamos los logs
		 * <p>
		 * &nbsp; &nbsp; 7.1 Verificamos que todo salio bien
		 */	

		@NonNull
        protected RespuestasExportar doInBackground(Context... arg0) {
			System.out.println("::: PASO por InventarioM ProductosNoContabilizados " + ParametrosInventario.ProductosNoContabilizados);
			boolean result = true;

			if (ParametrosInventario.ProductosNoContabilizados == 2) {
				ArrayList<Referencia> Referencias = new ArrayList<Referencia>();
				BaseDatos bd = new BaseDatos(ctxt);
				String fechaInicioInventario  = "";
				System.out.println("::: InventariosMainBoard 2367 RespuestasExportar " + inventarios_elegidos);
				int numero_inventario_elegido = inventarios_elegidos;
				if(inventarios_elegidos==-1 || inventarios_elegidos == -2){
					try {
						Inventario inven = bd.selectInventarioConNumero(-1);
					} catch (ExceptionBDD e1) {
					// TODO Auto-generated catch block
						e1.printStackTrace();
						System.out.println("::: PASO por InventarioM 3 catch");
					}
					System.out.println("::: PASO por InventarioM 4");
					Referencias = bd.getArticulosAll();
					for (Referencia ref : Referencias) {
						try {
							System.out.println("::: PASO por InventarioM 5");
							Articulo articulo = bd.selectArticuloConCodigos(
									ref.getSector(), ref.getArticulo(), -1);
							if (articulo == null) {
								Date fechaHoy = new Date();
								ArrayList<String> codbar = new ArrayList<String>();
								ArrayList<String> codbarcompleto = new ArrayList<String>();
								String fechaYA = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
								System.out.println("::: InventarioMain sector 1");
								Articulo art = new Articulo(ref.getSector(),
								ref.getArticulo(), ref.getBalanza(), ref.getDecimales(), codbar, codbarcompleto , -1, ref.getDescripcion(), ref.getPrecio_venta(), ref.getPrecio_costo(), "", 0, ref.getExis_venta(), ref.getExis_deposito(), ref.getDepsn(), fechaInicioInventario,fechaYA);
								bd.insertArticuloEnBdd_conFechaFin(art);
							} else {
								System.out.println("::: InventarioMainBoard ");
								Log.e("Referencia con articulo", "No agregar "+ articulo.getDescripcion().toString());
							}

						} catch (ExceptionBDD e) {
							Toast.makeText(ctxt, "Error al recorrer las referencias", Toast.LENGTH_LONG).show();
							result = false;
						}
					}
				}
			}else{
				try {
					Inventario inven = bd.selectInventarioConNumeroParametro(-1,ParametrosInventario.ProductosNoContabilizados);
				} catch (ExceptionBDD e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			System.out.println("::: InventarioM PASO por  6");
			try {
				System.out.println("::: InventarioM 7 PASO ");
				RegistroLog.log(ParametrosInventario.URL_ARCHIVO_LOG, new Date(), "MAIN BOARD", "0", "Export: 0 %");
			} catch (Exception e) {
		//		System.out.println("::: PASO por InventarioM 8");
				log.log("[-- 1943 --]" + e.toString(), 4);
				e.printStackTrace();
			}

			try {
				bdd = new BaseDatos(ctxt);
				// 1 Fabricamos la lista de todos los inventarios que estan cerrados:
				ArrayList<Integer> listaInventariosCerrados = null;
				try {
					listaInventariosCerrados = bdd.selectInventariosCerradosEnBdd();
				} catch (ExceptionBDD e4) {
					log.log("[-- 1959 --]" + e4.toString(), 4);
					e4.printStackTrace();
				}
				if (listaInventariosCerrados.size() <= 0) {
					Toast.makeText(ctxt, "Debe haber por lo menos un inventario cerrado", Toast.LENGTH_LONG).show();
					result = false;
				}
				try {
					// 2 se realiza la exportacin de los datos en las BD
					result = bdd.exportarTodasBaseDatosSQLite(listaInventariosCerrados);
				} catch (ExceptionHttpExchange e2) {
					log.log("[-- 1961 --]" + e2.toString(), 4);
					e2.printStackTrace();
					return new RespuestasExportar(RespuestasExportar.CODIGO_ERROR, "Error Export - Export a la BDD - Articulos - " + e2.toString());
				} catch (ExceptionBDD e) {
					log.log("[-- 1969 --]" + e.toString(), 0);
					e.printStackTrace();
					return new RespuestasExportar(RespuestasExportar.CODIGO_ERROR, "Error Export - Export a la BDD - Articulos - " + e.toString());
				}

				// 3 Exportamos los estados de los inventarios:
				try {
					if (result) {
						HttpSender httpSender = new HttpSender(Parametros.CODIGO_SOFT_DEBOINVENTARIO);
						for (int inventario : listaInventariosCerrados) {
							if (bdd.selectArticulosConNumeroInventario(inventario).size() <= 0) {
								result &= httpSender.send_liberacion(inventario, 0);
							} else {
								result &= httpSender.send_liberacion(inventario, 1);
							}

							// 4 A ver si borrar estuvo activado o no,o si es
							// dinamico el inventario:
							if (borrarDespues || inventario < 0) { bdd.borrarInventarioConArticulos(inventario); }
						}
					}
				} catch (ExceptionHttpExchange e2) {

					log.log("[-- 2001 --]" + e2.toString(), 4);
					e2.printStackTrace();
					return new RespuestasExportar(RespuestasExportar.CODIGO_ERROR, "Error Export - Export a la BDD - Inventarios - " + e2.toString());
				} catch (ExceptionBDD e) { log.log("[-- 2022 --]" + e.toString(), 4);

				} catch (Exception e3) {
					log.log("[-- 2024 --]" + e3.toString(), 4);
					e3.printStackTrace();
					return new RespuestasExportar(RespuestasExportar.CODIGO_ERROR, "Error Export - Export a la BDD - Inventarios - " + e3.toString());
				}
				int i = 1;

				// 5 Comprobamos que todo paso bien
				if (!result) {
					return new RespuestasExportar(RespuestasExportar.CODIGO_ERROR, "Error Export - Export a la BDD - Verifique la conexion a la red");
				}

				try {
					RegistroLog.log(ParametrosInventario.URL_ARCHIVO_LOG, new Date(), "MAIN BOARD", "0", "Export: 20 %");
				} catch (Exception e) {
					log.log("[-- 2054 --]" + e.toString(), 4);
					e.printStackTrace();
				}

//				i = 2;
//				// 6 Exportamos las fotos:
//				File carpetaFotos = new File(ParametrosInventario.URL_CARPETA_FOTOS);
//				i = 3;
//				if (carpetaFotos.listFiles().length > 0) {
//					i = 4;
//					HttpSender senderFotos;
//					try {
//						senderFotos = new HttpSender(Parametros.CODIGO_SOFT_DEBOINVENTARIO);
//					} catch (ExceptionHttpExchange e) {
//
//						log.log("[-- 2046 --]" + e.toString(), 4);
//						e.printStackTrace();
//						return new RespuestasExportar(RespuestasExportar.CODIGO_WARNING, "Error Export - Export imagenes - " + e.toString());
//					}
//
//					for (File unaFoto : carpetaFotos.listFiles()) {
//						result &= senderFotos.send_foto(ParametrosInventario.URL_CARPETA_FOTOS + unaFoto.getName());
//					}
//				}
				i = 5;
				// 6.1 Comprobar que todo esta bien
//				if (!result) {
//					return new RespuestasExportar(RespuestasExportar.CODIGO_WARNING, "Error Export - Export imagenes");
//				}
				i = 6;

				try {
					RegistroLog.log(ParametrosInventario.URL_ARCHIVO_LOG, new Date(), "MAIN BOARD", "0", "Export: 40 %");
				} catch (Exception e) {
					e.printStackTrace();

					log.log("[-- 2075 --]" + e.toString(), 4);
				}

				// 7 Exportamos los logs:
				File archivoLOG = new File(ParametrosInventario.URL_ARCHIVO_LOG);
				i = 7;
				if (archivoLOG.exists()) {
					HttpSender senderLOG;
					try {
						senderLOG = new HttpSender(Parametros.CODIGO_SOFT_DEBOINVENTARIO);
						result = senderLOG.send_txt(ParametrosInventario.URL_ARCHIVO_LOG);
					} catch (ExceptionHttpExchange e) {

						e.printStackTrace();
						return new RespuestasExportar(RespuestasExportar.CODIGO_WARNING, "Error Export - Export logs - " + e.toString());
					}
					i = 8;

					// 7.1 Comprobar que todo esta bien:
					if (!result) {
						return new RespuestasExportar(RespuestasExportar.CODIGO_WARNING, "Error Export - Export logs");
					}
					i = 9;
					// archivoLOG.delete();
					i = 10;
				}

				try {
					RegistroLog.log(ParametrosInventario.URL_ARCHIVO_LOG, new Date(), "MAIN BOARD", "0", "Export: 60 %");
				} catch (Exception e) {

					log.log("[-- 2114 --]" + e.toString(), 4);
					e.printStackTrace();
				}

				try {
					RegistroLog.log(ParametrosInventario.URL_ARCHIVO_LOG, new Date(), "MAIN BOARD", "0", "Export: 90 %");
				} catch (Exception e) {
					log.log("[-- 2136 --]" + e.toString(), 4);
					e.printStackTrace();
				}

			} catch (Exception e) {
				return new RespuestasExportar(RespuestasExportar.CODIGO_ERROR, "Error Export - " + " - Error fatal - " + e.toString());
			}

			return new RespuestasExportar(RespuestasExportar.CODIGO_OK, "Operacion Realizada con Exito");
		} // end doInBackground

		/**
		 * Tareas de aviso cuando se finalizo la tarea asincronica, segun
		 * resultados
		 */

		protected void onPostExecute(@NonNull RespuestasExportar result) {
			super.onPostExecute(result);

			// Terminamos la exportacion con un mesaje + refresh:
			cerrarMenuEspera();
			desactivarWifi();

			if (result.getCodigoError() == RespuestasExportar.CODIGO_OK) {
				showSimpleDialogOK("Exportacion Exitosa",
						"La exportacion se realizo con exito.").show();

				try {
					RegistroLog.log(ParametrosInventario.URL_ARCHIVO_LOG, new Date(), "MAIN BOARD", "0", "Export: 100 % --- EXITOSO");
				} catch (Exception e) {
					log.log("[-- 2170 --]" + e.toString(), 4);
					e.printStackTrace();
				}

				try {
					refreshTablaPrincipal();
				} catch (ExceptionBDD e) {
					log.log("[-- 2176 --]" + e.toString(), 4);
					e.printStackTrace();
				} catch (Exception e) {
					log.log("[-- 2178 --]" + e.toString(), 4);
					e.printStackTrace();
				}

				// Registro.log(ParametrosSancion.URL_ARCHIVO_LOG, new Date(),
				// nombreClase, String.valueOf(operadorId),
				// "Exportar datos 100%");
				// finish();
			} else {
				if (result.getCodigoError() == RespuestasExportar.CODIGO_ERROR) {
					showSimpleDialogOK("Exportacion Cancelada", "Explicacion: \n\n" + result.getMensaje()).show();
				} else if (result.getCodigoError() == RespuestasExportar.CODIGO_WARNING) {
					showSimpleDialogOK("Exportacion Finalizada con Advertencias", "Explicacion: \n\n" + result.getMensaje()).show();
				}
				try {
					RegistroLog.log(ParametrosInventario.URL_ARCHIVO_LOG, new Date(), "MAIN BOARD", "0", "Export: 100 % --- " + result);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

	}

	/**
	 * Lanza un progres dialog de espera
	 */
	private void lanzarMenuEspera() {
		popupEspera = new ProgressDialog(ctxt);
		popupEspera.setCancelable(false);
		popupEspera.setMessage("Exportando los datos...");
		popupEspera.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		popupEspera.show();
	}

	/**
	 * Cierra el menu de espera
	 */
	private void cerrarMenuEspera() {
		popupEspera.dismiss();
	}

	/**
	 * Muestra un dialog de OK
	 */

	public AlertDialog showSimpleDialogOK(String titulo, String mensaje) {
		log.log("[-- 2215 --]" + "titulo: " + titulo + ", \n mensaje: "
				+ mensaje, 3);
		AlertDialog.Builder dialogoSimple = new AlertDialog.Builder(this);
		dialogoSimple.setCancelable(false).setTitle(titulo).setMessage(mensaje)
				.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
					public void onClick(@NonNull DialogInterface dialog, int id) {
						dialog.dismiss();
					}
				});
		return dialogoSimple.create();
	}

	/**
	 * Muestra un dialog Si o No
	 */

	public AlertDialog showSimpleDialogSiNo(String titulo, String mensaje,
                                            @Nullable final Class<?> clase) {
		log.log("[-- 2233 --]" + "titulo: " + titulo + ", \n mensaje: "
				+ mensaje, 3);
		AlertDialog.Builder dialogoSimple = new AlertDialog.Builder(this);
		dialogoSimple
				.setCancelable(false)
				.setTitle(titulo)
				.setMessage(mensaje)
				.setPositiveButton("Si", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						bdd = new BaseDatos(ctxt);

						log.log("[-- 2243 --]" + "Acepto sino", 2);

						// Si CLASE = null, es un EXPORT
						if (clase == null) {
							int contador = 3;

							try {
								do {
									export_usb(false);
									contador--;
								} while (!control_buena_exportacion()
										&& contador >= 0);
							} catch (ExceptionBDD e) {

								log.log("[-- 2257 --]" + e.toString(), 4);
								showSimpleDialogOK(
										"ERROR DE EXPORTACION",
										"Generacion del documento XML imposible: "
												+ e.getComentario()).show();
								return;
							} catch (Exception e) {
								log.log("[-- 2264 --]" + e.toString(), 4);
								showSimpleDialogOK(
										"ERROR DE EXPORTACION",
										"Imposible exportar en el "
												+ Dispositivo_Export
												+ ". Verifique que este "
												+ "correctamente conectado")
										.show();
								return;
							}

							if (contador < 0) {
								showSimpleDialogOK(
										"ERROR DE EXPORTACION",
										"Los archivos XML de exportacion no han podido ser creados con exito. "
												+ "Verifique su correctitud")
										.show();
								return;
							}

							cerrarMenuEspera();

						}
						// Si CLASE es not NULL, es import:
						else {
							Intent intentUSB = new Intent(
									InventarioMainBoard.this, UsbProvider.class);
							intentUSB.putExtra(Parametros.extra_uri_usb,
									Parametros.PREF_USB_IMPORT);
							startActivity(intentUSB);
							finish();
						}
					}
				})
				.setNegativeButton("No", new DialogInterface.OnClickListener() {
					public void onClick(@NonNull DialogInterface dialog, int id) {
						dialog.cancel();
						log.log("[-- 2301 --]" + "Cancelo sino", 2);
					}
				});
		AlertDialog alert = dialogoSimple.create();
		return alert;
	}

	/**
	 * Activa el WIFI para usarlo en caso de ser necesario
	 */

	public void activarWifi() {
		WifiManager wifiManager = (WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
//		WifiManager wifiManager = (WifiManager)getSystemService(Context.WIFI_SERVICE);
		ConnectivityManager wifiConexion = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
		//NetworkInfo wifiInfo = wifiConexion.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		assert wifiConexion != null;
		wifiConexion.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		NetworkInfo wifiInfo;
		//wifiInfo = wifiConexion.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		wifiInfo = wifiConexion.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

		if (!wifiInfo.isConnected()) {

			Settings.System.putInt(ctxt.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0);
			Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
			intent.putExtra("state", false);
			sendBroadcast(intent);

			wifiManager.setWifiEnabled(true);
		}
		log.log("[-- 2329 --]" + "Se activo el Wifi", 2);
	}

	/**
	 * Desactiva el WIFI
	 */

	public void desactivarWifi() {
		// if (estaEnModoAvion() == false) {
		// // toggle airplane mode
		// Settings.System.putInt(ctxt.getContentResolver(),
		// Settings.System.AIRPLANE_MODE_ON, 1);
		//
		// // Post an intent to reload
		// Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
		// intent.putExtra("state", true);
		// sendBroadcast(intent);
		//
		// WifiManager wifiManager = (WifiManager)
		// getSystemService(Context.WIFI_SERVICE);
		// wifiManager.setWifiEnabled(false);
		//
		// log.log("[-- 2350 --]" + "Se dessactiva el Wi fi", 4);
		// }
	}

	/**
	 * Verificacion de modo Avion
	 */

	public boolean estaEnModoAvion() {
		return (Settings.System.getInt(ctxt.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) == 1);
	}

	/**
	 * Funcion accesoria para copiar un archivo de origen en uno de destino
	 * 
	 * @param sourceFile
	 * @param destFile
	 * @throws IOException
	 */
	private void copyFile(@NonNull File sourceFile, @NonNull File destFile) throws IOException {
		if (!sourceFile.exists()) {
			return;
		}
		if (!destFile.exists()) {
			destFile.createNewFile();
		}
		FileChannel source = null;
		FileChannel destination = null;
		source = new FileInputStream(sourceFile).getChannel();
		destination = new FileOutputStream(destFile).getChannel();
		if (source != null) {
			destination.transferFrom(source, 0, source.size());
		}
		if (source != null) {
			source.close();
		}
		if (destination != null) {
			destination.close();
		}
	}

	/**
	 * Funcion principal de exportacion de datos por USB (MUY IMPORTANTE)
	 * 
	 * @param borrar_despues
	 *            <p>
	 *            1 Vaciar la carpeta de exportacion
	 *            <p>
	 *            2 Fabricamos la lista de todos los inventarios que estn
	 *            cerrados
	 *            <p>
	 *            3 Llama al proceso de exportacion de las BD al pendrive, esto
	 *            genera un archivo o varios XML de export en la carpeta
	 *            data/data/com.foca.deboInventario/usb/export
	 *            <p>
	 *            4 Copiamos al pen drive todos los archivos XML presentes en
	 *            la carpeta de EXPORT, al pendrive y verifica el proceso
	 *            <p>
	 *            5 Se verifica la correcta exportacin, si es positiva se
	 *            borran los inventarios
	 * @throws ExceptionBDD
	 * @throws Exception
	 */
	private void export_usb(boolean borrar_despues) throws ExceptionBDD,

	Exception {
		// Para prueba descomentar la linea siguiente para que encuentre los
		// archivos
		// ParametrosInventario.PREF_USB_EXPORT =
		// "data/data/com.foca.deboInventario/test/";
		// 1 Vaciar la carpeta de exportacion
		vaciarCarpetaExportacion();
		bdd = new BaseDatos(ctxt);
		String texto_error = "";
		boolean estado_exportacion = true;
		Dispositivo_Export = TipoDispositivoExport();
		Dispositivo_Export = TipoDispositivoImport();

		// 2 Fabricamos la lista de todos los inventarios que estn cerrados:
		ArrayList<Integer> listaInventariosCerrados = bdd
				.selectInventariosCerradosEnBdd();
		if (listaInventariosCerrados.size() <= 0) {
			log.log("[-- 2433 --]"
					+ "Debe haber por lo menos un inventario cerrado", 3);
			Toast.makeText(ctxt,
					"Debe haber por lo menos un inventario cerrado",
					Toast.LENGTH_LONG).show();
			return;
		}

		/**
		 * 3 Llama al proceso de exportacion de las BD al pendrive, esto genera
		 * un archivo o varios XML de export en la carpeta
		 * data/data/com.foca.deboInventario/usb/export
		 */
		
		
		if (ParametrosInventario.ProductosNoContabilizados == 2) {


			ArrayList<Referencia> Referencias = new ArrayList<Referencia>();
			BaseDatos bd = new BaseDatos(ctxt);
			Referencias = bd.getArticulosAll();
			for (Referencia ref : Referencias) {
				try {
					Articulo articulo = bd.selectArticuloConCodigos(
							ref.getSector(), ref.getArticulo(), -1);

					if (articulo == null) {
						ArrayList<String> codbar = new ArrayList<String>();
						ArrayList<String> codbarcompleto = new ArrayList<String>();
						codbar.add(ref.getCodigo_barra());
						codbarcompleto.add(ref.getCodigo_barra_completo());
						Articulo art = new Articulo(ref.getSector(),
								ref.getArticulo(),
								ref.getBalanza(), 
								ref.getDecimales(), 
								codbar,
								codbarcompleto, -1,
								ref.getDescripcion(),
								ref.getPrecio_venta(),
								ref.getPrecio_costo(), "", 0,0,
								ref.getExis_venta(),
								ref.getExis_deposito(),
								ref.getDepsn(),
								"");
						bd.insertArticuloEnBdd(art);
					} else {
					//	Log.e("Referencias con articulos", "No agregar "
				//				+ articulo.getDescripcion().toString());
					}

				} catch (ExceptionBDD e) {
					Toast.makeText(ctxt,
							"Error al recorrer las referencias",
							Toast.LENGTH_LONG).show();
					
				}

			}
		}
		
		
		
		
		bdd.exportarTodasBaseDatosSQLite_HaciaUsb(listaInventariosCerrados);

		/**
		 * 4 Copiamos al pen drive todos los archivos XML presentes en la
		 * carpeta de EXPORT, al pendrive y verifica el proceso
		 */

		File carpeta_fuente = new File(
				ParametrosInventario.URL_CARPETA_USB_EXPORT);
		for (File archivo : carpeta_fuente.listFiles()) {
			File carpeta_destino = new File(
					ParametrosInventario.CARPETA_ATABLET);
			File archivo_destino = new File(
					ParametrosInventario.CARPETA_DESDETABLET
							+ archivo.getName());
			// boolean existecarpetaDest=carpeta_destino.exists();
			// boolean existearchivo=archivo.exists();
			try {
				if (carpeta_destino.exists() == true
						&& archivo.exists() == true) {
					// Puede arrojar la IOExc
					archivo_destino.createNewFile();
					// Puede arrojar la IOExc
					copyFile(archivo, archivo_destino);
					archivo.delete();
				} else {
					texto_error = "Imposible encontrar la carpeta de destino: " + carpeta_destino.getPath();
					estado_exportacion = false;
					// Deberiamos crear la carpeta de destino y hacer todo lo
					// anterior
					// carpeta_destino.mkdirs();
					// archivo_destino.createNewFile();
					// copyFile(archivo, archivo_destino);
					archivo.delete();
				}
			} catch (IOException e) {
				// Genera este error
				texto_error = "Un error occurio al momento de copiar los archivos al"
						+ Dispositivo_Export;
				estado_exportacion = false;
			}

			// Control directo sobre el archivo generado:
			if (!carpeta_destino.exists()) {
				estado_exportacion = false;
			}
		}

		// 5 Se verifica la correcta exportacion, si es positiva se borran los
		// inventarios
		if (estado_exportacion == true && control_buena_exportacion() == true) {
			// Los borramos si nos han marcado o si son dinamicos
			for (int num_inv : listaInventariosCerrados) {
				if (borrar_despues == true || num_inv < 0) {

					bdd.borrarInventarioConArticulos(num_inv);
				}
			}

			showSimpleDialogOK(
					"Exportacion exitosa",
					"Datos correctamente exportados en el "
							+ Dispositivo_Export).show();
		}// Solucion temporaria 08/05/2012
			// else if ()
		else {
			// Se saca para que no moleste despues
			// showSimpleDialogOK("Error", texto_error +
			// "\n Es posible que los archivos de exportacin hayan sido mal generados.\n\n"
			// +
			// "Por favor reintente.").show();
			// Borrar los archivos de la carpeta desdeTablet
			// File carpeta_destino = new
			// File(ParametrosInventario.PREF_USB_EXPORT);
			// for(File archivoDest:carpeta_destino.listFiles()) {
			// archivoDest.delete();
			// }
		}

		cerrarMenuEspera();
		refreshTablaPrincipal();
	}

	/**
	 * Devuelve una informacin sobre el tamao de los archivos (aqui los
	 * archivos de exportacin). Si los archivos son de tamaos inferiores a 1
	 * bytes, se considera que el archivo esta vacio.
	 * 
	 * @return (boolean) TRUE si los archivos tienen un tamao aceptable, FALSE
	 *         sino.
	 */
	private boolean control_buena_exportacion() {

		File carpeta_destino = new File(ParametrosInventario.CARPETA_DESDETABLET);
		boolean respuesta = true;

		// Controlamos la integridad de todos los archivos de export
		for (File archivo : carpeta_destino.listFiles()) {
			// No funciona esto con archivos de menos de 1 byte por lo menos en
			// el emulador
			Long tamaoArchivo = new Long(archivo.length());
			int resultadoComparacion = tamaoArchivo.compareTo(new Long(1L));
			int comparativa = -1;
			boolean esMenor = (resultadoComparacion == comparativa);
			if (esMenor) {
				respuesta = false;
				break;

			}
		}

		return respuesta;
	}

	/**
	 * Funcin accesoria para vaciar la carpeta de exportacion del pendrive
	 */
	private void vaciarCarpetaExportacion() {
		File carpeta_destino = new File(
				ParametrosInventario.CARPETA_DESDETABLET);

		for (File archivo : carpeta_destino.listFiles()) {
			// No funciona esto con archivos de menos de 1 byte por lo menos en
			// el emulador
			archivo.delete();
		}

	}

	/**
	 * Verifica que los inventarios tengan articulos
	 */
	private void control_integridad_tablas() {
		try {
			System.out.println("::: InventarioMainBoard 2769 verifica inventario con articulos");
			BaseDatos bdd = new BaseDatos(ctxt);
			
			boolean condicionRadio = ParametrosInventario.InventariosVentas;
			System.out.println("::: InventarioMainBoard 3062 condicionRadio " + condicionRadio);
			
			if(condicionRadio == true){
				// Esta seleccionado ventas, esto debe continuar sin los campos de deposito
				condR=-1;
			}else{
				// Esta seleccionado deposito, esto debe continuar sin los campos de ventas
				condR=-2;
			}
			System.out.println("::: InventarioMainBoard 3062 condR == " + condR);
			
			

			ArrayList<Integer> lista_numeros_inventarios = bdd
					.selectInventariosNumerosEnBdd();

			if (lista_numeros_inventarios != null) {
				for (int id_inv : lista_numeros_inventarios) {
					System.out.println("::: InventarioMainBoard 2769 " + lista_numeros_inventarios);
					System.out.println("::: InventarioMainBoard 2769 " + 
							bdd.selectArticulosCodigosConNumeroInventario(
									id_inv));
					if (id_inv >= 0
							&& bdd.selectArticulosCodigosConNumeroInventario(
									id_inv).size() <= 0) {
						bdd.borrarInventarioConArticulos(id_inv);
					}
				}
			}
		} catch (ExceptionBDD e) {
			e.printStackTrace();
			log.log("[-- 2594 --]" + e.toString(), 4);
		}
	}

	/**
	 * Funcion accesoria que devuelve el minimo indice de una lista?
	 * 
	 * @param lista
	 * @return
	 */
	private int min(@NonNull ArrayList<Integer> lista) {
		int mini = lista.get(0);
		for (int i : lista) {
			if (i < mini) {
				mini = i;
			}
		}
		return mini;
	}

} // end class