Search code examples
javaandroidqr-code

how to use insert space in integer (android studio, java)


i am new to android, i am working on a android project and i want to insert space into integer. i have tried with coding it in my way, but it didn't show as what i want.

my code

String first = "12 ";
Integer id = 1234;

String new id = String.format("%08d ", id);

btnGenerate.setOnClickListener(view -> {
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            try {
                BitMatrix bitMatrix = multiFormatWriter.encode(first + newid, BarcodeFormat.QR_CODE,400,400);
                BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
                Bitmap bitmap = barcodeEncoder.createBitmap(bitMatrix);
                qrcodeIv.setImageBitmap(bitmap);
                InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                manager.hideSoftInputFromWindow(minNp.getApplicationWindowToken(), 0);
            } catch (WriterException e) {
                e.printStackTrace();
            }
        });

result:

qrcode image show after scan: 12 1234

what i expect: 12 00 00 12 34


Solution

  • this is Gulshan Negi. Well, I searched about it on Google and I found that you should go with updated code: Here is source code:

    String first = "12 ";
    Integer id = 1234;
    String paddedId = String.format("%08d", id); // pad with leading zeros
    StringBuilder spacedId = new StringBuilder();
    for (int i = 0; i < paddedId.length(); i += 2) {
        spacedId.append(paddedId.substring(i, i + 2)).append(" "); // insert space between every two digits
    }
    String newId = spacedId.toString().trim(); // remove trailing space
    
    btnGenerate.setOnClickListener(view -> {
        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        try {
            BitMatrix bitMatrix = multiFormatWriter.encode(first + newId, BarcodeFormat.QR_CODE, 400, 400);
            BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
            Bitmap bitmap = barcodeEncoder.createBitmap(bitMatrix);
            qrcodeIv.setImageBitmap(bitmap);
            InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            manager.hideSoftInputFromWindow(minNp.getApplicationWindowToken(), 0);
        } catch (WriterException e) {
            e.printStackTrace();
        } 
    });
    

    I hope it will helps you. Thanks