I make a POS project. I want to print receipt. I'm using thermal printer zonerich. I had successfully to print the receipt. Now, I want to custom the font. I want to make the outlet name bigger ,have a bold style and in center.
In my code bellow, when i try to put the bold format it will bold all of the receipt not only the outlet name. Please tell me how to make style only in outlet name and how to change the font size, Sorry for bad english. Thanks for your help.
public void IntentPrint(String notaID, String namaKasir, String date, String total, String pay, String change, String method) {
db = new DatabaseHandler(MainActivity.this);
String payment="";
String sosmed = "\n"+ sessionStartUp.getUserDetails().get(sessionStartUp.KEY_SOSMED);
String namaOtlet = sessionStartUp.getUserDetails().get(sessionStartUp.KEY_OUTLET);
String header ="\nReceipt : " + db.getFakeNotaID(notaID) + "\n" +
"Nama Kasir : " + namaKasir + "\n" +
"Date : " + date+"\n"+
"Name Qty Price"+"\n";
if(!pay.equals("0"))
{
payment ="\nTotal : "+total+"\n"+"Method : "+method+"\n"+
"Payment : "+pay+"\n"+
"Change : "+change;
}
else
payment ="\nTotal : "+total+"\n"+"\nMethod : "+method+"\n";
InitPrinter();
try {
outputStream.write(header.getBytes());
outputStream.write(data(notaID).getBytes());
outputStream.write(payment.getBytes());
outputStream.write(sosmed.getBytes());
byte[] format= { 27, 33, 0 };
byte[] center = { 0x1b, 'a', 0x01 };
byte[] arrayOfByte1 = { 27, 33, 0 };
format[2] = ((byte)(0x8 | arrayOfByte1[2]));
outputStream.write(center);
outputStream.write(format);
outputStream.write(namaOtlet.getBytes(),0,namaOtlet.getBytes().length);
outputStream.close();
socket.close();
} catch (Exception ex) {
value += ex.toString() + "\n" + "Excep IntentPrint \n";
// Toast.makeText(this, value, Toast.LENGTH_LONG).show();
}
}
Related
I want to replace one word in the String by using substring. But it seen didn't work.
for example: The string is 0000 , and I want to replace the first word from 0 to 1.
It should be 1000. but it doesn't.
The code is like the following
String WorkStatus = "0000";
if(WorkStatus.substring(0, 1).matches("0"))
{
WorkStatus.substring(0, 1).replace("0", "1");
Log.d(TAG, "WorkStatus.substring(0, 1) = " + WorkStatus.substring(0, 1) + "\n");
Log.d(TAG, "WorkStatus = " + WorkStatus + "\n");
}
It didn't work , the string always show 0000. And what I want is "1000"
Do I missing something ?
use this
String WorkStatus = "0000";
//You use matches, while you might as well use equals
if (WorkStatus.substring(0, 1).equals("0")) {
//reassign workstatus to workstatus where the first entry is a '1' + the last three chars "000"
WorkStatus = WorkStatus.substring(0, 1).replace("0", "1") + WorkStatus.substring(1, WorkStatus.length());
Log.d(TAG, "WorkStatus.substring(0, 1) = " + WorkStatus.substring(0, 1) + "\n");
Log.d(TAG, "WorkStatus = " + WorkStatus + "\n");
}
You didnt assign the modified string to WorkStatus
Another possibility is converting the string to a char[] and replacing the index, instead of working with substrings.
String WorkStatus = "0000";
char[] chars = WorkStatus.toCharArray();
if (chars[0] == '0') {
chars[0] = '1';
WorkStatus = new String(chars);
}
If you want other chars to become 1 instead of zero, alter the chars[0] into chars[index], where index is the index you want to change from 0 to 1
Or, even easier, use a StringBuilder:
int yourIndex = 2; //your index which you want to check for 0 and change to 1
StringBuilder sb = new StringBuilder("0000");
if (sb.charAt(yourIndex) == '0')
sb.setCharAt(yourIndex, '1');
WorkStatus = sb.toString();
method replace has a return value of the string after replaced
you shuold resign the result to the String
WorkStatus=WorkStatus.substring(0, 1).replace("0", "1")+ WorkStatus.substring(1, WorkStatus.length();
if you asign it to a new variable like the below code, you can get what you needed.
String newWorkStatus=WorkStatus.substring(0, 1).replace("0", "1")+WorkStatus.substring(1);
Log.d("LOG", "WorkStatus.substring(0, 1) = " + WorkStatus.substring(0, 1) + "\n");
Log.d("LOG", "WorkStatus = " + WorkStatus + "\n");
Log.d("LOG", "New WorkStatus = " + newWorkStatus + "\n");
WorkStatus.substring(0, 1).replace("0", "1"); returns 1, you should use StringBuilder instead of String.
My solution:
StringBuilder WorkStatus = new StringBuilder("0000");
int pos = WorkStatus.indexOf("0", 0);
if (pos != -1) {
WorkStatus.replace(pos, pos + 1, "1");
}
System.out.print(WorkStatus);
I am currently saving values to a text file in my application. The values are read from an EEG headset every second and are then stored within the text file.
The values are read using a handler e.g.:
final Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
// msg.what determines the type of each message
switch (msg.what) {
case TGDevice.MSG_EEG_POWER:
eegPower = (TGEegPower) msg.obj;
//trace code
Log.d("LSD", "highAlpha: " + eegPower.highAlpha);
Log.d("LSD", "lowAlpha: " + eegPower.lowAlpha);
Log.d("LSD", "highBeta: " + eegPower.highBeta);
Log.d("LSD", "lowBeta: " + eegPower.lowBeta);
Log.d("LSD", "lowGamma: " + eegPower.lowGamma);
Log.d("LSD", "midGamma: " + eegPower.midGamma);
Log.d("LSD", "delta: " + eegPower.delta);
Log.d("LSD", "theta: " + eegPower.theta);
//adding all the EEGpowers to an arraylist to help add them to file
ArrayList<String> EEGPowers= new ArrayList<String>();
EEGPowers.add("highAlpha: " + eegPower.highAlpha);
EEGPowers.add("lowAlpha: " + eegPower.lowAlpha);
EEGPowers.add("highBeta: " + eegPower.highBeta);
EEGPowers.add("lowBeta: " + eegPower.lowBeta);
EEGPowers.add("lowGamma: " + eegPower.lowGamma);
EEGPowers.add("midGamma: " + eegPower.midGamma);
EEGPowers.add("delta: " + eegPower.delta);
EEGPowers.add("theta: " + eegPower.theta);
for(String s: EEGPowers){
writeToFileEEGPower(s);
}
//rest of handler...
The following method is the method used to save the values to file:
public void writeToFileEEGPower(String data){
//creating time for the file
Time t= new Time();
int timeFileSecond= t.second;
int timeFileDate= t.yearDay;
int timeFileYear= t.year;
//creating file name
String fileName= "MathsGame" + timeFileSecond + timeFileDate + timeFileYear + android.os.Build.SERIAL;
//creating the file where the contents will be written to
File file= new File(dir, fileName + ".txt");
FileOutputStream os;
try{
boolean append= true;
os= new FileOutputStream(file, append);
String writeMe =data + "\n";
os.write(writeMe.getBytes());
os.close();
} catch(FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
The method and handler work as is, however my issue is that the values are not formatted as I would like when they are saved and are very messy as you can see:
E.g. of current text file:
I would like my text file to be formatted like this:
How can I implement this formatting in my code?
EDIT (Attempt at formatting):
//Declared globally outside handler
final int maxWordLength = 15;
String spaces[] = new String[maxWordLength];
//Within handler:
//setting up the array of maxlength etc
spaces[0] = "";
for(int i=1; i<maxWordLength ;i++){
spaces[i] = spaces[i-1]+" ";
}
int seconds=0;
//CREATING THE HEADER IN THE TEXT FILE
writeToFileEEGPower(order("Seconds")+order("highAlpha")+order("lowAlpha")+order("highBeta")+order("LowBeta")+
order("lowGamma")+order("midGamma")+order("Delta")+order("Theta")+ "\n");
//creating the string to be written to file
String line = order(seconds+"")+order(eegPower.highAlpha+"")+order(eegPower.lowAlpha+"")+order(eegPower.highBeta+"")+
order(eegPower.lowBeta+"")+order(eegPower.midGamma+"")+order(eegPower.delta+"")+order(eegPower.theta+"")+ "\n";
//write the string to file
writeToFileEEGPower(line);
Current sample output in text file:
You can define your max 'word' length, and complete every 'word' with empty spaces.
for example:
STEP 1
Define maxWordLength. this value describe the width of each column. Should this value will be slightly larger than the longest word (In this example length of 'highAlpha:'=10, choose number>10).
final int maxWordLength = 15;
STEP 2
Create array of empty spaces.
String spaces[] = {""," "," "," "," ", /*....*/ " "};// Complete the missing words up to the last word with 15 spaces.
Or create it dynamically:
String spaces[] = new String[maxWordLength];
spaces[0] = "";
for(int i=1; i<maxWordLength ;i++){
spaces[i] = spaces[i-1]+" ";
}
STEP 3
Define the 'Seconds' var, create the order function at your class and write the header row to the file:
int seconds=0;
//table header row
writeToFileEEGPower(order("Seconds")+order("highAlpha")+order("lowAlpha")+order("highBeta")/+.../);
private String order(String value){
return (value + spaces[maxWordLength-value.length()]);
}
STEP 4
For each handleMessage create a line and save it to the file:
String line = order(seconds+"")+order(eegPower.highAlpha+"")+order(eegPower.lowAlpha+"")+order(eegPower.highBeta+"")//+...;
writeToFileEEGPower(line);
in my android application the user can send feedback
public void c_send_send(View v) {
Uri uri = Uri.parse("mailto:xx#xx.net");
Intent send = new Intent(Intent.ACTION_SENDTO, uri);
send.putExtra(Intent.EXTRA_SUBJECT, "feedback");
send.putExtra(
Intent.EXTRA_TEXT,
DeviceInformation(getResources().getString(R.string.app_name),
getResources().getString(R.string.app_version)));
startActivity(Intent.createChooser(send, "feedback"));
}
public static String DeviceInformation(String app_name, String app_version) {
String EnterTextHere = "[Enter Text Here]";
Spannable spanText = Spannable.Factory.getInstance().newSpannable(EnterTextHere);
spanText.setSpan(new BackgroundColorSpan(0xFFFFFF00), 1, 17, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
String info = "\n" + spanText + "\n\n\n\nDevice Model: "
+ android.os.Build.MANUFACTURER
+ " " + android.os.Build.MODEL + "\nAndroid Version: "
+ Build.VERSION.RELEASE + "\nApplication Version: "
+ app_version;
return info;
}
the question how can i make
[Enter Your Text Here]
highlighted as shown in the picture posted in the link below
Example
Spannable strings are a very good way to use different styling in a single string. try exploring its different functions.
You can make it highlighted by the Toast option in android
Toast.makeText(getApplicationContext(), (String)data.result, Toast.LENGTH_LONG).show();
I'm developing an app where I need to send 3 seekbar's values to a PCB via bluetooth. I've done all the bluetooth code based on the bluetoothchat example. I first modified it to send a string with these 3 values. But now, I need to do something more dificult and i don't know how to do it.
First of all, in the app i modify the seekbars and then i click on the send button. In the code, I need to set a string for each seekbar's value, because I need to access to the MCU variables and set each variable address, value, CRC etc...
So, I need to know the correct way to do this. Here is the code where i define the send function:
/**
* SEND THREAD
*/
/**[Start Thread + Send command + Nº bytes thread + Nº bytes variable + Address + Variable value + CRC]*/
public void sendValues() {
/**Set the seekbars values into a string*/
send_value1 = Integer.toString(savedProgress1);
send_value2 = Integer.toString(savedProgress2);
send_value3 = Integer.toString(savedProgress3);
String message1 = start_thread+" "+send_command+" "+num_byte_trama1+ " "+num_byte_variable+" "+pos_reg_1+" "+Value+" "+CRC;
String message2 = start_thread+" "+send_command+" "+num_byte_trama1+ " "+num_byte_variable+" "+pos_reg_2+" "+Value+" "+CRC;
String message3 = start_thread+" "+send_command+" "+num_byte_trama1+ " "+num_byte_variable+" "+pos_reg_3+" "+Value+" "+CRC;
String message4 = start_thread+" "+send_command+" "+num_byte_trama2+ " "+num_byte_variable+" "+pos_reg_save_request+" "+Value+" "+CRC;
String message5 = start_thread+" "+send_command+" "+num_byte_trama2+ " "+num_byte_variable+" "+pos_reg_save_status+" "+Value+" "+CRC;
/**Check that we're actually connected before trying anything*/
if (GlobalVar.mTransmission.getState() != GlobalVar.STATE_CONNECTED) {
Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
return;
}
/**Get the message bytes and tell the Transmission to write*/
byte[] send = message.getBytes();
GlobalVar.mTransmission.write(send);
/**Reset out string buffer to zero*/
GlobalVar.mOutStringBuffer.setLength(0);
}
There are these few things that I ask you to help me:
1- Need to know how to calculate the CRC
2- I need to send these 5 strings together when pressing the send button.
In the part where i get the bytes to send, I don't know If the right way to do this would be to add these 5 strings on 1 and send this one (maybe it would be to long if I do this), or to create a function to send these 5 separately but at the same time.
This is the edited code to send each message one by one:
/**Conversion to decimal of the seekbar's % value*/
send_int1 = ((savedProgress1 * 20480) / 100) * -1;
send_int2 = ((savedProgress2 * 20480) / 100) * -1;
send_int3 = ((savedProgress3 * 20480) / 100) * -1;
/**Conversion to string of the previous values to send in the string message*/
sendValue1 = Integer.toString(send_int1);
sendValue2 = Integer.toString(send_int1);
sendValue3 = Integer.toString(send_int1);
String message1 = start_thread+" "+send_command+" "+num_byte_trama1+" "+num_byte_variable+" "+pos_reg_1+" "+sendValue1+" " ;
String message2 = start_thread+" "+send_command+" "+num_byte_trama1+" "+num_byte_variable+" "+pos_reg_2+" "+sendValue2+" " ;
String message3 = start_thread+" "+send_command+" "+num_byte_trama1+" "+num_byte_variable+" "+pos_reg_3+" "+sendValue3+" " ;
String message4 = start_thread+" "+send_command+" "+num_byte_trama2+" "+num_byte_variable+" "+pos_reg_save_request+" " ;
String message5 = start_thread+" "+send_command+" "+num_byte_trama2+" "+num_byte_variable+" "+pos_reg_save_status+" " ;
/**Check that we're actually connected before trying anything*/
if (GlobalVar.mTransmission.getState() != GlobalVar.STATE_CONNECTED) {
Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
return;
}
/**Get the message bytes and tell the Transmission to write*/
byte[] send1 = message1.getBytes();
GlobalVar.mTransmission.write(send1);
//Wait untill I receive the confirmation from the MCU
byte[] send2 = message2.getBytes();
GlobalVar.mTransmission.write(send2);
byte[] send3 = message3.getBytes();
GlobalVar.mTransmission.write(send3);
byte[] send4 = message4.getBytes();
GlobalVar.mTransmission.write(send4);
byte[] send5 = message5.getBytes();
GlobalVar.mTransmission.write(send5);
/**Reset out string buffer to zero*/
GlobalVar.mOutStringBuffer.setLength(0);
}
For your frame, I recommand you to use this kind of frame :
final byte[] HEADER = AA11 // For example
// When you want to send a message :
Strign messageToSend = new String(HEADER) + yourStringMessage
It'll be easier for you to analyze the frame when you receive it.
Then, for the CRC, I can't answer if you don't tell the kind of CRC. In my app, I used
private static char createCRC(byte[] frame)
{
int crc = 0;
for(byte i : frame)
{
crc = crc^i;
}
return (char)crc;
}
to create the CRC by "XORing" each byte of my message , and then check a CRC is quite easy
UPDATE : Well, I finally get it.
In the BluetoothChat activity, you get a string version of message, and the byte[] one.
If you want to get the first byte of the message, just add byte myByte = readBuf[0] before String readMessage = new String(readBuf, 0, msg.arg1);
Then, String readMessage = new String(myByte, 0, msg.arg1);
I got this part inside my json object. But I couldn't get this as a java List. It give error. So I tried to take it as a String Array. But it was same as before. So what should I use to parse this data to use with my android application ?
cuisine: {
-cuisine_names: [
"All (36)"
"Malaysian/ Singaporean (1)"
"Asian (1)"
"Australian (2)"
"Chinese (1)"
"European (3)"
"Spanish (1)"
"Greek (2)"
"Steak House (1)"
"Indian (1)"
"International (7)"
"Thai (1)"
"Italian (8)"
"Modern Australian (7)"
]
-price_ranges: [
"Any Price"
"$0-15"
"$15-30"
"$30+"
]
-times: [
"Any Time"
"05:30PM"
"06:00PM"
"06:30PM"
"07:00PM"
"07:30PM"
"08:00PM"
"08:30PM"
"09:00PM"
"09:30PM"
"10:00PM"
"10:30PM"
"11:00PM"
"11:30PM"
]
}
Thanks in advance !
To fill a list with a JSONObject, you should use a function like this (where NewsBSR is a custom object with some basic fields):
private ArrayList<NewsBSR> getListObjectsNews(JSONObject objNews)
{
ArrayList<NewsBSR> listNews = new ArrayList<NewsBSR>();
try{
for (Iterator iterator = objNews.keys(); iterator.hasNext();)
{
String cle = String.valueOf(iterator.next());
Object objet = objNews.get(String.valueOf(cle));
Log.v("V", "News: "+cle+ " : "+objet.toString());
if (cle.equals("results"))
{
JSONArray array = objNews.getJSONArray(cle);
for(int i = 0; i < array.length() ; i++)
{
Object obj = array.get(i);
Iterator it = ((JSONObject) obj).keys();
NewsBSR news = new NewsBSR();
while (it.hasNext())
{
String k = String.valueOf(it.next());
String val = ((JSONObject) obj).getString(k);
Log.v("V", "Array content : "+k+ " : "+val);
if (k.equals("tt") && val.length() > 0)
{
news.setTitle(val);
}
if (k.equals("dt") && val.length() > 0)
{
news.setDate(UtilsDate.stringToDate(val));
}
if (k.equals("num") && val.length() > 0)
{
news.setId(val);
}
}
listNews.add(news);
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.v("V", "Error HOME: "+ e.getMessage());
e.printStackTrace();
}
return (listNews);
}
I think you have forgotten put commas. And you can use this
http://www.androidcompetencycenter.com/2009/10/json-parsing-in-android/
The json format is not supposed to be like that.
first, there should be a root object surrounding the codes like this.
{ <---this
cuisine: {
-cuisine_names: [
"All (36)"........
} <-- and this
and then you need commas between every string in the array like so
"Australian (2)",
"Chinese (1)",
"European (3)",
"Spanish (1)",
"Greek (2)",
"Steak House (1)",
It's very simple with Gson:
public class Foo
{
static String jsonInput =
"{" +
"\"cuisine\": {" +
"\"cuisine_names\": [" +
"\"All (36)\"," +
"\"Malaysian/ Singaporean (1)\"," +
"\"Asian (1)\"," +
"\"Australian (2)\"," +
"\"Chinese (1)\"," +
"\"European (3)\"," +
"\"Spanish (1)\"," +
"\"Greek (2)\"," +
"\"Steak House (1)\"," +
"\"Indian (1)\"," +
"\"International (7)\"," +
"\"Thai (1)\"," +
"\"Italian (8)\"," +
"\"Modern Australian (7)\"" +
"]," +
"\"price_ranges\": [" +
"\"Any Price\"," +
"\"$0-15\"," +
"\"$15-30\"," +
"\"$30+\"" +
"]," +
"\"times\": [" +
"\"Any Time\"," +
"\"05:30PM\"," +
"\"06:00PM\"," +
"\"06:30PM\"," +
"\"07:00PM\"," +
"\"07:30PM\"," +
"\"08:00PM\"," +
"\"08:30PM\"," +
"\"09:00PM\"," +
"\"09:30PM\"," +
"\"10:00PM\"," +
"\"10:30PM\"," +
"\"11:00PM\"," +
"\"11:30PM\"" +
"]" +
"}" +
"}";
public static void main(String[] args)
{
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
CuisineContainer cc = gson.fromJson(jsonInput, CuisineContainer.class);
System.out.println(cc);
}
}
class CuisineContainer
{
private Cuisine cuisine;
#Override
public String toString()
{
return cuisine.toString();
}
}
class Cuisine
{
private String[] cuisine_names;
private String[] price_ranges;
private String[] times;
#Override
public String toString()
{
StringBuilder result = new StringBuilder();
result.append("cuisine_names: ");
result.append(Arrays.asList(cuisine_names));
result.append(System.getProperty("line.separator"));
result.append("price_ranges: ");
result.append(Arrays.asList(price_ranges));
result.append(System.getProperty("line.separator"));
result.append("times: ");
result.append(Arrays.asList(times));
return result.toString();
}
}
output:
cuisine_names: [All (36), Malaysian/ Singaporean (1), Asian (1), Australian (2), Chinese (1), European (3), Spanish (1), Greek (2), Steak House (1), Indian (1), International (7), Thai (1), Italian (8), Modern Australian (7)]
price_ranges: [Any Price, $0-15, $15-30, $30+]
times: [Any Time, 05:30PM, 06:00PM, 06:30PM, 07:00PM, 07:30PM, 08:00PM, 08:30PM, 09:00PM, 09:30PM, 10:00PM, 10:30PM, 11:00PM, 11:30PM]