Android read large file line by line - android

I'm working on an application which is connection to the web server and receiving an response. I'm saving this response in txt file in internal memory of the device. Now I need to read the whole file line by line, because if I try to read the whole file it's throwing an OutofMemoryException. So for now I'm writing and reading the file with this code :
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://www.rpc.probnata.com");
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("debug_data","1"));
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
HttpResponse response = httpclient.execute(httppost);
Log.w("Response ","Status line : "+ response.getStatusLine().toString());
buffer = EntityUtils.toByteArray(response.getEntity());
FileOutputStream out = this.openFileOutput("response",this.MODE_PRIVATE);
out.write(buffer);
out.close();
Reading the file :
public void parseResponse(){
try {
File myDir = new File(getFilesDir().getAbsolutePath());
BufferedReader br = new BufferedReader(new FileReader(myDir + "/response"));
String line;
while ((line = br.readLine()) != null) {
Log.v("","line : "+line);
handleDataFromSync(line);
}
br.close();
} catch (Exception e){
e.printStackTrace();
}
}
This method parse the response.
public void handleDataFromSync(final String responseBody) {
for(int index=0;index<responseBody.length();index++){
Log.w("Response ","Response size : "+ responseBody.length());
Log.w("","****************Index is : "+index);
int objectIdentificator = 0;
objectIdentificator = Integer.parseInt(responseBody.substring(index,index+packetFieldSizes[0]));
Log.w("Response ","Object Identificator (LONGINT) : "+ objectIdentificator);
index = index+packetFieldSizes[0];
Log.w("","****************Index is (must be 32) : "+index);
String type = null;
type = responseBody.substring(index,index + packetFieldSizes[1]);
Log.w("Response ","TYPE (UNSIGNED BYTE) : "+ type);
short pType = Short.parseShort(type);
Log.w("Response ","TYPE (UNSIGNED BYTE) : "+ pType);
index = index + packetFieldSizes[1];
Log.w("","****************Index is (must be 35) : "+index);
String operation=null;
operation = responseBody.substring(index,index + packetFieldSizes[2]);
short operationType = Short.parseShort(operation);
Log.w("Response ","OPERATION (UNSIGNED BYTE) : "+ operation);
Log.w("Response ","OPERATION (UNSIGNED BYTE) : "+ operationType);
index = index + packetFieldSizes[2];
Log.w("","****************Index is (must be 38) : "+index);
String objectId=null;
objectId = responseBody.substring(index, index + packetFieldSizes[3]);
Log.w("Response ","UID (CHAR, length 32) : "+ objectId);
index = index + packetFieldSizes[3];
Log.w("","****************Index is (must be 70) : "+index);
int id=0;
id = Integer.parseInt(responseBody.substring(index,index + packetFieldSizes[4]));
Log.w("Response ","ID (LONGINT) : "+ responseBody.substring(index, index + packetFieldSizes[4]));
Log.w("Response ","ID (LONGINT) : "+ id);
index = index + packetFieldSizes[4];
Log.w("","****************Index is (must be 102) : "+index);
String size=null;
size = responseBody.substring(index,index + packetFieldSizes[5]);
int dataSize = Integer.parseInt(size);
Log.w("Response ","Data Size (LONGINT) : "+ dataSize);
index = index + packetFieldSizes[5];
Log.w("","****************Index is (must be 134) : "+index);
String hash=null;
hash = responseBody.substring(index,index + packetFieldSizes[6]);
Log.w("Response ","Data Hash (CHAR, length 32 : "+ hash);
index = index + packetFieldSizes[6];
Log.w("","****************Index is (must be 166) : "+index);
String dType=null;
dType = responseBody.substring(index,index + packetFieldSizes[7]);
Log.w("Response ","Data Type (UNSIGNED BYTE) : "+ dType);
short dataType = Short.parseShort(dType);
Log.w("Response ","Data Type (UNSIGNED BYTE) : "+ dataType);
index = index + packetFieldSizes[7];
Log.w("","****************Index is (must be 169) : "+index);
String data=null;
data = responseBody.substring(index, index + dataSize);
Log.w("Response ","Data (CHAR, any length, in BASE64) : "+ data);
index = (index + dataSize)-1;
Log.w("","****************Index is must be : "+index);
byte[] first = Base64.decode(data);
String string = new String(first, "UTF-8");
Log.w("Response ","BASE 64 : "+ string);
}
}
So any idea how to read the next line, because the thing which this code is doing now is to read the first line and after that it's tryint to read the first line again.

