android json parsing keeps on loading - java

I am not new to android platform, i have parsed many json pages before, but one link is creating problem. I am using following function to return the json object. The program stops at reader.readline() and loading does not stop.
public JSONObject getJSONFromUrl(String url) {
DefaultHttpClient httpClient = new DefaultHttpClient();
try {
HttpResponse httpResponse = httpClient.execute(new HttpGet(url));
if (httpResponse.getStatusLine().getStatusCode()==200)
{
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
System.out.println("Unsupported Encoding");
} catch (ClientProtocolException e) {
e.printStackTrace();
System.out.println("Client Protocol");
} catch (IOException e) {
e.printStackTrace();
System.out.println("IO");
}
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);
}
is.close();
jsonStr = sb.toString();
} catch (Exception e) {
System.out.println("Error here");
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(jsonStr);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}
can any one suggest something?

I am pretty sure that this is caused by the server not finishing the response in your case. Try to isolate that using "curl" as a client first.
Also there is an easier way to fetch body into String if you use EntitUtils like this:
EntityUtils.toString(entity);
You can also specify encoding as second parameter.
http://developer.android.com/reference/org/apache/http/util/EntityUtils.html

Related

why i am getting org.json.JSONException: Value property of type java.lang.String cannot be converted to JSONObject?

By use of this i'm getting response code and trying to convert String to JSONObject but getting exception.
public JSONObject getJSONFromUrl(String url,List<NameValuePair> nameValuePairsList) {
// Making HTTP request
try {
HttpParams param = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(param, 20000);
HttpConnectionParams.setSoTimeout(param, 20000);
DefaultHttpClient httpClient = new DefaultHttpClient(param);
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairsList));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
PropertyLogger.debug("URL Request: ", url.toString());
PropertyLogger.debug("Encoded Params: ", nameValuePairsList.toString());
HttpResponse httpResponse = httpClient.execute(httpPost);
int code = httpResponse.getStatusLine().getStatusCode();
if (code != 200) {
PropertyLogger.debug("HTTP response code is:", Integer.toString(code));
return null;
} else {
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (ConnectTimeoutException e) {
// TODO: handle exception
PropertyLogger.error("Timeout Exception", e.toString());
return null;
} catch (SocketTimeoutException e) {
// TODO: handle exception
PropertyLogger.error("Socket Time out", e.toString());
return null;
} catch (UnsupportedEncodingException e) {
PropertyLogger.error("UnSupported Exception", e.toString());
e.printStackTrace();
return null;
} catch (ClientProtocolException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
String TAG = "PropertyJsonParser";
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();
jsonResp = sb.toString();
PropertyLogger.debug("Content: ", sb.toString());
} catch (Exception e) {
PropertyLogger.error("Buffer Error", "Error converting Response " + e.toString());
return null;
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(jsonResp);
} catch (JSONException e) {
PropertyLogger.error("JSON Parser", "Error parsing data :" + e.toString());
return null;
}
return jObj;
}
You get this error because you are not receiving proper JSON response.
Check your api response and possible also provide your api response.
Because your variable jsonResp contain string value not JSONObject so please first print and make sure is it string type value or not.

jsonparse android get data from server secure with login/password

I want to get the data ["04:44","05:59","12:03","15:29","18:07","18:07","19:17"]
from a server that is secure with login and password.
I already have the code for get the datajson:
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;
}
How can I
connect with the server and
how can I get the data from jObj?

POST httpRequest doesn't fetch all data

I use the following function in java to connect to my php script in a server.
The script queries for an image (BLOB), encodes it (base64) and sends it back in JSON format.
The problem is that I can get some of the encoded data but not all of them. Should I use any headers on my httpRequest? What am I doing wrong?
Here is my java function:
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// request method is 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();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
System.out.println("Print1: "+json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
return null;
}
// 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 null;
}
System.out.println("Print2: "+jObj.toString());
// return JSON String
return jObj;
}
Here is my PHP code showing the JSON structure:
$response = array(
"success" => 0,
"message" => "",
"data" => "");
$stmt->bindColumn(1, $binary, PDO::PARAM_LOB);
$stmt->bindColumn(2, $professorName);
$stmt->fetch(PDO::FETCH_BOUND);
$pic = base64_encode($binary);
$data = array(
"photo" => $pic,
"professorName" => $professorName
);
$response["success"] = 1;
$response["message"] = "We have results!";
$response["data"] = $data;
echo json_encode($response);
After testing I realized that if I use a small image (tested size < 1Kb) everything works as it should.
If I try to obtain a larger image (here 5 Kb) the data I obtain is cut in the middle.
The json structure doesn't arrive complete.
Here is an example of a successful transfer:
Print1: {"success":1,"message":"We have results!","data":
{"photo":"iVBORw0KGgoAAAANS~~~~more data~~~~N6GGYzAAAAAElFTkSuQmCC","professorName":"cluvas"}}
Print2: {"data":{"kathigitisName":"cluvas","photo":"iVBORw0K~~~~more data~~~~AElFTkSuQmCC"},
"message":"We have results!","success":1}
Here an example of an unsucessful one
Print1: {"success":1,"message":"We have results!","data":
{"photo":"\/9j\/4AAQS~~~~more data~~~~6KKogkH\/ //unexpected end of data
Print2: {"data":{"professorName":"cluvas",
"photo":"\/9j\/4AAQS~~~~more data~~~~K+U\/Ce //unexpected end of data

Read json object from server

Hi I am new to android programming and I am working on a project that converts a list into json object and stores it in the server and retrieves it. I am able to send the json object to the server and store it but i am not able to retrieve it. What approach should i use to retrieve the json object stored on the server?
You can reffer bellow class ...... call getJSONfromURL(YOUR_JOSN_URL) and method will return you JSONObject.
I hope this will work
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
JSONObject jObj = null;
String json = "";
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
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, "UTF-8"), 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;
}
}
To retrieve JSON from server you have to establish a connection with server first by using DefaultHttpClient Hope you did that. If yes, post your code and if no then have look on
www.androidhive.info/2012/01/android-json-parsing-tutorial
Or google it you will lot of help to parse the JSON when you have URL with you.

JSON parsing for huge data

I have to download more than 40,000 json records from my web service, but it is taking so long time to download. The downloaded data is storing into a string, but I am not able parse that string. Please tell me a solution to solve this problem.
URL: https://buzoonga.co.uk/appapi/contacts.php?user_id=531
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;
}
check out gzip. excellent text compressor. you are going to remove ~70% of the size :) you just have to gzip it serverside and unzip it clientside. if this overhead increases the time but the download is a third of the time, you might win in the end.
Also consider designing a better schema to reduce the size of your jsons.
Like, instead of "animalBodyParts" put "abp" or something. you have not put an example of your jsons so I am just guessing.
You can use the JSONTokener class and pass the InputStream
jObj = new JSONObject(new JSONTokener(httpEntity.getContent()));
To reduce the time to download you need to support gzipped downloads on the server side or change your JSON structure to a more compact array based format

Categories