I'm using Eclipse, for an application where I have to read a JSON file from an URL.
The code I'm using is this one:
http://collegewires.com/android/2012/06/json-parsing-in-android/
Ok, the CLASS which I'm using for reading JSON files is called Parser.java:
package com.cw.json;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
public class Parser {
static InputStream is = null;
static JSONObject jsonObject = null;
static String json = "";
// class constructor
public Parser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException exception) {
exception.printStackTrace();
} catch (ClientProtocolException exception) {
exception.printStackTrace();
} catch (IOException exception) {
exception.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sBuilder.append(line + "\n");
}
is.close();
json = sBuilder.toString();
} catch (Exception exception) {
exception.printStackTrace();
}
// Parsing the string to a JSON object
try {
jsonObject = new JSONObject(json);
} catch (JSONException exception) {
exception.printStackTrace();
}
// JSON String
return jsonObject;
}
}
I was using this code for reading a JSON file which is directly an ARRAY, but the code gives me an error.
My question is: is it possible to read an Array instead always reading an Object??
maybe using another class?
Try to modify your Parser.java to this, so you gat a Array not a Object. And please buy you a JAVA Book for beginners, so you do learn how to speak JAVA
public JSONArray getJSONFromUrl(String url) {
....
static JSONArray jsonArray = null;
....
// Parsing the string to a JSON Array
try {
jsonArray = new JSONArray(json);
} catch (JSONException exception) {
exception.printStackTrace();
}
return jsonArray;
}
Related
i'm trying to make android food order for my thesis and because this error i'm running out of time :(
error on logcat :
Error parsing dataorg.json.JSONException: Value cannot be converted to JSONObject
org.json.JSONException: Value to JSONObject
here's my JSONParser :
package com.makanan.restotradisional;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {
}
// fungsi abil json url lewat method HTTP POST atau GET
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
try {
if (method == "POST") {
// jika request method adalah POST
// 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();
} else if (method == "GET") {
// jika request method adalah GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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();
} catch (Exception e) {
Log.e("Buffer Error", "Error Converting result" + e.toString());
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data" + e.toString());
e.printStackTrace();
}
return jObj;
}
}
this my PHP & Java : http://www.4shared.com/rar/1lGplX19ba/Java_and_PHP.html
and this is my database on phpmyadmin :http://www.4shared.com/rar/y_UMtL7_ce/rumah_makan.html
please help me
Remove any of the <br> statements or echo statements from your php file except the one that you are using to pass json..
Check the output of your file in browser, remove all the unwanted things other than json..
Please print and check if your string json is in right format as expected by the JSONObject constructor. Per documentation, valid json string to construct JSONObject should be -- A string beginning with { (left brace) and ending with } (right brace).
Please refer this.
Go inside JSONParser and do this so u see in logcat whats comming from php. Probably its a php error.
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
//This line is what u need to add
Log.d("Whats wrong?", json.toString());
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
I am getting java.lang.NullPointerException when I run this. Does anyone know why this is happening and how I can fix it?
Please take a look at my code and let me know if you have any suggestions.
{"begin":[{"id":1,"name":"Andy","size":1}],"open":[{"id":1,"name":"Tom","size":2}]}
Fragment
public class MainFragment extends Fragment {
public MainFragment() {}
//URL to get JSON Array
private String url = "URL...";
//JSON Node Names
private static final String TAG_BEGIN = "begin";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_SIZE = "size";
JSONArray begin = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
new JSONParse().execute();
return rootView;
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(HomeActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array
begin = json.getJSONArray(TAG_BEGIN);
JSONObject c = begin.getJSONObject(0);
// Storing JSON item in a Variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String size = c.getString(TAG_SIZE);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
JSONParser
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
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();
} 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;
}
}
Error:
E/JSON Parserīš Error parsing data org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
FATAL EXCEPTION: main
java.lang.NullPointerException
at
...$MainFragment$JSONParse.onPostExecute(MainActivity.java:399)
at
...$MainFragment$JSONParse.onPostExecute(MainActivity.java:373)
Which is...
begin = json.getJSONArray(TAG_BEGIN);
and...
private class JSONParse extends AsyncTask<String, String, JSONObject> {
EDIT (Answer)
JSONParser
Inside of JSONParser I changed my code to this:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpUriRequest request = new HttpGet(url);
request.setHeader("Accept", "application/json");
HttpResponse response = httpClient.execute(request);
HttpEntity httpEntity = response.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();
} 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;
}
}
Inside of onPostExecute
JSONArray begin = json.getJSONArray(TAG_BEGIN);
for (int i = 0; i < begin(); i++) {
try {
JSONObject b = = begin(i);
String id = b.getString(TAG_ID);
String name = b.getString(TAG_NAME);
String size = b.getString(TAG_SIZE);
} catch (JSONException e) {
e.printStackTrace();
}
}
First make sure your JSONObject is not null. Then slowly transverse line by line based off the type.
JSONArray begin = json.getJSONArray(TAG_BEGIN);
Then possibly do something like this?
for(int n = 0; n < begin.length(); n++)
{
JSONObject object = begin.getJSONObject(n);
// query through the array
String id = object.getString(TAG_ID);
String name = object.getString(TAG_NAME);
String size = object.getString(TAG_SIZE);
//Now do something with the strings
}
Of course you'd do the same thing with the TAG_OPEN. Let me know if this works, I'll gladly help as much as possible.
the error shows that the return string of you http request is not only the json data
something like <!DOCTYPE are includeed
please check you are request the right url, and the server handle the request correctly
you can use your browser visit the url you request and check the return result
I am not using a fragment but here is similar solution.
Change your url and key values for retrieving values from json. I didn't have your url so i used some other. Please check it out. Same concept except i am not using fragments but this json parsing code works just fine.
First of all, you have to deal with the network on main thread exception
Add:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
in your class,
and
ADD this to ManiFestFile:
<uses-permission android:name="android.permission.INTERNET"/>
MainActivity.Java
package com.example.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
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;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Making HTTP request
String url = "http://api.androidhive.info/contacts/";
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting JSON Array
JSONArray begin = json.getJSONArray("contacts");
JSONObject c = begin.getJSONObject(0);
// Storing JSON item in a Variable
String id = c.getString("id");
String name = c.getString("name");
String size = c.getString("email");
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
JSONParser.Java
package com.example.test;
import android.os.StrictMode;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
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();
} 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;
}
}
I am new to android development. I have the following class for downloading some data in JSON format. I keep getting a Source not found error on the
HttpResponse httpResponse = httpClient.execute(httpPost);
line... I'm sure this must be a simple fix... Here is the class code...
package com.example.tankandroid;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
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();
} 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;
}
}
Put this code in onCreate method
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
Use Apache HttpCore and HttpClient libraries. Put these two libraries into your lib folder, its automatically add these into your build path.
One reason for this situation may be missing internet permissions in AndroidManifest.xml file. Adding this line in manifest will fix the issue.
<uses-permission android:name="android.permission.INTERNET" />
You need to provide some more information I think. Where do you get the "Source not found" error? Is it an Eclipse error that prevents you from compiling. Is it during compilation? Is it a runtime error? Could this be a possible duplicate of: Source not found Android? ?
Question: Why are you doing an HTTP POST if you don't intend to add any POST data? A GET seems more appropriate.
And since you also ask "I'm sure this must be a simple fix" then yes, it is. I'd really suggest that you rip out your HTTP code and switch to Android Asynchronous Http Client. It's super easy to work with and very well suited for getting an HTTP response and parsing it. Example:
AsyncHttpClient client = new AsyncHttpClient();
RequestParams rp = new RequestParams();
rp.put("some_param", "some value");
rp.put("another_param", "some other value");
client.post("http://www.simonsayssolutions.co.uk/index.php", rp, new AsyncHttpResponseHandler() {
#Override
public final void onSuccess(String response) {
// handle your response and parse JSON here
}
#Override
public void onFailure(Throwable e, String response) {
// something went wrong
}
});
or GET:
client.get("http://www.simonsayssolutions.co.uk/index.php", rp, new AsyncHttpResponseHandler() {
...
}
And finally if you want to simplify JSON parsing have a look at Jackson or Gson. Especially if you want to parse JSON data to Java objects and vice versa.
I'm trying to retrive some data from a web site.
I wrote a java class which seems to work pretty fine with many sites but it doesn't work with this particular site, which use extensive javascript in the input fomr.
As you can see from the code I specified the input fields taking the name from the HTML source, but maybe this website doesn't accept POST request of this kind?
How can I simulate an user-interaction to retrieve the generated HTML?
package com.transport.urlRetriver;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
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.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
public class UrlRetriver {
String stationPoller (String url, ArrayList<NameValuePair> params) {
HttpPost postRequest;
HttpResponse response;
HttpEntity entity;
String result = null;
DefaultHttpClient httpClient = new DefaultHttpClient();
try {
postRequest = new HttpPost(url);
postRequest.setEntity((HttpEntity) new UrlEncodedFormEntity(params));
response = httpClient.execute(postRequest);
entity = response.getEntity();
if(entity != null){
InputStream inputStream = entity.getContent();
result = convertStreamToString(inputStream);
}
} catch (Exception e) {
result = "We had a problem";
} finally {
httpClient.getConnectionManager().shutdown();
}
return result;
}
void ATMtravelPoller () {
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(2);
String url = "http://www.atm-mi.it/it/Pagine/default.aspx";
params.add(new BasicNameValuePair("ctl00$SPWebPartManager1$g_afa5adbb_5b60_4e50_8da2_212a1d36e49c$txt_address_s", "Viale romagna 1"));
params.add(new BasicNameValuePair("ctl00$SPWebPartManager1$g_afa5adbb_5b60_4e50_8da2_212a1d36e49c$txt_address_e", "Viale Toscana 20"));
params.add(new BasicNameValuePair("sf_method", "POST"));
String result = stationPoller(url, params);
saveToFile(result, "/home/rachele/Documents/atm/out4.html");
}
static void saveToFile(String toFile, String pos){
try{
// Create file
FileWriter fstream = new FileWriter(pos);
BufferedWriter out = new BufferedWriter(fstream);
out.write(toFile);
//Close the output stream
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return stringBuilder.toString();
}
}
At my point of view, there could be javascript generated field with dynamic value for preventing automated code to crawl the site. Send concrete site you want to download.
I have a class (RestClient.java) that extends AsyncTask:
package org.stocktwits.helper;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
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.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.util.Log;
public class RestClient extends AsyncTask<String, Void, JSONObject>{
public JSONObject jsonObj = null;
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
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();
}
/* This is a test function which will connects to a given
* rest service and prints it's response to Android Log with
* labels "Praeda".
*/
public static JSONObject connect(String url)
{
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Execute the request
HttpResponse response;
try {
response = httpclient.execute(httpget);
// Examine the response status
Log.i("Praeda",response.getStatusLine().toString());
// Get hold of the response entity
HttpEntity entity = response.getEntity();
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
// A Simple JSONObject Creation
JSONObject json=new JSONObject(result);
// Closing the input stream will trigger connection release
instream.close();
return json;
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected JSONObject doInBackground(String... urls) {
return connect(urls[0]);
}
#Override
protected void onPostExecute(JSONObject json ) {
this.jsonObj = json;
}
public void setJSONObject(JSONObject jsonFromUI){
this.jsonObj = jsonFromUI;
}
public JSONObject getJSONObject(){
return this.jsonObj;
}
}
I am trying to execute the AsyncTask on my Main class (Main.java):
RestClient rc = new RestClient();
JSONObject json = new JSONObject();
rc.setJSONObject(json);
rc.execute(buildQuery());
json = rc.getJSONObject();
//do some stuff with the json object
try { JSONObject query = json.getJSONObject("query");
//...
}
json is null because it is called before onPostExecute(). How can I get my JSON?
UPDATE:
I need to run this try block in onPostExecute():
try {
JSONObject query = json.getJSONObject("query");
JSONObject results = query.getJSONObject("results");
if (query.getString("count").equals("1")) { // YQL JSON doesn't
// return an array for
// single quotes
JSONObject quote = results.getJSONObject("quote");
Quote myQuote = new Quote();
myQuote.setName(quote.getString("Name"));
myQuote.setSymbol(quote.getString("Symbol"));
myQuote.setLastTradePriceOnly(quote
.getString("LastTradePriceOnly"));
myQuote.setChange(quote.getString("Change"));
myQuote.setOpen(quote.getString("Open"));
myQuote.setMarketCapitalization(quote
.getString("MarketCapitalization"));
myQuote.setDaysHigh(quote.getString("DaysHigh"));
myQuote.setYearHigh(quote.getString("YearHigh"));
myQuote.setDaysLow(quote.getString("DaysLow"));
myQuote.setYearLow(quote.getString("YearLow"));
myQuote.setVolume(quote.getString("Volume"));
myQuote.setAverageDailyVolume(quote
.getString("AverageDailyVolume"));
myQuote.setPeRatio(quote.getString("PERatio"));
myQuote.setDividendYield(quote.getString("DividendYield"));
myQuote.setPercentChange(quote.getString("PercentChange"));
quotesAdapter.add(myQuote);}
Hey You can use listeners to fix this problem.
I've changed the code slightly to use this.
package com.insidetip.uob.data;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
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.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
public class JSONClient extends AsyncTask<String, Void, JSONObject>{
ProgressDialog progressDialog ;
GetJSONListener getJSONListener;
Context curContext;
public JSONClient(Context context, GetJSONListener listener){
this.getJSONListener = listener;
curContext = context;
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
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 static JSONObject connect(String url)
{
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Execute the request
HttpResponse response;
try {
response = httpclient.execute(httpget);
// Examine the response status
Log.i("Praeda",response.getStatusLine().toString());
// Get hold of the response entity
HttpEntity entity = response.getEntity();
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
// A Simple JSONObject Creation
JSONObject json=new JSONObject(result);
// Closing the input stream will trigger connection release
instream.close();
return json;
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
public void onPreExecute() {
progressDialog = new ProgressDialog(curContext);
progressDialog.setMessage("Loading..Please wait..");
progressDialog.setCancelable(false);
progressDialog.setIndeterminate(true);
progressDialog.show();
}
#Override
protected JSONObject doInBackground(String... urls) {
return connect(urls[0]);
}
#Override
protected void onPostExecute(JSONObject json ) {
getJSONListener.onRemoteCallComplete(json);
progressDialog.dismiss();
}
}
Use in the calling class like this.
JSONClient client = new JSONClient(context, listener);
client.execute(URL);
Dont forget to implement the listener
public interface GetJSONListener {
public void onRemoteCallComplete(JSONObject jsonFromNet);
}
I'm be mistaken by result of doInBackground can be consumed in onPostExecute
doInBackground(Params...), invoked on
the background thread immediately
after on PreExecute() finishes
executing. This step is used to
perform background computation that
can take a long time. The parameters
of the asynchronous task are passed
to this step. The result of the
computation must be returned by this
step and will be passed back to the
last step. This step can also use
publishProgress(Progress...) to
publish one or more units of
progress. These values are published
on the UI thread, in the
onProgressUpdate(Progress...) step.
#Override
protected void onPostExecute(JSONObject json ) {
// DO stuff here ( it's UI thread )
mJsonFromTheActivity = json;
}
execute() always returns the AsyncTask itself. The object you return from doInBackground() is handed to you in onPostExecute().
If you have your asynctask as a nested inner class of your activity, you can set one of your activities variables to the result of your asynctask