Your bufferedReader implementation looks fine so my suspicion would be that there's something going on in your handleDataFromSync method. From the code I would infer that each responseBody is a string of indeterminate length but with repeating patterns of values at known positions. Potential culprits could be your packetFieldSizes[] which we can't inspect and the value of dataSize.
Validate that the index logged values are what you expect them to be and that you are actually making it out of your handleDataFromSync. If that's the case then there's something wrong with your bufferedReader that I didn't see and you'll need to add some additional logging to determine what's causing the failure at that step.

Related

Bluetooth printer prints garbage character for every new object

I am taking reference of P25 Demo Example to print my receipt using Bluetooth printer.
Everything works fine. It's printing receipt also in defined format. But the problem is for every new String and StringBuilder object its printing few garbage characters.
Below I am adding my function:-
private void printStruk() {
String titleStr = "Receipt" + "\n\n";
StringBuilder contentSb = new StringBuilder();
contentSb.append("IDPEL : 435353535435353" + "\n");
contentSb.append("NAMA : LORENSIUS WLT" + "\n");
contentSb.append("TRF/DAYA : 50/12244 VA" + "\n");
contentSb.append("BL/TH : 02/14" + "\n");
contentSb.append("ST/MTR : 0293232" + "\n");
contentSb.append("RP TAG : Rp. 100.000" + "\n");
contentSb.append("JPA REF :" + "\n");
StringBuilder content2Sb = new StringBuilder();
content2Sb.append("ADM BANK : Rp. 1.600" + "\n");
content2Sb.append("RP BAYAR : Rp. 101.600,00" + "\n");
byte[] titleByte = Printer.printfont(titleStr, FontDefine.FONT_24PX,FontDefine.Align_CENTER,
(byte)0x1A, PocketPos.LANGUAGE_ENGLISH);
byte[] content1Byte = Printer.printfont(contentSb.toString(), FontDefine.FONT_24PX,FontDefine.Align_LEFT,
(byte)0x1A, PocketPos.LANGUAGE_ENGLISH);
byte[] content2Byte = Printer.printfont(content2Sb.toString(), FontDefine.FONT_24PX,FontDefine.Align_LEFT,
(byte)0x1A, PocketPos.LANGUAGE_ENGLISH);
byte[] totalByte = new byte[titleByte.length + content1Byte.length +content2Byte.length];
int offset = 0;
System.arraycopy(titleByte, 0, totalByte, offset, titleByte.length);
offset += titleByte.length;
System.arraycopy(content1Byte, 0, totalByte, offset, content1Byte.length);
offset += content1Byte.length;
System.arraycopy(content2Byte, 0, totalByte, offset, content2Byte.length);
offset += content2Byte.length;
byte[] senddata = PocketPos.FramePack(PocketPos.FRAME_TOF_PRINT, totalByte, 0, totalByte.length);
sendData(senddata);
}
In above code, it's printing Title String Receipt in center of the paper,but before that it also print some garbage character.

Android How to print through Bluetooth printer with text alignment and also using table style?

I am trying to print some information through bluetooth printer. I can print plain text. But I can't add any alignment and text format. Also i want to print some data like tableview.
Text format and alignment should be like this:-
Table formatted data should be like this:-
I need some help Please.
Here i include my code which i try:-
String titleStr = "Title" + "\n\n";
StringBuilder contentSb = new StringBuilder();
contentSb.append("Item1 : 1221" + "\n");
contentSb.append("Item2 : test" + "\n");
StringBuilder content2Sb = new StringBuilder();
content2Sb.append("BANK : Us. 1.600" + "\n");
String message = "This is for test." + "\n\n";
long milis = System.currentTimeMillis();
String date = DateUtil.timeMilisToString(milis, "dd-MM-yy / HH:mm") + "\n\n\n\n";
byte[] titleByte = titleStr.getBytes();
byte[] content1Byte = contentSb.toString().getBytes();
byte[] messageByte = message.getBytes();
byte[] content2Byte = content2Sb.toString().getBytes();
byte[] dateByte = date.getBytes();
byte[] totalByte = new byte[titleByte.length + content1Byte.length + messageByte.length +
content2Byte.length + dateByte.length];
int offset = 0;
System.arraycopy(titleByte, 0, totalByte, offset, titleByte.length);
offset += titleByte.length;
System.arraycopy(content1Byte, 0, totalByte, offset, content1Byte.length);
offset += content1Byte.length;
System.arraycopy(messageByte, 0, totalByte, offset, messageByte.length);
offset += messageByte.length;
System.arraycopy(content2Byte, 0, totalByte, offset, content2Byte.length);
offset += content2Byte.length;
System.arraycopy(dateByte, 0, totalByte, offset, dateByte.length);
mmOutputStream.write(totalByte);

How to check word in android

