I want to parse an xml file of this form from a url into my android application.
<ArrayOfCurrency xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/MobileAssignmentApi.Models">
<Currency>
<Buy>21.19573</Buy>
<CurrencyId>53</CurrencyId>
<Name>USD/MXN</Name>
<PipMultiplier>10000</PipMultiplier>
<Sell>21.15679</Sell>
</Currency>
<Currency>
<Buy>1.46806</Buy>
<CurrencyId>22</CurrencyId>
<Name>EUR/NZD</Name>
<PipMultiplier>10000</PipMultiplier>
<Sell>1.46395</Sell>
</Currency>
<Currency>
<Buy>1.34658</Buy>
<CurrencyId>15</CurrencyId>
<Name>EUR/CAD</Name>
<PipMultiplier>10000</PipMultiplier>
<Sell>1.3445</Sell>
</Currency>
.
.
.
</ArrayOfCurrency>
It is an array of currencies.
After a lot of effort i managed to parse the xml file into a string into my application.
The string have now the following form.
[{"currencyId":53,"buy":21.23042,"sell":21.1921,"name":"USD/MXN","pipMultiplier":10000},{"currencyId":22,"buy":1.50225,"sell":1.49891,"name":"EUR/NZD","pipMultiplier":10000},{"currencyId":15,"buy":1.38201,"sell":1.38083,"name":"EUR/CAD","pipMultiplier":10000},{"currencyId":62,"buy":0.69619,"sell":0.69404,"name":"NZD/CHF","pipMultiplier":10000},{"currencyId":19,"buy":80.085,"sell":79.968,"name":"NZD/JPY","pipMultiplier":100},{"currencyId":13,"buy":1.23727,"sell":1.23613,"name":"GBP/CHF","pipMultiplier":10000},{"currencyId":16,"buy":0.95424,"sell":0.95167,"name":"AUD/CAD","pipMultiplier":10000},{"currencyId":5,"buy":1.00469,"sell":1.00414,"name":"USD/CHF","pipMultiplier":10000},{"currencyId":1,"buy":122.014,"sell":121.839,"name":"EUR/JPY","pipMultiplier":100},{"currencyId":60,"buy":0.9092,"sell":0.90615,"name":"NZD/CAD","pipMultiplier":10000},{"currencyId":97,"buy":30.806,"sell":30.793,"name":"TRY/JPY","pipMultiplier":100},{"currencyId":10,"buy":0.68269,"sell":0.6823,"name":"NZD/USD","pipMultiplier":10000},{"currencyId":23,"buy":1.61316,"sell":1.61245,"name":"GBP/CAD","pipMultiplier":10000},{"currencyId":9,"buy":1.31115,"sell":1.31023,"name":"USD/CAD","pipMultiplier":10000},{"currencyId":3,"buy":1.21594,"sell":1.21552,"name":"GBP/USD","pipMultiplier":10000},{"currencyId":27,"buy":1.75536,"sell":1.7494,"name":"GBP/NZD","pipMultiplier":10000},{"currencyId":63,"buy":3.6378,"sell":3.62206,"name":"USD/TRY","pipMultiplier":10000},{"currencyId":64,"buy":3.83117,"sell":3.81819,"name":"EUR/TRY","pipMultiplier":10000},{"currencyId":28,"buy":0.73074,"sell":0.72814,"name":"AUD/CHF","pipMultiplier":10000},{"currencyId":50,"buy":9.54563,"sell":9.51557,"name":"EUR/SEK","pipMultiplier":10000},{"currencyId":18,"buy":87.091,"sell":86.919,"name":"CAD/JPY","pipMultiplier":100},{"currencyId":14,"buy":1.43031,"sell":1.4289,"name":"EUR/AUD","pipMultiplier":10000},{"currencyId":8,"buy":0.71693,"sell":0.7154,"name":"AUD/USD","pipMultiplier":10000},{"currencyId":17,"buy":83.97,"sell":83.811,"name":"AUD/JPY","pipMultiplier":100},{"currencyId":11,"buy":0.84385,"sell":0.84329,"name":"EUR/GBP","pipMultiplier":10000},{"currencyId":4,"buy":115.641,"sell":115.555,"name":"USD/JPY","pipMultiplier":100},{"currencyId":61,"buy":0.75641,"sell":0.75508,"name":"CAD/CHF","pipMultiplier":10000},{"currencyId":20,"buy":1.67121,"sell":1.66758,"name":"GBP/AUD","pipMultiplier":10000},{"currencyId":76,"buy":1171.7,"sell":1170.674,"name":"XAU/USD","pipMultiplier":100},{"currencyId":6,"buy":142.45,"sell":142.188,"name":"GBP/JPY","pipMultiplier":100},{"currencyId":2,"buy":1.04081,"sell":1.03929,"name":"EUR/USD","pipMultiplier":10000},{"currencyId":54,"buy":13.77633,"sell":13.70746,"name":"USD/ZAR","pipMultiplier":10000},{"currencyId":7,"buy":1.05845,"sell":1.05868,"name":"EUR/CHF","pipMultiplier":10000},{"currencyId":52,"buy":8.53823,"sell":8.51386,"name":"USD/NOK","pipMultiplier":10000},{"currencyId":48,"buy":9.0615,"sell":9.03791,"name":"USD/SEK","pipMultiplier":10000},{"currencyId":12,"buy":113.73,"sell":113.454,"name":"CHF/JPY","pipMultiplier":100},{"currencyId":21,"buy":1.03599,"sell":1.03438,"name":"AUD/NZD","pipMultiplier":10000},{"currencyId":51,"buy":8.99332,"sell":8.96375,"name":"EUR/NOK","pipMultiplier":10000},{"currencyId":150,"buy":6.7165,"sell":6.7144,"name":"USD/CNH","pipMultiplier":1000},{"currencyId":77,"buy":15.142,"sell":15.112,"name":"XAG/USD","pipMultiplier":100},{"currencyId":93,"buy":7.182,"sell":7.129,"name":"ZAR/JPY","pipMultiplier":100}]
using the following code:
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class MainActivity extends AppCompatActivity {
String str = "http://massignment.zulutrade.com/api/rates";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new AsyncTaskClass().execute(str);
}
class AsyncTaskClass extends AsyncTask<String, Void,String > {
private Exception exception;
protected String doInBackground(String ...params) {
URLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(str);
connection = url.openConnection();
connection.setDoOutput(true);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line = "";
StringBuilder builder = new StringBuilder();
int i=0;
while ((line = reader.readLine()) != null) {
builder.append(line+"\n");
// Log.w("Response ", "> " + line );
i++;
}
String xml = builder.toString();
}
catch( IOException e) {
e.printStackTrace();
}
return "0k";
}
protected void onPostExecute() {
}
}
}
I need to parse that xml/string to its contents.
Any idea how can i do that parsing?
Assuming that your code is in Java - there are some good XML parsers available. You may want to use one of them to parse your XML.
I have This code and I tried to getting items from this string
but it's failed
I have used eclipse IDE
I have parsing the json string from remote host
package selectDB;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.sql.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class selectDB
{
public static void main(String[] args) throws IOException, ParseException
{
String line;
String s = "";
URL u = new URL("http://192.168.3.1/android/select.php");
URLConnection c = u.openConnection();
InputStream r = c.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(r));
for(; (line = reader.readLine()) != null;)
{
s+=line;
}
System.out.println(s);
try{
JSONObject jObject = new JSONObject(s);
String projecname=(String) jObject.get("name");
System.out.print(projecname);
}catch(Exception e)
{}
}
}
the result Json string is like this
{"result" : "true" , "messages" : [{"id":"866343023633578","latitute":"27","longitude":"31","number_phone":"01113171374"},{"id":"352168066354050","latitute":"27","longitude":"31","number_phone":"202222"},{"id":"50","latitute":"50","longitude":"100","number_phone":"50"},{"id":"110","latitute":"50","longitude":"50","number_phone":"110"},{"id":"120","latitute":"27","longitude":"31","number_phone":"120"},{"id":"130","latitute":"28","longitude":"29","number_phone":"120"},{"id":"140","latitute":"30","longitude":"40","number_phone":"140"},{"id":"800","latitute":"60","longitude":"30","number_phone":"800"},{"id":"353629054230064","latitute":"70","longitude":"80","number_phone":"120"}]}
please help me
thanks
You have to parse the json string into JSONObject using JSONParser
You cannot simply parameterise JSONObject with a string.
So you have to do:
JSONParser parser = new JSONParser();
JSONObject jObject=(JSONObject)parser.parse(jsonstr);
String projecname=(String) jObject.get("name");
I have a problem while getting a push notification on the server side. I am using C2DM sever connection to achieve the push notification. Its working fine on android but not in the Java Servecr. I'm able to get the registration ID and authentication code but the handling stops when it comes to the line:
OutputStream out = conn.getOutputStream();
It does not throw anything, just stops.
If anyone has a solution for this then please guide me. I am adding the whole code so you can go through and tell me where I'm wrong in getting the result.
import org.apache.http.client.methods.HttpPost;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
import javax.print.DocFlavor.INPUT_STREAM;
import org.apache.http.HttpClientConnection;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.DefaultHttpClientConnection;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class Server {
private static String key=null;
// private final static String AUTH = "authentication";
private static final String UPDATE_CLIENT_AUTH = "Update-Client-Auth";
public static final String PARAM_REGISTRATION_ID = "registration_id";
public static final String PARAM_DELAY_WHILE_IDLE = "delay_while_idle";
public static final String PARAM_COLLAPSE_KEY = "collapse_key";
private static final String UTF8 = "UTF-8";
private static String Authcode = null;
// Registration is currently hardcoded
private final static String YOUR_REGISTRATION_STRING = "reg id";
public void getAuthentification() {
System.out.println("check");
//HttpPost post = new HttpPost("http://www.google.com/accounts/ClientLogin");
try {
System.getProperties().put("proxySet", true);
System.getProperties().put("proxyHost","proxy" );
System.getProperties().put("proxyPort","8080");
System.out.println("getAuthentication method called****************************");
URL url=new URL("https://www.google.com/accounts/ClientLogin");
URLConnection connection=url.openConnection();
connection.setDoOutput(true);
HttpURLConnection conn=(HttpURLConnection)connection;
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(true);
StringBuilder content = new StringBuilder();
content.append("Email=").append("xyz#gmail.com");
content.append("&Passwd=").append("asdfgt");
content.append("&service=").append("ac2dm");
content.append("&source=").append("MY_APP-V0.1");
content.append("&accountType=").append("HOSTED_OR_GOOGLE");
OutputStream out = conn.getOutputStream();
out.write(content.toString().getBytes("UTF-8"));
out.close();
int res = conn.getResponseCode();
System.out.println(res + "Success");
StringBuffer resp = new StringBuffer();
if(res == HttpsURLConnection.HTTP_OK){
InputStream in = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
System.out.println("inside");
if (line.startsWith("Auth=")) {
Authcode = line.substring(5);
resp.append(line.substring(5));
System.out.println(line.substring(5));
System.out.println("something to be done here..");
}
}
rd.close();
}
}
}
public void sendMessage() {
try {
System.out.println(YOUR_REGISTRATION_STRING);
System.out.println("Authcode = " + Authcode);
System.getProperties().put("proxySet", true);
System.getProperties().put("proxyHost","proxy" );
System.getProperties().put("proxyPort","8080");
URL url1 = new URL("https://android.apis.google.com/c2dm/send");
System.out.println("here2.5");
HttpURLConnection conn1 = (HttpURLConnection) url1.openConnection();
System.out.println("here2.6");
conn1.setDoInput(true);
conn1.setDoOutput(true);
conn1.setUseCaches(false);
conn1.setRequestMethod("POST");
conn1.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
conn1.setRequestProperty("Authorization", "GoogleLoginauth="+ Authcode);
System.out.println("here2.7");
OutputStream out = conn1.getOutputStream();
System.out.println("send Message method.");
String auth_key="n/a";
if(key!=null) {
auth_key=Authcode;
}
System.out.println("here");
// Send a sync message to this Android device.
StringBuilder postDataBuilder = new StringBuilder();
postDataBuilder.append(PARAM_REGISTRATION_ID)
.append("=").append(YOUR_REGISTRATION_STRING);
System.out.println("here1");
postDataBuilder.append("&").append(PARAM_COLLAPSE_KEY)
.append("=").append("0");
System.out.println("here2");
postDataBuilder.append("&").append("data.payload")
.append("=").append(URLEncoder.encode("Lars war hier", UTF8));
byte[] postData = postDataBuilder.toString().getBytes(UTF8);
conn1.setRequestProperty("Content-Length",
Integer.toString(postData.length));
// Hit the dm URL.
System.out.println("out created");
out.write(postData);
System.out.println("data written");
out.close();
System.out.println("here3");
int responseCode = conn1.getResponseCode();
System.out.println(String.valueOf(responseCode));
// Validate the response code
if (responseCode == 401 || responseCode == 403) {
// The token is too old - return false to retry later, will
// fetch the token
// from DB. This happens if the password is changed or token
// expires. Either admin
// is updating the token, or Update-Client-Auth was received by
// another server,
// and next retry will get the good one from database.
System.out.println("C2DM, Unauthorized - need token");
}
} catch (Exception ignore) {
// the editor that corrected the indentation of the code could not find any code here so he closed all methods to have a syntactically correct class.
}
}
}
Make sure that you are posting message to url from background thread not from the UI thread.
I hope after this change it will work. Good Luck!!!