Android open UTF-8 XML - android

Hello I get some xml file
They are on UTF-8 so i follow some sample and my code look like this
String text = "";
String str;
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(Path), "UTF-8"));
while ((str = in.readLine()) != null) {
text += str;
}
return text;
And then i try to parse the code with the dom parser
Document doc = parser.getDomElement(result);
And this fail
I have check my xml file with a hexeditor
I have the following charcode before "<": ef bb bf
What have i miss? why getDomElement tell me
Unexpected token (position:TEXT #1:2)

text += str + "\n";
If there was a line break in a tag:
<img
src="smile.jpg"/>
you could get:
<imgsrc="smile.jpg">
And some other cases.
StringBuilder text = new StringBuilder();
try (BufferedReader in = new BufferedReader(new InputStreamReader(
new FileInputStream(Path), "UTF-8"))) {
String str;
while ((str = in.readLine()) != null) {
text.append(str).append("\n");
}
} // Does an in.close()
return text.toString();

Related

Unable to split mix latin & arabic string from a file in android

Need to parse this file (mixed latin & arabic):
1|حِيمِ
2|الَمِينَ
The file was saved as UTF8 in notepad++, and put in android asset folder.
Expected result: for line1, the entries are "1" and "حِيمِ" (split by "|").
AssetManager manager = context.getAssets();
InputStream inStream = null;
inStream = manager.open("file.txt");
BufferedReader buffer = new BufferedReader(new InputStreamReader(inStream, "UTF-8"));
String line = "";
while ((line = buffer.readLine()) != null) {
String lineEnc = URLEncoder.encode(line, "UTF-8");
String[] columns = lineEnc.split("%7C");
if (columns.length>=3) {
Toast toast = Toast.makeText(context, "Line: " + columns[0] + " and " + columns[1], Toast.LENGTH_LONG);
toast.show();
}
}
Actual Result:
columns[0] = "1" ok, but
columns[1] = "%D8%AD%D9..." not Ok, expected "حِيمِ".
How to fix this, or is there better way? Please help. Thanks in advance.
Solved, changing:
while ((line = buffer.readLine()) != null) {
String lineEnc = URLEncoder.encode(line, "UTF-8");
String[] columns = lineEnc.split("%7C");
into
while ((line = buffer.readLine()) != null) {
String[] columns = line.split("\\|");

android- stream is closed when using URLConnection

I've an asynctask , this is the code inside background :
try {
URL url = new URL(urls);
Log.v("this", urls);
URLConnection conn = url.openConnection();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(conn.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String lineC;
StringBuffer sb = new StringBuffer();
while ((lineC = bufferedReader.readLine()) != null)
{
sb.append(lineC );
}
Log.v("this",sb.toString() + " I need this for something else");
NodeList nodes = doc.getElementsByTagName("data");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList title = element.getElementsByTagName("content");
Element line = (Element) title.item(0);
if (i == 0)
random = line.getTextContent();
else if (i == 1)
topsell = line.getTextContent();
else if (i == 2)
jadidtarin = line.getTextContent();
else if (i == 3)
pishnahad = line.getTextContent();
}
} catch (Exception e) {
e.printStackTrace();
goterror = true;
Log.v("this", e.getMessage() + "eror");
}
When I remove these lines , it works fine and I get no problem.
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String lineC;
StringBuffer sb = new StringBuffer();
while ((lineC = bufferedReader.readLine()) != null)
{
sb.append(lineC );
}
I don't close anything but when I run the code, I get this error "Stream is closed" , I don't know why .
How can I solve this problem ? as I said in the code, I need to save the whole returned value .
How can I solve this problem ?
Instead of using:
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
Use
BufferedReader bufferedReader = new BufferedReader(new BufferedInputStream(conn.getInputStream()));

only last entry is shown in csv file during reading?

i am reading a file using the following code
`FileReader fr=new FileReader("/mnt/sdcard/content.csv");
BufferedReader in = new BufferedReader(fr);
String reader = "";
while ((reader = in.readLine()) != null){
String[] RowData = reader.split(",");
id = RowData[0];
path = RowData[1];`
and i have also tried using the opencsv class but with both the method i am only able to read the last entry in the file..
what am i missing?can someone explain to me?
FileReader fr=new FileReader("/mnt/sdcard/playlist_record.csv");
BufferedReader in = new BufferedReader(fr);
String reader = "";
while ((reader = in.readLine()) != null){
String[] RowData = reader.split(",");
id = RowData[0];
path = RowData[1];
type= RowData[2];
update= RowData[3];
server= RowData[4];
t1.setText(id);
// t1.append(path);
// t1.append(type);
// t1.append(server);
}
in.close();
this is my code i am using to read the file

Android JSON parse troubles

I have a web service returning the following string verbatim:
"{\"type\":\"youtube\", \"data\":\"http://66.84.12.156/android/?x=12&uid=4&lati=40.73972412&longi=-73.99234962&y=14&pixel_id=7224&pid=4&surface_id=7&fn=showHTML&data_id=7224&data=kT2UQ8TYMpk\",\"pixel_id\":\"471\",\"x\":\"12\",\"y\":\"14\",\"pid\":\"4\",\"surface_id\":\"7\",\"data_id\":\"7224\",\"user_id\":\"4\"}"
Code looks lke:
dataScanner.client = new DefaultHttpClient();
dataScanner.post = new HttpPost("http://someurl/somepage.php");
post.setEntity(new UrlEncodedFormEntity(userKV));
Log.d("DST Scanner", "post string:" + post.toString());
HttpResponse response = client.execute(post);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line);
}
Log.d("DST Scanner", "Post Response (string)" + builder.toString());
//JSONTokener tokener = new JSONTokener(builder.toString());
finalResult = new JSONObject(builder.toString());
I've tried many different formats (escaped quotes, unescaped quotes, no surrounding quotes, escaped forward slashes), but I keep getting this error:
org.json.JSONException: Value {"type":"youtube", "data":"http://66.84.12.156/android/?x=12&uid=4&lati=40.73972412&longi=-73.99234962&y=14&pixel_id=7224&pid=4&surface_id=7&fn=showHTML&data_id=7224&data=kT2UQ8TYMpk","pixel_id":"471","x":"12","y":"14","pid":"4","surface_id":"7","data_id":"7224","user_id":"4"} of type java.lang.String cannot be converted to JSONObject
Everything looks fine to me, but I've been looking at this so long I wouldn't be surprised if there's some silly thing I'm doing..
I'm new to json, but all of my JSON start and end with "[" and "]" and I use PHP to echo out the json_encode method.
On Android side i use:
try {
URL pHH = new URL("http://192.168.1.5/somephp.php");
URLConnection WC = pHH.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(WC.getInputStream()));
String line;
while((line = in.readLine()) != null){
JSONArray ja = new JSONArray(line);
for (int i = 0; i < ja.length(); i++){
JSONObject jo = (JSONObject) ja.get(i);
items[i] = jo.getString("title");
thumbnails[i] = jo.getString("thumb");
links[i] = jo.getString("link");
}
}
char[] utf8 = null;
StringBuilder properString = new StringBuilder("");
utf8 = Response.toCharArray();
for (int i = 0; i < utf8.length; i++) {
if ((int) utf8[i] < 65000) {
properString.append(utf8[i]);
}
}
System.out.println("Response of Login::"
+ properString.toString());

Android URL Content to String

I would like to connect to a Website, filter some content and then put it in a String but I don´t know how to do this.
public void zahlenLaden (View view) throws Exception {
URL oracle = new URL("http://www.blabla.de");
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
//What I have to write here?
}
Declare a String to output to before the while loop:
String output = "";
Then just append to that String in each iteration:
output += inputLine + "\n"; (don't forget the omitted newline)
StringBuilder sb = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
sb.append(inputLine + "\n");
}
then just do sp.toString();
Nikola's answer is OK, just an improvement on the use of StringBuilder:
StringBuilder sb = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
sb.append(inputLine).append("\n");
}

Categories

Resources