Cannot retrieve data from MySQL table which matches specific "uid" - java

I am trying to learn more about MySQL and using Java (on Android) to access and retrieve information from a database on my WAMS server. The way my app is setup is that it has an initial login screen which also grabs the "uid" of the username that's logging in (from a different table) and stores it.
Upon login (which is functional - I setup a toast notification that displays the retrieved username and uid of the user logging in), it goes to a new screen (dashboard.xml) which has a TextView field setup to display the retrieved data (from table posted below) associated with the stored "uid". Here is the table I am trying to pull data from:
http://db.tt/4izVQuGB
Now, I have setup a PHP file that queries my db for rows that are associated with a specific "uid". I have tested this file using an HTML form.
$connect = mysql_connect($dbhost, $dbuser, $dbpass) or die("connection error");
mysql_select_db($dbdb)or die("database selection error");
//Retrieve the User ID
$uid = $_POST['uid'];
//Query
$query = mysql_query("SELECT * FROM node WHERE uid='$uid' AND type='goal'");
//store # of rows returned
$num_rows = mysql_num_rows($query);
if ($num_rows >= 1) {
while($results=mysql_fetch_assoc($query)) {
//Store the returned data into a variable
$output = $results;
//encode the returned data in JSON format
echo json_encode($output);
}
mysql_close();
}
The result I get by testing the PHP file using uid value of 1 is:
{"nid":"1","vid":"1","type":"goal","language":"","title":"test","uid":"1","status":"1","created":"1342894493","changed":"1342894493","comment":"2","promote":"1","moderate":"0","sticky":"1","tnid":"0","translate":"0"}
{"nid":"2","vid":"2","type":"goal","language":"","title":"test2","uid":"1","status":"1","created":"1342894529","changed":"1342894529","comment":"2","promote":"1","moderate":"0","sticky":"1","tnid":"0","translate":"0"}
{"nid":"5","vid":"5","type":"goal","language":"","title":"run","uid":"1","status":"1","created":"1343506987","changed":"1343506987","comment":"2","promote":"1","moderate":"0","sticky":"1","tnid":"0","translate":"0"}
{"nid":"9","vid":"9","type":"goal","language":"","title":"run to the
hills","uid":"1","status":"1","created":"1343604338","changed":"1343605100","comment":"2","promote":"0","moderate":"0","sticky":"0","tnid":"0","translate":"0"}
Now, I have written some android code which sets up httppost and is supposed to retrieve the "titles" in my database table. I know it is wrong (obviously since it doesn't work) but I am confused as to what to do next.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
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.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Dashboard extends Activity implements OnClickListener {
// variable declarations
String uid = "1";
// create textview to display retrieved data
TextView display;
HttpClient httpclient;
HttpPost httppost;
HttpResponse httpresponse;
HttpEntity httpentity;
ArrayList<NameValuePair> resultArray;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dashboard);
display = (TextView) findViewById(R.id.test);
// initialize HttpClient
httpclient = new DefaultHttpClient();
// initialize HttpPost
httppost = new HttpPost("http://192.168.1.112/android/fetch.php");
try {
// Create new List
List<NameValuePair> resultList = new ArrayList<NameValuePair>();
resultList.add(new BasicNameValuePair("uid", uid));
httppost.setEntity(new UrlEncodedFormEntity(resultList));
httpresponse = httpclient.execute(httppost);
httpentity = httpresponse.getEntity();
InputStream instream = entity.getContent();
try {
// store incoming stream in an array
JSONArray jArray = new JSONArray(streamToString(instream));
JSONObject jData = null;
for (int i = 0; i < jArray.length(); i++) {
jData = jArray.getJSONObject(i);
String goals = jData.getString("title");
display.setText(goals);
}
//} catch (JSONException e) {
//Toast.makeText(this, "No entries found", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, e.toString(), Toast.LENGTH_LONG)
.show();
}
} catch (Exception e) {
e.printStackTrace();
Notifications error = new Notifications();
error.userPassErrorDialog();
}
}
private static String streamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
I get the following error when testing it in the Android emulator:
http://db.tt/2vg9MqYh
Any help or suggestions will be greatly appreciated.

In your Android app, you expect a JSONArray:
// store incoming stream in an array
JSONArray jArray = new JSONArray(streamToString(instream));
However, in your PHP file you only output multiple separate JSON objects instead of a real array. I think, you should collect all items from the database in an PHP array first and then encode and output it only once.
My PHP skills are a bit rusted, but I hope this one will work:
//store # of rows returned
$num_rows = mysql_num_rows($query);
if ($num_rows >= 1) {
$output = array();
while($results = mysql_fetch_assoc($query)) {
// append row to output
$output[] = results
}
mysql_close(); // shouldn't that be outside the if block?
//encode the returned data in JSON format
echo json_encode($output);
}
I would expect the output then to be like this (maybe without indentation):
[
{"nid":"1","vid":"1","type":"goal","language":"","title":"test","uid":"1","status":"1","created":"1342894493","changed":"1342894493","comment":"2","promote":"1","moderate":"0","sticky":"1","tnid":"0","translate":"0"},
{"nid":"2","vid":"2","type":"goal","language":"","title":"test2","uid":"1","status":"1","created":"1342894529","changed":"1342894529","comment":"2","promote":"1","moderate":"0","sticky":"1","tnid":"0","translate":"0"},
{"nid":"5","vid":"5","type":"goal","language":"","title":"run","uid":"1","status":"1","created":"1343506987","changed":"1343506987","comment":"2","promote":"1","moderate":"0","sticky":"1","tnid":"0","translate":"0"},
{"nid":"9","vid":"9","type":"goal","language":"","title":"run to the hills","uid":"1","status":"1","created":"1343604338","changed":"1343605100","comment":"2","promote":"0","moderate":"0","sticky":"0","tnid":"0","translate":"0"}
]

The problem lies in encoding and decoding of JSON. from your JSON response it looks like you are receiving JSON object from server also please try to validate you JSON response here. run your php file in browser, copy the entire response on the JSON validator and check the brackets that you are receiving the response in.
1. If your response starts with '[' it is and array and if it starts with '{' it is a JSON Object. while parsing JSON you have defined JSON array first but the server response is JSON object. While using JSON you have to be careful on server side for the format of response it will send and you have to be careful on the client side for the format of response you receive. I am posting example script for you.
-> Server side
if (mysql_num_rows($result)>0){
$response["data"] = array(); //this is an array
while($row= mysql_fetch_array($result))
{
$data = array(); //here I have created another temp array
$data["name"] = $row["name"];
$data["surname"] = $row["surname"];
array_push($response["data"], $data); //this makes an array of objects in the response
}}
}//endif
else{
echo "no input";
}}
mysql_close();
echo json_encode($response); //and finally I echo it as an JSON object
As this php script will return me one object of array of objects ( bit complex isn't it!!) below is the format of response
-> validated JSON response
{
"data": [
{
"name": "Setu",
"surname": "Desai",
}
]
}
and to decode this my client site script need to be the following
-> parsing JSON object
JSONObject snObject = new JSONObject(jsonString);
JSONArray snArray = snObject.getJSONArray("data");
for (int i = 0; i < snArray.length(); i++) {
JSONObject snObject2 = snArray.getJSONObject(i);
String surname = snObject2.getString("surname");
surnamearray.add(surname);
}
the simple way to understand is to validate you JSON response and identify the position of JSON array and objects and then start decoding.

Related

Carrying and reusing information (json string) from an AsyncTask?

I have created a simple android app with 3 TextViews and then run an AsyncTask Task via a different class the next step would be to carry the information over and make the task reusable.
The Task will consume a String (URL) and the context of the MainActivity.
The Task will make a simple REST Request (GET) and retrieve a json string.
I have then created another class that which gets the json response and creates a .json file saves it to
..../0/Notes/launch.json
The folder "Notes is created by myself via file.mkdirs().
In the MainActivity I created an InputStream to read the .json file saved by the AsyncTask but once I try to open it, it gives me a FileNotFoundException.
Here's the code of my MainActivity.class
package com.example.root.example;
import android.Manifest;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 200);
String url = "https://api.spacexdata.com/v3/launches/upcoming"; //Copy the url and open it in your browser to see the json.
AsyncCall asyncCall = new AsyncCall(getApplicationContext());
asyncCall.myAsyncTask(url);
try {
InputStream inputStream = this.getAssets().open("launch.json");
int size = inputStream.available();
byte[] buffer = new byte[size];
inputStream.read(buffer);
inputStream.close();
String jsonStringFromFile= new String(buffer,"UTF-8");
JSONObject launchObject = new JSONObject(jsonStringFromFile);
System.out.println(launchObject.get("flight_number"));
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
This is the AsyncCall.class (making and retrieving the json etc..)
package com.example.root.example;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class AsyncCall {
FileCreator fileCreator = new FileCreator();
private final Context myContext;
public AsyncCall(final Context context) {
myContext = context;
}
public void myAsyncTask(final String url) {
AsyncTask asyncTask = new AsyncTask() {
#Override
protected Object doInBackground(Object[] objects) {
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
Response response = null;
try {
response = okHttpClient.newCall(request).execute();
fileCreator.generateFile(myContext, myContext.getString(R.string.fileName), response.body().string());
} catch (IOException ioe) {
ioe.getMessage();
}
return null;
}
}.execute();
}
}
what am I trying to archive? I'm trying to save information (json here) and make it reusable just as the Falcon 9.
The issue lies in carrying information over to a different class.
If there's an alternative solution (other than saving a .json file) to fix this issue then please don't hesitate to post it.
This is just my first issue, the second issue appears once you open the api link and see that there are a few more than just one JSON String (0,1,2,3,4... upcoming missions).
I have no clue in any way to tacle the first let alone the second problem and have started over a few times, a while ago multiple times.
Within your Activity, you can get the JSON like so
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
okHttpClient.newCall(request).enqueue(new Callback() {
#Override
public void onResponse(Call call, final Response response) throws IOException {
try {
final String responseData = response.body().string();
JSONObject json = new JSONObject(responseData);
String flightNumber = json.getString("flight_number");
// TODO: Load number into a TextView
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Looking at your API response, though, you'll actually need new JSONArray(responseData), and you would have to loop over that to get each individual object's flight number

add JSONArray within a JSONObject

I'm making an application to send notifications using OneSignal and must do a POST request in JSON format.
To send notification to a user I have to use the include_player_ids argument which have to be an array because it is possible to send to multiple users the same notification (in my case I only send notification to one user).
I use a JSONArray to create this array but when adding it to the JSONObject, there are extra quotes for the field include_player_ids.
What I have:
{
"headings": {"en":"my_title"},
"contents": {"en":"my_text"},
"include_player_ids": "[\"my-player-id\"]",
"app_id":"my-app-id"
}
As you can see, there is some quote around the array [ ].
I guess it's what is making the response error from OneSignal :
errors":["include_player_ids must be an array"]
What I want :
...
"include_player_ids": ["my-player-id"]
...
It is weird because adding JSONObject to JSONObject doesn't do this even though it is quite similar as you can see with the headings / contents fields
My code :
import org.json.JSONException;
import org.json.JSONObject;
import org.json.alt.JSONArray;
JSONObject headings = new JSONObject();
JSONObject contents = new JSONObject();
JSONArray player_id = new JSONArray();
JSONObject notification = new JSONObject();
try {
notification.put("app_id", appId);
notification.put("include_player_ids", player_id);
player_id.put(idUser);
headings.put("en", "my_title");
contents.put("en", "my_text");
notification.put("headings", headings);
notification.put("contents", contents);
} catch (JSONException e) {
System.out.println("JSONException :" + e.getMessage());
}
idUser is a String
Thanks in advance for any help,
I believe the problem is that you're using org.json.alt.JSONArray instead of org.json.JSONArray. I'm not familiar with that class, but I suspect JSONObject.put is just calling toString() on it rather than treating it as an existing JSON array. Here's a short but complete example that doesn't have the problem:
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray; // Note the import here
public class Test {
public static void main(String[] args) throws JSONException {
JSONArray playerIds = new JSONArray();
playerIds.put("a");
playerIds.put("b");
JSONObject notification = new JSONObject();
notification.put("include_player_ids", playerIds);
System.out.println(notification);
}
}
Output:
{"include_player_ids":["a","b"]}

Create Page In Confluence Via Rest API using Java

Does anyone have any examples on how to create a page/wiki entry in Confluence using Confluence's RESTful API? I'm trying to write something in Java that can do this.
Thank you in advance...
Thank you, I already checked the documentation online but I couldn't find any examples THAT USE JAVA in the Confluence REST API. That's why I posted on here.
Regardless, I think I figured it out:
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
/**
* Creates a Confluence wiki page via the RESTul API
* using an HTTP Post command.
*/
public class ConfluenceRestApi2CreateEntry {
//private static final String BASE_URL = "http://localhost:1990/confluence";
private static final String BASE_URL = "https://<context>.atlassian.net/wiki";
private static final String USERNAME = "username";
private static final String PASSWORD = "password";
private static final String ENCODING = "utf-8";
public static String createContentRestUrl()throws UnsupportedEncodingException
{
return String.format("%s/rest/api/content/?&os_authType=basic&os_username=%s&os_password=%s", BASE_URL, URLEncoder.encode(USERNAME, ENCODING), URLEncoder.encode(PASSWORD, ENCODING));
}
public static void main(final String[] args) throws Exception
{
String wikiPageTitle = "My Awesome Page";
String wikiPage = "<h1>Things That Are Awesome</h1><ul><li>Birds</li><li>Mammals</li><li>Decapods</li></ul>";
String wikiSpace = "JOUR";
String labelToAdd = "awesome_stuff";
int parentPageId = 9994250;
JSONObject newPage = defineConfluencePage(wikiPageTitle,
wikiPage,
wikiSpace,
labelToAdd,
parentPageId);
createConfluencePageViaPost(newPage);
}
public static void createConfluencePageViaPost(JSONObject newPage) throws Exception
{
HttpClient client = new DefaultHttpClient();
// Send update request
HttpEntity pageEntity = null;
try
{
//2016-12-18 - StirlingCrow: Left off here. Was finally able to get the post command to work
//I can begin testing adding more data to the value stuff (see above)
HttpPost postPageRequest = new HttpPost(createContentRestUrl());
StringEntity entity = new StringEntity(newPage.toString(), ContentType.APPLICATION_JSON);
postPageRequest.setEntity(entity);
HttpResponse postPageResponse = client.execute(postPageRequest);
pageEntity = postPageResponse.getEntity();
System.out.println("Push Page Request returned " + postPageResponse.getStatusLine().toString());
System.out.println("");
System.out.println(IOUtils.toString(pageEntity.getContent()));
}
finally
{
EntityUtils.consume(pageEntity);
}
}
public static JSONObject defineConfluencePage(String pageTitle,
String wikiEntryText,
String pageSpace,
String label,
int parentPageId) throws JSONException
{
//This would be the command in Python (similar to the example
//in the Confluence example:
//
//curl -u <username>:<password> -X POST -H 'Content-Type: application/json' -d'{
// "type":"page",
// "title":"My Awesome Page",
// "ancestors":[{"id":9994246}],
// "space":{"key":"JOUR"},
// "body":
// {"storage":
// {"value":"<h1>Things That Are Awesome</h1><ul><li>Birds</li><li>Mammals</li><li>Decapods</li></ul>",
// "representation":"storage"}
// },
// "metadata":
// {"labels":[
// {"prefix":"global",
// "name":"journal"},
// {"prefix":"global",
// "name":"awesome_stuff"}
// ]
// }
// }'
// http://localhost:8080/confluence/rest/api/content/ | python -mjson.tool
JSONObject newPage = new JSONObject();
// "type":"page",
// "title":"My Awesome Page"
newPage.put("type","page");
newPage.put("title", pageTitle);
// "ancestors":[{"id":9994246}],
JSONObject parentPage = new JSONObject();
parentPage.put("id",parentPageId);
JSONArray parentPageArray = new JSONArray();
parentPageArray.put(parentPage);
newPage.put("ancestors", parentPageArray);
// "space":{"key":"JOUR"},
JSONObject spaceOb = new JSONObject();
spaceOb.put("key",pageSpace);
newPage.put("space", spaceOb);
// "body":
// {"storage":
// {"value":"<p><h1>Things That Are Awesome</h1><ul><li>Birds</li><li>Mammals</li><li>Decapods</li></ul></p>",
// "representation":"storage"}
// },
JSONObject jsonObjects = new JSONObject();
jsonObjects.put("value", wikiEntryText);
jsonObjects.put("representation","storage");
JSONObject storageObject = new JSONObject();
storageObject.put("storage", jsonObjects);
newPage.put("body", storageObject);
//LABELS
// "metadata":
// {"labels":[
// {"prefix":"global",
// "name":"journal"},
// {"prefix":"global",
// "name":"awesome_stuff"}
// ]
// }
JSONObject prefixJsonObject1 = new JSONObject();
prefixJsonObject1.put("prefix","global");
prefixJsonObject1.put("name","journal");
JSONObject prefixJsonObject2 = new JSONObject();
prefixJsonObject2.put("prefix","global");
prefixJsonObject2.put("name",label);
JSONArray prefixArray = new JSONArray();
prefixArray.put(prefixJsonObject1);
prefixArray.put(prefixJsonObject2);
JSONObject labelsObject = new JSONObject();
labelsObject.put("labels", prefixArray);
newPage.put("metadata",labelsObject);
return newPage;
}
}
Here's a project in GitHub that I created that also has an example of simply pulling wiki page entry using Java:
https://github.com/stirlingcrow/Confluence-AccessRestApiWithJava
What about using the official REST client?
https://mvnrepository.com/artifact/com.atlassian.confluence/confluence-rest-client
I'm not able to find any documentation on how to use it, tho.

Parsing JSON data in Java

I want to parse the some data from this page:
http://www.bbc.co.uk/radio1/programmes/schedules/england/2013/03/1.json
The data I want to parse is the titles however I am unsure how I can extract the data. This is what I have done so far:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class Test
{
public Test() { }
public static void main(String[] args)
{
URL url;
HttpURLConnection connection = null;
InputStream is = null;
JSONParser parser = new JSONParser();
try
{
url = new URL("http://www.bbc.co.uk/radio1/programmes/schedules/england/2013/03/1.json");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
is = connection.getInputStream();
BufferedReader theReader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String reply;
while ((reply = theReader.readLine()) != null)
{
System.out.println(reply);
Object obj = parser.parse(reply);
JSONObject jsonObject = (JSONObject) obj;
String title = (String) jsonObject.get("time");
System.out.println(title);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
This just returns null. Can anybody tell me what I need to change? Thanks.
If you read the javadoc of JSONObject#get(String) which is actually HashMap.get(String), it states
Returns: the value to which the specified key is mapped, or null if
this map contains no mapping for the key
Your JSON does not contain a mapping for the key time.
Edit:
If you meant title instead of time, take this extract of the JSON
{"schedule":{"service":{"type":"radio","key":"radio1","title":"BBC Radio 1",...
You need to first get schedule as a JSONObject, then service as a JSONObject, and then title as a normal String value. Apply this differently depending on the type of JSON value.
use something like JSONGen to better understand your data structures, maybe even map your data to the generated objects using google-gson library

sending parameters across applications

Is there a way I can send attributes across applications that may or may not be on the same machine ?
For example :
// IN APPLICATION 1 (APP-1)
request.setAttribute("Truth","Ghazal is the food for the soul of separation");
RequestDispatcher rd = request.getRequestDispatcher("http://IP/App-2/servlet");
rd.forward(request,response);
// IN APPLICATION 2'S (APP-2) SERVLET
String truth = request.getAttribute("Truth").toString();
// NOW USE THIS STRING
Let us suppose that IP on which app-1 is deployed is not the same as the IP on which the app-2 is deployed.
Is there any way I can send parameters like these across applications that are hosted far away from each other ? When I tried I couldn't do this way,but may be there is a way around.
Both the applications use Tomcat.
If you are going to be sharing state between a variable number of machines, then using HTTP as the method to store that state is not very reliable.
"Attributes" are not transmitted over HTTP, they are merely shared state that reside on the application for the given session. Attributes are 100% purely server-side information.
From the Javadocs:
"It is warned that when the request is dispatched from the servlet
resides in a different web application by RequestDispatcher, the
object set by this method may not be correctly retrieved in the caller
servlet."
you can create a base package to be used through the application
package base;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class GetXMLTask
{
static double longitute;
static double latitude;
public ArrayList<JSONObject> getOutputFromUrl1(String url)
{
ArrayList<JSONObject> output = new ArrayList<JSONObject>();
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse response;
StringBuilder builder= new StringBuilder();
JSONObject myjson ;
JSONArray the_json_array;
try
{
response = httpClient.execute(httpPost);
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
char[] buf = new char[8000];
int l = 0;
while (l >= 0)
{
builder.append(buf, 0, l);
l = in.read(buf);
}
myjson = new JSONObject("{child:"+builder.toString()+"}");
JSONObject mmm = new JSONObject(builder.toString());
JSONArray mmmArr = mmm.getJSONArray("status");
the_json_array = myjson.getJSONArray("child");
for (int i = 0; i < the_json_array.length(); i++)
{
JSONObject another_json_object = the_json_array.getJSONObject(i);
output.add(another_json_object);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return output;
}
}
now from your application call this method by
ArrayList<JSONObject> obj = new GetXMLTask().getOutputFromUrl1("url for the other application method which responds");

Categories