example i have
String = "makan"
how to check last character is "n"
and character number 4 = "a"
and character number 3 = "k"
how to check third charcter of last word,
thanks
You can use the strings method as
char c= "string".charAt(index);
To get the characters in the string.
Edit
You can get the string as array of char as-
String str = "string";
char[] charArray = str.toCharArray();
It depends on the language you are using, but in general read the character by index number (-1 because they start at 0) using []. Or with charAt like Sanjeet said.
Java:
String name = "makan";
bool lastCharacterIsN = name[name.length - 1] == 'n';
bool fourthCharacterIsA = name[3] == 'a';
bool thirdCharacterIsK = name[2] == 'k';
Javascript:
var name = "makan";
var lastCharacterIsN = name[name.length - 1] === 'n';
var fourthCharacterIsA = name[3] === 'a';
var thirdCharacterIsK = name[2] === 'k';
You can do this very simply like this.
String _makan = "makan";
int _length = _makan.length();
System.out.println(" Index of n " +_makan.indexOf("n"));
System.out.println("Length of String : " + _length);
System.out.println("character at last : " + _makan.charAt(_length-1));
System.out.println("character number 3 : " + _makan.charAt(2));
System.out.println("character number 4: " + _makan.charAt(3));

How to replace the word in the string by using replace in Android?

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);

Byte array to string till '\n'

I have Android <-> Arduino bluetooth communication. Sometimes Android gets two messages instead of one from Arduino. What i mean: if i send for ex. 5 bytes message "1234" from Arduino to Android over bluetooth, sometimes i get "1" 1 byte in one message and "234"+\n 4 bytes in second message. Sometimes i get full "1234"+\n 5 byte message and do not have any clue why. I need to split input message by delimiter and if i get separate message i get crash. So i need to append bytes to string till new line char comes.
How to add chars to string till "\n" new line char comes?
Case when data comes:
case BLUETOOTH_RECEIVED:
byte[] buffer = (byte[])msg.obj;
int len = msg.arg1;
if (len > 0 && buffer != null) {
onBluetoothRead(buffer, len);
}
break;
}
buffer to string:
private void onBluetoothRead(byte[] buffer, int len) {
Log.i(LOGGER_TAG, String.format("Received: " + output.replace("\n", "") + " message of " + "%d bytes", len));
String output = new String(buffer, 0, len); // Add read buffer to new string
m_deviceOutput.append(output); // Add (not replace) string to TextView
StringTokenizer splitStr = new StringTokenizer(output, ","); // split string by comma
String numberOne = splitStr.nextToken(); // First split string
String numberTwo = splitStr.nextToken(); // Second split string
numberOne = numberOne.replaceAll("\\D+",""); // replace all chars, leave only numbers
numberTwo = numberTwo.replaceAll("\\D+","");
}
LogCat:
07-22 14:06:15.099: I/DeviceActivity(20370): Received: 1234 message of 5 bytes
07-22 14:06:20.599: I/DeviceActivity(20370): Received: 1234 message of 5 bytes
07-22 14:06:27.349: I/DeviceActivity(20370): Received: 1 message of 1 bytes
07-22 14:06:27.469: I/DeviceActivity(20370): Received: 234 message of 4 bytes
07-22 14:06:37.219: I/DeviceActivity(20370): Received: 1 message of 1 bytes
07-22 14:06:37.349: I/DeviceActivity(20370): Received: 234 message of 4 bytes
in Arduino i can write like this and i want something similar here:
//Get data from RS485:
void READ01(){
while (mySerial.available()){
mySerial.read();
}
mySerial.println("01READ");
momentas1="";
delay(20);
while (mySerial.available()) {
char c = mySerial.read();
if (c == '\n'){
break;
}
momentas1 += c;
}
}
This void READ01 adds chars to string until new line char comes.
You could use a buffer-like implementation by adding obtained string to another string until "\n" is received.
private String packet = "";
private void onBluetoothRead(byte[] buffer, int len) {
Log.i(LOGGER_TAG, String.format("Received: " + output.replace("\n", "") + " message of " + "%d bytes", len));
String output = new String(buffer, 0, len); // Add read buffer to new string
packet += output;
if (packet.endsWith( "\n" ) {
//do what you need to do
m_deviceOutput.append(output); // Add (not replace) string to TextView
StringTokenizer splitStr = new StringTokenizer(packet, ","); // split string by comma
String numberOne = splitStr.nextToken(); // First split string
String numberTwo = splitStr.nextToken(); // Second split string
numberOne = numberOne.replaceAll("\\D+",""); // replace all chars, leave only numbers
numberTwo = numberTwo.replaceAll("\\D+","");
packet = "";
}
}

Categories

Resources