just a simple question here. How can I get the return value on this kind of xml
Art C. Cauyao<$#FBID#$>501912568<$#ENDFBID#$>Tessa Rose
Brainard<$#FBID#$>510831686<$#ENDFBID#$>
Dan Gangan<$#FBID#$>513545777<$#ENDFBID#$>
C Jhec DawAko<$#FBID#$>523059320<$#ENDFBID#$>Jeremy
Please see that I am getting Facebook name and Facebook ID
Is there any way about that?
EDIT
I found out that it is not an xml but rather A JSON (sorry) now my question really is how can I incorporate that returned value?
EDIT SECOND
Sir this what I am doing
Parsing it through this
static final String URL_FBFRIEND ="Some URL"+ "getFBFriends.php";
Now using that I can now parse some data by using my input values. Here is the code
XMLparser parser2 = new XMLparser();
parser2.getXmlFromUrl(URL_FBFRIEND);
//HTTP POST
String url_Getmembermob= URL_FBFRIEND ;
String xml_getMembermob=null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url_Getmembermob);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("...", "...."));
nameValuePairs.add(new BasicNameValuePair("fbID", modGen.facebookID ));
nameValuePairs.add(new BasicNameValuePair("accToken", modGen.tokenID));
nameValuePairs.add(new BasicNameValuePair("reqType", "0"));
Log.i("nameValuePairs", "nameValuePairs=" + nameValuePairs);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpclient.execute(httppost);
HttpEntity httpEntity = httpResponse.getEntity();
xml_getMembermob = EntityUtils.toString(httpEntity);
Log.i("xml-return",""+ xml_getMembermob);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
See that I am logging the returned xml Log.i("xml-return",""+ xml_getMembermob); And thats the output
Sir Ive altered your code`
public static List parseUserList(String userData)
{
List ret = new ArrayList();
int index = 0;
while (index < userData.length())
{
int startFbTag = userData.indexOf(FB_NAME, index);
if (index == -1)
{
return ret;
}
String name = userData.substring(index, startFbTag - index);
startFbTag += FB_NAME.length(); // Start of the actual data
int endFbTag = userData.indexOf(FB_ID, startFbTag);
if (endFbTag == -1)
{
throw new IllegalArgumentException("Unterminated start tag");
}
fbTagValue = userData.substring(startFbTag, endFbTag - startFbTag);
Log.i("UserName",fbTagValue);
//fbId = Long.parseLong(fbTagValue);
//ret.add(new User(name, fbId));
index = endFbTag + FB_ID.length();
}
return ret;
}
I am getting an error here ** fbTagValue = userData.substring(startFbTag, endFbTag - startFbTag);**
what seems to be the problem
This is pretty horrible format. It's not XML. It's not JSON. Assuming you've already got some sort of User class, and that all the data is in a single String, you could write something like this (completely untested):
private static final String FB_START = "<$#FBID#$>";
private static final String FB_END = "<$#ENDFBID#$>";
public static List<User> parseUserList(String userData)
{
List<User> ret = new ArrayList<User>();
int index = 0;
while (index < userData.length())
{
int startFbTag = userData.indexOf(FB_START, index);
if (index == -1)
{
// No tags left. You should check whether you've actually got
// some data left, and potentially throw an exception. It's not
// clear what your data format does here.
return ret;
}
String name = userData.substring(index, startFbTag - index);
startFbTag += FB_START.length(); // Start of the actual data
int endFbTag = userData.indexOf(FB_END, startFbTag);
if (endFbTag == -1)
{
throw new IllegalArgumentException("Unterminated start tag");
}
String fbTagValue = userData.substring(startFbTag, endFbTag - startFbTag);
long fbId = Long.parseLong(fbTagValue);
ret.add(new User(name, fbId));
index = endFbTag + FB_END.length();
}
return ret;
}
Related
I've created an app in Android to retrieve restaurants in the local area and return them in list view. I've created individual arrays for each of the details in question (name / address / postcode & hygiene rating). Some of the venues are exempt and the array will return the information as -1, so I want to alter this using a filter, which I think I have done.
This is my Async Task which returns the JSON array.
// lets things run in the background, JSON Array to retrieve the list
class RetrieveNearestRestaurantsTask extends AsyncTask<Void, Void, JSONArray> {
private Exception exception;
// performs the search in the background / populates the arraylist
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
protected JSONArray doInBackground(Void... voids) {
// if the searchUrl conversion is empty
if (!searchUrl.toString().isEmpty()) {
// do this instead
try {
URL url = new URL(searchUrl.toString());
URLConnection tc = url.openConnection();
InputStreamReader isr = new InputStreamReader(tc.getInputStream());
BufferedReader in = new BufferedReader(isr);
String line; // variable
// while line in (read in) is not equal to null
// create a new object and output as line in JSON
while ((line = in.readLine()) != null) {
ja = new JSONArray(line);
// run through the length of the array
for (int i = 0; i < ja.length(); i++) {
JSONObject JO = (JSONObject) ja.get(i);
// output to meet Basic Functionality requirement
businessNames.add(JO.getString("BusinessName"));
postCodes.add(JO.getString("PostCode"));
addressList1.add(JO.getString("AddressLine1"));
addressList2.add(JO.getString("AddressLine2"));
addressList3.add(JO.getString("AddressLine3"));
// if the rating of the restaurant is -1, exempt
// should be displayed
ratingValue.add(JO.getString("RatingValue"));
ratingValue.stream()
.filter(x -> x.equals("-1"))
.findFirst()
.ifPresent(v -> System.out.println("Exempt"));
calcDistance.add(JO.getString("DistanceKM"));
// output everything together
ConcatenateSearchResults();
}
}
isr.close();
in.close();
//return ja;
} catch (Exception e) {
this.exception = e;
return ja;
} finally {
//is.close();
}
}
return ja;
}
Loads the search results.
protected void onPostExecute(JSONArray jsonArray) {
LoadSearchResults();
}
}
Concatenates the search results
private ArrayList<String> ConcatenateSearchResults()
{
int length = businessNames.size();
ArrayList<String> concatenatedResults = new ArrayList<>();
if(!businessNames.isEmpty() && !calcDistance.isEmpty() && !ratingValue.isEmpty()
&& !addressList1.isEmpty() && !addressList2.isEmpty() && !addressList3.isEmpty()
&& !postCodes.isEmpty())
{
for(int i=0; i < length; i++)
{
concatenatedResults.add("\n"+businessNames.get(i) +
"\nDistance (in Km) :"+ calcDistance.get(i) +
"\n\nRating: "+ ratingValue.get(i) +
"\nAddress Line 1: "+ addressList1.get(i) +
"\nAddress Line 2: "+ addressList2.get(i)+
"\nAddress Line 3: "+ addressList3.get(i) +
"\nPostcode: "+ postCodes.get(i));
}
}
return concatenatedResults;
}
}
However, I think somewhere I haven't enabled the proper ratingValue variable (?) to return the correct information (exempt instead of -1, where applicable, but I haven't worked out what I might have done wrong. Thank you for any help, I am slooowly getting better at explaining what I don't know.
I am writing a client that can reserve slots, view available slots, view slots you've booked and cancel reserved slots. My code for works for everything but reserving slots.
The below is code for reserving a slot.
while(hotelBooked == false && bandBooked == false)
{
// This works
xmlString = XMLRequest.availability(requestID, USERNAME, PASSWORD);
ArrayList<String> availSlots = checkAvailiabilityOrBookings(xmlString);
for(int i = 0; i < availSlots.size(); i++)
{
TimeUnit.SECONDS.sleep(1);
System.out.println("availSlots.get(" + i + "): " + Integer.parseInt(availSlots.get(i).trim()));
// generate a unique ID based off time
requestID = genRequestID();
System.out.println("REQUESTID" + requestID);
//Something goes wrong around here
xmlString = XMLRequest.Reservation(requestID, USERNAME, PASSWORD, 134);
// breaks in this method
hotelBooked = reserveSlot(xmlString, hotelNum);
if(hotelBooked == true)
{
bandBooked = reserveSlot(xmlString, bandNum);
if(bandBooked == false)
{
requestID = genRequestID();
System.out.println("REQUESTID " + requestID);
xmlString = XMLRequest.cancel(requestID, USERNAME, PASSWORD, Integer.parseInt(availSlots.get(i).trim()));
cancelSlot(xmlString, hotelNum);
}// if
else
{
requestID = genRequestID();
System.out.println("REQUESTID" + requestID);
xmlString = XMLRequest.bookings(requestID, USERNAME, PASSWORD);
bookedSlots = checkAvailiabilityOrBookings(xmlString);
System.out.println("1st time - Booked slots:");
System.out.println(bookedSlots.toString());
break;
}
}// if
The below is the method it breaks in
// reserve a slot
public static Boolean reserveSlot(String xmlString, String hotelOrBand) {
System.out.println("Entered reserveSlot");
Response recMsgOutput;
PutMethod putMethod;
boolean booked = false;
try {
if(hotelOrBand.equals(String.valueOf(3010)))
{
putMethod = putMethodHotel;
}
else
{
putMethod = putMethodBand;
}
/*
* Set the request's entity (body).
*/
System.out.println("Set the request's entity (body)");
RequestEntity entity = new StringRequestEntity(xmlString);
putMethod.setRequestEntity(entity);
/*
* Set the put method's headers
*/
System.out.println("Set the put method's headers");
putMethod.addRequestHeader("Content-Type", "application/xml");
putMethod.addRequestHeader("Accept", "application/xml");
/*
* Create a client and the execute the put method.
*/
System.out.println("Create a client and the execute the put method.");
HttpClient client = new HttpClient();
int responseCode = client.executeMethod(putMethod);
while(responseCode != HttpStatus.SC_OK){
client = new HttpClient();
responseCode = client.executeMethod(putMethod);
TimeUnit.SECONDS.sleep(1);
}// while
if (responseCode == HttpStatus.SC_OK) {
System.out.println("Message uri: " + Response.getMsgURI(putMethod.getResponseBodyAsString()));
String [] message = Response.getMsgURI(putMethod.getResponseBodyAsString()).split("/");
String msgNum = message[message.length - 1];
String recMsgArg = "http://jewel.cs.man.ac.uk:" + hotelOrBand + "/queue/msg/" + msgNum + "?username=0ih058&password=4UhMf9";
System.out.println("recMsgArg " + recMsgArg);
String [] recMsgArgArray = new String[1];
// Send requests to ClientRecMsg
recMsgArgArray[0] = recMsgArg;
System.out.println("recMsgArgArray " + recMsgArgArray[0]);
recMsgOutput = ClientRecMsg.main(recMsgArgArray);
Matcher matcher1 = Pattern.compile("\\d+").matcher(recMsgOutput.toString());
matcher1.find();
int responseNum = Integer.valueOf(matcher1.group());
System.out.println("num: " + responseNum);
if(responseNum == 200)
booked = true;
} else if(responseCode != HttpStatus.SC_OK) {
System.out.println("Error code:" + responseCode);
System.out.println("Error message:" + putMethod.getResponseBodyAsString());
}
}//try
Outputs this
availSlots.get(4): 135
REQUESTID 1584934385
Entered reserveSlot
Set the request's entity (body)
Set the put method's headers
Create a client and the execute the put method.
[Fatal Error] :1:1: Content is not allowed in prolog.
uk.ac.manchester.cs.comp28112.lab2.ParseException
at uk.ac.manchester.cs.comp28112.lab2.Response.getMsgURI(Response.java:179)
at uk.ac.manchester.cs.comp28112.lab2.ClientReserve.reserveSlot(ClientReserve.java:527)
at uk.ac.manchester.cs.comp28112.lab2.ClientReserve.reserveRequest(ClientReserve.java:164)
at uk.ac.manchester.cs.comp28112.lab2.ClientReserve.main(ClientReserve.java:77)
The XML for reservation is the code below
static public String Reservation(String request_id, String username,
String password, int slot_id) throws RequestException {
try {
XMLRequest.createBuilder();
Document document = documentBuilder.newDocument();
Element reserve_element = document.createElement(RESERVE_ELEMENT);
document.appendChild(reserve_element);
Node id_element = document.createElement(REQUEST_ID_ELEMENT);
id_element.appendChild(document.createTextNode(request_id));
reserve_element.appendChild(id_element);
Node username_element = document.createElement(USERNAME_ELEMENT);
username_element.appendChild(document.createTextNode(username));
reserve_element.appendChild(username_element);
Node password_element = document.createElement(PASSWORD_ELEMENT);
password_element.appendChild(document.createTextNode(password));
reserve_element.appendChild(password_element);
Node slot_id_element = document.createElement(SLOT_ID_ELEMENT);
slot_id_element.appendChild(document.createTextNode(new Integer(
slot_id).toString()));
reserve_element.appendChild(slot_id_element);
return XMLRequest.toString(document);
} catch (ParserConfigurationException e) {
throw new RequestException(e);
} catch (TransformerConfigurationException e) {
throw new RequestException(e);
} catch (TransformerFactoryConfigurationError e) {
throw new RequestException(e.getException());
} catch (TransformerException e) {
throw new RequestException(e);
}
Below is the method for Response.getMsgURI()
static public String getMsgURI(String xmlString) throws ParseException {
try {
Response.createBuilder();
InputSource source = new InputSource(new StringReader(xmlString));
Node node = (Node) msgIdXPathExpression.evaluate(source, XPathConstants.NODE);
return node.getTextContent();
} catch (XPathExpressionException e) {
throw new ParseException();
} catch (ParserConfigurationException e) {
throw new ParseException();
}
}
Below is the output for putMethod.getResponseBodyAsString()
Status: 500 Internal Server Error
Content-Type: text/html
<html><body><h1>500 Internal Server Error</h1></body></html>
I've think it's something to do with making multiple xml requests in the same method because when I make the reservation request first it runs fine but when I try to make another xml request immediately after that gets stuck as well.
Sorry for including so much code, help would be much appreciated thanks.
The problem was that I was trying to reuse putMethod objects, I needed to create a new one everytime I made a request. I don't know why this is though.
I am trying to log weather data for a university hydrological project using java.
The data is formated as a json file in 5 minute intervals for the last 24 hours in the following way (example):
{
"1482439800":{
"hu":92,
"te":-2.9,
"dp":-4.5,
"pr":1028.4,
"pa":null,
"ws":1.4,
"wd":180
},
"1482440100":{
"hu":92,
"te":-2.9,
"dp":-4.5,
"pr":1028.4,
"pa":null,
"ws":1.4,
"wd":180
}
}
I have already tried to use the following code to access data from the json file:
private static String readUrl(String urlString) throws Exception {
BufferedReader reader = null;
try {
URL url = new URL(urlString);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
return buffer.toString();
} finally {
if (reader != null)
reader.close();
}
}
public static Object[][] getstation1(){
Object[][] data = null;
try {
JSONObject json = new JSONObject(readUrl("http://netzwerk.wetter.com/api/stationdata/14091/24/"));
Iterator keys = json.keys();
while (keys.hasNext()) {
Object key = keys.next();
JSONObject value = json.getJSONObject((String) key);
double hu = value.getDouble("hu");
System.out.println(hu);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return data;
}
This was somewhat successful as it returned data for humidity (hu) but in a seemingly random order.
Now for my question: How do I read the times and return them alongside the corresponding weather data from newest to oldest inside the Object[][]?
Any help is appreciated.
Thank you.
A sorted map would be more appropriate than an Object[][].
Quickly:
TreeMap<String, Object> sorted = new TreeMap<>(json.toMap());
But that will sort alphanumerically (probably fine in your case as the timestamps are all the same length).
You could do a little more work to sort the results into a typed map:
TreeMap<Date, Map<String, Double>> byDate = json.toMap().entrySet().stream()
.collect(Collectors.toMap(
e -> new Date(Long.valueOf(e.getKey()) * 1000),
e -> (Map) e.getValue(),
(a, b) -> {throw new IllegalArgumentException("Duplicate key " + a);},
TreeMap::new
));
If you really need an Object[][] you can remap your data once it's sorted:
Object[][] data = sorted.entrySet().stream().map(e -> new Object[] {e.getKey(), e.getValue()}).toArray(Object[][]::new);
Or consider using an object mapper like jackson or gson.
Thanks for the answer but in the end I decided to go a slightly simpler route.
I retrieved all the key names, sorted them and then read the corresponding data key by key. And as I was getting frequent errors because of data being null I added protection for that as well (I need them as actual numbers).
public static Object[][] getstation1(){
Object[][] data = null;
try {
JSONObject json = new JSONObject(readUrl("http://netzwerk.wetter.com/api/stationdata/14091/2/"));
System.out.println("Fetching "+"http://netzwerk.wetter.com/api/stationdata/14091/2/");
String[] times = json.getNames(json);
Arrays.sort(times);
data = new Object[times.length][8];
for (int i = 0; i < times.length; i++){
Date temp = new Date((long)Integer.parseInt(times[i])*1000);
data[i][0] = temp;
if (json.getJSONObject(times[i]).isNull("hu")){
data[i][1] = 0;
} else {
data[i][1] = json.getJSONObject(times[i]).getDouble("hu");
}
if (json.getJSONObject(times[i]).isNull("te")){
data[i][2] = 0;
} else {
data[i][2] = json.getJSONObject(times[i]).getDouble("te");
}
if (json.getJSONObject(times[i]).isNull("dp")){
data[i][3] = 0;
} else {
data[i][3] = json.getJSONObject(times[i]).getDouble("dp");
}
if (json.getJSONObject(times[i]).isNull("pr")){
data[i][4] = 0;
} else {
data[i][4] = json.getJSONObject(times[i]).getDouble("pr");
}
if (json.getJSONObject(times[i]).isNull("pa")){
data[i][5] = 0;
} else {
data[i][5] = json.getJSONObject(times[i]).getDouble("pa");
}
if (json.getJSONObject(times[i]).isNull("ws")){
data[i][6] = 0;
} else {
data[i][6] = json.getJSONObject(times[i]).getDouble("ws");
}
if (json.getJSONObject(times[i]).isNull("wd")){
data[i][7] = 0;
} else {
data[i][7] = json.getJSONObject(times[i]).getDouble("wd");
}
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return data;
}
I got the error when to parse the JSON. Error parsing data org.json.JSONException: End of input at character 0 of.
error log:
04-19 20:51:00.635: E/ViewRootImpl(24857): sendUserActionEvent() mView == null
04-19 20:51:00.635: E/ViewRootImpl(24857): sendUserActionEvent() mView == null
04-19 20:51:03.320: E/ViewRootImpl(24857): sendUserActionEvent() mView == null
04-19 20:51:10.215: E/JSON Parser(24857): Error parsing data org.json.JSONException: End of input at character 0 of
04-19 20:51:35.600: E/ViewRootImpl(24857): sendUserActionEvent() mView == null
This is the code for calling a function in UserFunction class:
pTotalPrice=new double[cartSize]; // store array of totalprice
/** To be sent to DB **/
sPID = new String[cartSize];
sProduct = new String[cartSize];
sQuantity = new String[cartSize];
sTotalPrice = new String[cartSize];
if(cartSize >0)
{
for(int i=0;i<cartSize;i++)
{
final int counter = i;
// Get probuct data from product data arraylist
String pID = aController.getProducts(i).getProductId();
sPID[i] = pID;
String pName = aController.getProducts(i).getProductName();
sProduct[i] = pName;
double pPrice = aController.getProducts(i).getProductPrice();
int pQuantity = aController.getProducts(i).getProductQuantity();
sQuantity[i] = Integer.toString(pQuantity);
pTotalPrice[i] = pPrice * pQuantity;
sTotalPrice[i] = Double.toString(pTotalPrice[i]);
}
pFinalPrice -= pTotalPrice[counter];
sFinalPrice = Double.toString(pFinalPrice);
}
protected JSONObject doInBackground(String... args) {
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.orderDetails(username, sPID, sProduct, sQuantity, sTotalPrice, Double.toString(pFinalPrice));
Log.d("Button", "Order");
return json;
}
The function in UserFunction class
/**
* Function store order details
**/
public JSONObject orderDetails(String username, String[] pid, String[] products, String[] quantity, String[] totalprice, String finalprice) {
// Building Parameters
List params = new ArrayList();
params.add(new BasicNameValuePair("tag", order_tag));
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("finalpice", finalprice));
for (int i = 0; i < pid.length; i++) {
params.add(new BasicNameValuePair("pid[i]", pid[i]));
}
for (int j = 0; j < products.length; j++) {
params.add(new BasicNameValuePair("products[j]", products[j]));
}
for (int k = 0; k < quantity.length; k++) {
params.add(new BasicNameValuePair("quantity[k]", quantity[k]));
}
for (int l = 0; l < totalprice.length; l++) {
params.add(new BasicNameValuePair("totalprice[l]", totalprice[l]));
}
JSONObject json = jsonParser.getJSONFromUrl(orderURL,params);
return json;
}
The java parser class:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
This is my index.php api
else if ($tag == 'order') {
$username = $_POST['username'];
$finalprice = $_POST['finalprice'];
$pid = $_POST['pid'];
$quantity = $_POST['quantity'];
$totalprice = $_POST['totalprice'];
$response["successfullypost"] = 1;
$response["user"]["username"] = $username;
$response["user"]["finalprice"] = $finalprice;
$response["user"]["pid"] = $pid;
$response["user"]["quantity"] = $quantity;
$response["user"]["totalprice"] = $totalprice;
echo json_encode($response);
$uResult = mysql_query("SELECT * FROM users WHERE username = $username");
$uid = $uResult['uid'];
$counter = sizeof($pid);
for ( $i=0; $i < $counter; $i++) {
$db-> orderdetails($uid, $pid[$i], $quantity[$i], $totalprice[$i], $finalprice);
}
}
else {
$response["error"] = 3;
$response["error_msg"] = "JSON ERROR";
echo json_encode($response);
}
index.php call this orderdetails function
public function orderdetails ($uid, $pid, $quantity, $totalprice, $finalprice) {
$pResult = mysql_query("SELECT * FROM products WHERE pid = $pid");
$Product_ID = $pResult['ProductID'];
$final = mysql_query("INSERT INTO vieworders (uid, ProductID, quantity, $totalprice, finalprice)
VALUES ('$uid', '$ProductID', '$quantity', '$totalprice', '$finalprice')");
}
The new JSON Response. although I have to products it don't show the array. why the JSON tag show 'i' instead of pid[i]? same for quantity and totalprice
04-20 10:19:31.615: E/ViewRootImpl(20740): sendUserActionEvent() mView == null
04-20 10:19:44.505: E/JSON(20740): {"tag":"order","success":0,"error":0,"successfullypost":1,"user":{"username":"zulanawi","finalprice":null,"pid":{"i":"0002"},"quantity":{"k":"3"},"totlaprice":{"l":"32.400000000000006"}}}{"success":0}
DONE!!! After referring to Passing String array to PHP as POST I got the answer.
/**
* Function store order details
**/
public JSONObject orderDetails(String username, String[] pid, String[] products, String[] quantity, String[] totalprice, String finalprice) {
// Building Parameters
List params = new ArrayList();
params.add(new BasicNameValuePair("tag", order_tag));
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("finalpice", finalprice));
for (int i = 0; i < pid.length; i++) {
params.add(new BasicNameValuePair("pid[]", pid[i]));
}
for (int j = 0; j < products.length; j++) {
params.add(new BasicNameValuePair("products[]", products[j]));
}
for (int k = 0; k < quantity.length; k++) {
params.add(new BasicNameValuePair("quantity[]", quantity[k]));
}
for (int l = 0; l < totalprice.length; l++) {
params.add(new BasicNameValuePair("totalprice[]", totalprice[l]));
}
JSONObject json = jsonParser.getJSONFromUrl(orderURL,params);
return json;
}
I'm trying to parse the json data that I get back from lastfm.
The method I'm interested in is album.search
The documentation requires there to be a search term for the album name, and an api key, which I've done here:
String api_key = "x";
String url = "http://ws.audioscrobbler.com/2.0/?method=album.search" +
"&album="
+ query
+ "&apikey="
+ api_key
+ "&format=json";
Then my issue was trying to iterate through the json data so I can get to the value that I wanted, in my case, name, so I made an array to loop through the json file.
boolean error = false;
HttpClient httpclient = null;
try {
httpclient = new DefaultHttpClient();
HttpResponse data = httpclient.execute(new HttpGet(url));
HttpEntity entity = data.getEntity();
String result = EntityUtils.toString(entity, "UTF8");
for ( int i = 0; i < results.length(); i++) {
JSONObject row = new JSONObject(result);
albummatches = row.getString("albummatches");
album = row.getString("album");
name = row.getString("name");
results.getJSONObject(i).get("album");
I have this method which returns results.
public JSONArray getResults() {
return results;
}
Now in my other class, I'm trying to attach the name of the album to my adapter list view through this method.
public void ServiceComplete(AbstractService service) {
if (!service.hasError()) {
AlbumSearchService albumService = (AlbumSearchService)service;
String[] result = new String[albumService.getResults().length()];
for (int i = 0; i < albumService.getResults().length(); i++) {
try{
result[i] = albumService.getResults().getJSONObject(i).getString("name");
} catch (JSONException ex) {
result[i] = "Error";
}
}
setListAdapter(new ArrayAdapter<String>(this, R.layout.album_list_cell, R.id.text, result));
}
But unfortunately, when I try to run the app, and search for an album, it just stays stuck on 'searching...', and doesn't display any results in my list view.
I don't know where I'm going wrong :( Help someone!