Reputation: 1037
I receive data from external device and save on mobile as text file. My problem is - I need to get value userID from that text file. Value is kept in tag. For example
<user>1234</user>
I'm trying to use JSoup to archieve this but I have some complications.
Here is my code :
public CommunicationThread(Socket clientSocket) {
this.clientSocket = clientSocket;
try {
InputStream in = this.clientSocket.getInputStream();
Date date = new Date();
File root = new File("/sdcard/mente/" + user.getID() );
if(!root.exists())
root.mkdirs();
String fileName = connectedDeviceSerialNumber + "_" + date + ".txt".replace(" ","_");
file = new File(root,fileName);
OutputStream out = new FileOutputStream(file);
int count;
StringBuilder sb = new StringBuilder();
while ((count = in.read(bytes)) > 0) {
out.write(bytes, 0, count);
for (byte b : bytes) {
sb.append(String.format("%02X ", b));
}
Log.e(TAG, "CommunicationThread: " + sb.toString() );
if (sb.toString().contains("3C 65 6E 64 5F 72 61 77 3E 74 72 75 65 3C 2F 65 6E 64 5F 72 61 77 3E") && syncProgressDialog != null) {
syncProgressDialog.dismiss();
}
}
Document doc = Jsoup.parse(sb.toString());
Elements el = doc.select("user");
String userId = el.attr("user");
Log.e(TAG, "STR: " + userId );
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream(), Charset.forName("ISO-8859-2")));
Log.e(TAG, "synchData1: ");
} catch (IOException e) {
Log.e(TAG, "error: " + e.getMessage());
}
}
Thanks in advance for helping :)
Upvotes: 0
Views: 257
Reputation: 18677
My guess is that you are not getting the text properly
Instead
Document doc = Jsoup.parse(sb.toString());
Elements el = doc.select("user");
String userId = el.attr("user");
You should
String userId = "";
Document doc = Jsoup.parse(sb.toString());
Elements el = doc.select("user"); // el is an ArrayList... not a single element...
if(!el.isEmpty()) {
Element singleElement = el.get(0);
if (singleElement.hasText()) {
userId = singleElement.text(); // Don't read attr... but text()
} else {
Log.e(TAG, "tag <user> has no text");
}
} else {
Log.e(TAG, "tag <user> not fould");
}
EDIT
I tested with a file with following format:
<user>1234</user>
<pass>1234</pass>
It works fine. You said is not working for you, so, maybe, sb.toString()
does not contain the proper text (which you can log to confirm... Log.e(TAG, "sb: " + sb.toString());
) or it has a different format that I tested.... So, please, share an example of string that you are reading.
Upvotes: 3