I am new to android studio and object oriented programming in general so apologies if this is obvious but I cannot get my head round it. I have a small xml web server and I can connect to it and send data to it and I can also read it back and view it in the monitor. I want to parse XML
but cannot get it to work.
The line "System.out.println(output);" gives me the output from the server in in a string.
The response is saved from a string but I think I need it in a different format to do a pull parser on it. The program basically prints this string and then crashes. What is the best way to parse my data? Any help would be really appreciated.
public class HTTPRequestTask extends AsyncTask<String , Void, String > {
@Override
protected String doInBackground(String... args) {
String IP = args[0];
System.out.println(IP);
try {
URL url = new URL(IP);
XmlPullParser recievedData = XmlPullParserFactory.newInstance().newPullParser();
recievedData.setInput(url.openStream(),null);
System.setProperty("http.keepAlive", "false");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
XmlPullParser parser = Xml.newPullParser();
parser.setInput(new StringReader(output));
System.out.println("doc");
System.out.println(parser);
System.out.println("Disconnecting\n");
conn.disconnect();
System.out.println(recievedData);
processRecievedData(recievedData);
String[] separated = output.split("F");
// separated[0]; // this will contain "Fruit"
// separated[1]; // this will contain " they taste good"
//System.out.println(separated);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
return null;
}
I also try and use Document but am not sure what format Document is in and whether I can print it like that.
public Document GetData(String output){
try {
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
builder = builderFactory.newDocumentBuilder();
//Document xmlDoc = builder.parse(output);
//System.out.println(xmlDoc);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}