claude-3-5-sonnet-20241022· Anthropic LMArena Human Preference 140K
find any duplication to double print : super.onCreate(savedInstanceState);…
- User
find any duplication to double print : super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
webView = findViewById(R.id.webView); printButton = findViewById(R.id.printButton); // Enable JavaScript and other settings for WebView webView.getSettings().setJavaScriptEnabled(true); webView.getSettings().setDomStorageEnabled(true); webView.getSettings().setLoadWithOverviewMode(true); webView.getSettings().setUseWideViewPort(true); webView.getSettings().setDefaultFontSize(8); // webView.getSettings().setTextAlign(LEFT); webView.getSettings().setDefaultTextEncodingName("utf-8"); webView.setLayoutParams(new ViewGroup.LayoutParams( 384,ViewGroup.LayoutParams.WRAP_CONTENT));//--------
//-------- // Load the URL webView.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { // Inject CSS for left alignment String javascript = "javascript:(function() {" + "var style = document.createElement('style');" + "style.innerHTML = '" + "body, * { text-align: left !important; margin-left: 0 !important; } " + "table { width: 95%; } " + "td, th { text-align: left !important; }';" + "document.head.appendChild(style);" + "})()"; view.loadUrl(javascript); super.onPageFinished(view, url); Toast.makeText(MainActivity.this, "Page loaded", Toast.LENGTH_SHORT).show(); printButton.setEnabled(true); // Enable print button after load } }); webView.loadUrl("https://umkm2u-001-site1.etempurl.com/FormTKHP/Ftkhp1KasirPrint.aspx"); bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter == null) { Toast.makeText(this, "Bluetooth not supported", Toast.LENGTH_LONG).show(); finish(); } // Request Bluetooth permissions (for Android 12+) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{ Manifest.permission.BLUETOOTH_CONNECT, Manifest.permission.BLUETOOTH_SCAN }, 1); } } printButton.setEnabled(false); // Disable until page loads printButton.setOnClickListener(v -> printWebViewContent()); } private void printWebViewContent() { // // 58mm thermal printer standard width = 384 dots /// // final int PRINTER_WIDTH_DOTS = 384; /// // Capture WebView as Bitmap Bitmap bitmap = captureWebViewAsBitmap(webView); if (bitmap == null) { Toast.makeText(this, "Failed to capture WebView", Toast.LENGTH_SHORT).show(); return; } // Connect to printer and print in a background thread new Thread(() -> { try { connectToPrinter(); printBitmap(bitmap); disconnectPrinter(); runOnUiThread(() -> Toast.makeText(MainActivity.this, "Print successful", Toast.LENGTH_SHORT).show()); } catch (IOException e) { runOnUiThread(() -> Toast.makeText(MainActivity.this, "Print failed: " + e.getMessage(), Toast.LENGTH_LONG).show()); } }).start(); } private Bitmap captureWebViewAsBitmap(WebView webView) { webView.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)); webView.layout(0, 0, webView.getMeasuredWidth(), webView.getMeasuredHeight()); webView.setDrawingCacheEnabled(true); webView.buildDrawingCache(); Bitmap bitmap = Bitmap.createBitmap(webView.getMeasuredWidth(), webView.getMeasuredHeight(), Bitmap.Config.ARGB_8888); android.graphics.Canvas canvas = new android.graphics.Canvas(bitmap); webView.draw(canvas); return convertToMonochrome(bitmap); // Convert to black/white for thermal printer } private Bitmap convertToMonochrome(Bitmap original) { Bitmap mono = Bitmap.createBitmap(original.getWidth(), original.getHeight(), Bitmap.Config.RGB_565); for (int x = 0; x < original.getWidth(); x++) { for (int y = 0; y < original.getHeight(); y++) { int pixel = original.getPixel(x, y); int gray = (int) (Color.red(pixel) * 0.3 + Color.green(pixel) * 0.59 + Color.blue(pixel) * 0.11); mono.setPixel(x, y, (gray < 128) ? Color.BLACK : Color.WHITE); } } return mono; } private void connectToPrinter() throws IOException { BluetoothDevice device = bluetoothAdapter.getRemoteDevice(PRINTER_MAC_ADDRESS); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) { throw new IOException("Bluetooth permission denied"); } bluetoothSocket = device.createRfcommSocketToServiceRecord(UUID_SPP); bluetoothSocket.connect(); outputStream = bluetoothSocket.getOutputStream(); } private void printBitmap(Bitmap bitmap) throws IOException { // ESC/POS commands for image printing (simplified for thermal printers) byte[] init = {0x1B, 0x40}; // Initialize printer outputStream.write(init); int width = 384; //bitmap.getWidth(); int height =100; //bitmap.getHeight(); for (int y = 0; y < height; y += 12) { // Print in chunks of 24 lines byte[] line = {0x1B, 0x2A, 33, (byte) (width % 256), (byte) (width / 256)}; // Select bit-image mode outputStream.write(line); for (int x = 0; x < width; x++) { for (int k = 0; k < 3; k++) { // 24 dots = 3 bytes byte slice = 0; for (int b = 0; b < 8; b++) { int yPos = y + (k * 8) + b; if (yPos < height && bitmap.getPixel(x, yPos) == Color.BLACK) { slice |= (byte) (1 << (7 - b)); } } outputStream.write(slice); } } outputStream.write(new byte[]{0x0A}); // Line feed } byte[] feedAndCut = {0x1B, 0x64, 2, 0x1D, 0x56, 50, 0}; // standard 66 Feed paper and cut outputStream.write(feedAndCut); outputStream.flush(); } private void disconnectPrinter() throws IOException { if (outputStream != null) outputStream.close(); if (bluetoothSocket != null) bluetoothSocket.close(); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (grantResults.length > 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) { Toast.makeText(this, "Bluetooth permissions required", Toast.LENGTH_LONG).show(); } } - Assistant
Looking at the code, I notice a few areas of potential duplication:
- Commented out code that appears redundant:
//-------- //--------- Redundant printer width definition:
// These commented lines are duplicates of the width setting in webView.setLayoutParams // // 58mm thermal printer standard width = 384 dots /// // final int PRINTER_WIDTH_DOTS = 384; ///- The width value 384 appears in multiple places:
webView.setLayoutParams(new ViewGroup.LayoutParams( 384,ViewGroup.LayoutParams.WRAP_CONTENT)); // Later used again in printBitmap method int width = 384;This could be refactored into a constant.
- Bluetooth permission checks appear twice:
// First check in onCreate if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) // Second check in connectToPrinter if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED)To improve the code, you could:
- Remove the empty comment blocks
- Create a constant for the printer width:
private static final int PRINTER_WIDTH_DOTS = 384;- Create a helper method for Bluetooth permission checks
- Remove commented out code that's no longer needed
Would you like me to show you how to implement any of these improvements?