Problem
Currently I am working on a Receipt Printing Tabulation code in Java/Android.
StringBuilder textData2 = new StringBuilder();
StringBuilder textData3 = new StringBuilder();
StringBuilder textData4 = new StringBuilder();
StringBuilder textData5 = new StringBuilder();
StringBuilder textData6 = new StringBuilder();
And I am calling these all textData to arrange bellow lines.
mPrinter.addCommand(new byte[] {0x0d, 0x0a});
textData2.append("-----------------------------------------------");
mPrinter.addText(textData2.toString());
mPrinter.addCommand(new byte[] {0x0d, 0x0a}); //LF
//
mPrinter.addCommand(new byte[] {0x1b,0x44, 0x27, 0x00});
textData3.append("Bill no. 216381651273-5632");
mPrinter.addText(textData3.toString());
mPrinter.addCommand(new byte[] {0x09});//// HT
textData4.append("cash");
mPrinter.addText(textData4.toString());
mPrinter.addCommand(new byte[] {0x0d, 0x0a}); //LF
mPrinter.addCommand(new byte[] {0x1b,0x44, 0x27, 0x00});
textData5.append("Dine In");
mPrinter.addText(textData5.toString());
mPrinter.addCommand(new byte[] {0x09});//// HT
textData6.append("20 mar-17");
mPrinter.addText(textData6.toString());
mPrinter.addCommand(new byte[] {0x0d, 0x0a}); //LF
So, How can I define this textdata
for once and use in multiple places ? Actually, I want to ignore using textdata1/2/3/4/5.....
so on multiple times.
Solution
Doing
StringBuilder t = new StringBuilder();
t.append("some text");
t.toString();
is exactly equivalent to
"some text"
Unless you’re calling append on the StringBuilder
more than once, it’s completely redundant. So your code should read:
mPrinter.addCommand(new byte [] {0x0d, 0x0a});
mPrinter.addText("-----------------------------");
...
It would probably be a lot more readable if you stored all the text in a template file instead, but then you would have to have some way of figuring out what printer commands to intersperse with the text.