Java parsing json array, Error parsing data org.json.JSONException - java

This is my code, in my log, i'm getting:
E/JSON Parser: Error parsing data org.json.JSONException Value xml of type java.lang.String cannot be converted to JSONObject
I really need a solution i have been searching for weeks now.
#Override
protected String doInBackground(String... para) {
List<NameValuePair> params=new ArrayList<NameValuePair>();
JSONObject json=jparser.makeHttpRequest(getDataUrl, "POST", params);
try {
success=json.getInt("success");
if(success==1){
drivers=new ArrayList<Driver>();
JSONArray sounds=json.getJSONArray("location");
for (int i = 0; i < sounds.length(); i++) {
JSONObject jobj=sounds.getJSONObject(i);
Driver d=new Driver();
d.setId(jobj.getString("id"));
d.setName(jobj.getString("name"));
d.setEmail(jobj.getString("email"));
d.setNumber(jobj.getString("number"));
d.setLatitude(jobj.getString("latitude"));
d.setLongitude(jobj.getString("longitude"));
d.setInfo(jobj.getString("info"));
d.setCost(jobj.getString("cost"));
drivers.add(d);
}
}
} catch (JSONException e) {
e.printStackTrace();
error=1;
}catch (Exception e) {
error=1;
}
return null;
}
And this is the JSONParser class
JSONParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method.equals("POST")){
// 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();
} else if(method.equals("GET")) {
// request method is GET
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, "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;
}
}
PHP File
<?php
header('Content-Type: application/json');
$response = array();
// include db connect class
require_once 'core/db_connect.php';
$db = new DB_CONNECT();
$sql="SELECT * FROM locations WHERE online=1";
$result = mysqli_query($db->connect(), $sql) or die(mysqli_error($db->connect()));
if (mysqli_num_rows($result)>0) {
$response["location"] = array();
while ($row=mysqli_fetch_array($result)) {
$files=array();
$files["id"]=$row["id"];
$files["name"]=$row["name"];
$files["email"]=$row["email"];
$files["number"]=$row["number"];
$files["latitude"]=$row["latitude"];
$files["longitude"]=$row["longitude"];
$files["info"]=$row["vehicleinfo"];
$files["cost"]=$row["costpkm"];
array_push($response["location"], $files);
}
$response["success"]=1;
echo json_encode($response);
} else {
$response["success"]=0;
$response["message"]="No Taxi found";
echo json_encode($response);
}
?>

Based on your error, the return result for makeHttpRequest is an xml object instead of json formated string.

Solved
the error was due to incorrect url, the xampp apache server was returning an object not found page..error 404, which is an xml file. That's why the return result for makeHttpRequest is an xml object instead of json formated string.

Related

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

For each loop is not executing when uploaded at 000webhost server

I have an application that post data to a php file in an online server. When the post is done i get a garbage of html code. In it says I have a php error and that is Invalid argument supplied for each() on line 33. However this problem does not occur if I run it in localhost. I don't understand why this problem is occuring. So someone please help me to solve it.
The following is my jsonparser Class
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getandpostJSONFromUrl(String url, String method,JSONArray name) {
// Making HTTP request
try {
// defaultHttpClient
if (method == "POST") {
HttpParams params = new BasicHttpParams();
//params.setParameter("data", auth);
HttpClient httpclient = new DefaultHttpClient(params);
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair("json", name.toString()));
for (NameValuePair nvp : postParams) {
String name2 = nvp.getName();
String value = nvp.getValue();
Log.d("NameValue pair content", ""+name2+""+value);
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams,HTTP.UTF_8);
httpPost.setEntity(entity);
HttpResponse response = httpclient.execute(httpPost);
String responseBody = EntityUtils.toString(response.getEntity());
Log.d("",responseBody);
}
if (method == "GET") {
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();
}
if (method == "POST") {
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
} catch (Exception e) {
Log.e("Buffer error", "Buffer error" + e);
}
} else if (method == "GET") {
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;
}
}
The following is the php file on the server
<?php
header('Content-type: application/json');
/*define('DB_NAME', 'a1422982_sshop');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');*/
define('DB_NAME', 'onlineshop');
define('DB_USER', 'shop');
define('DB_PASSWORD', 'pass');
define('DB_HOST', 'mysql28.000webhost.com');
$link = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD);
if(!$link){
die('could not connect: '.msql_error());
}
$db_selected=mysql_select_db(DB_NAME, $link);
if(!$db_selected){
die('Can not use '.DB_NAME.':'.mysql_error());
}
//var_dump(json_decode ($_POST['json'])));
if($_POST['json']){
$parsed = json_decode($_POST['json'],TRUE);
$i=0;
foreach ($parsed as $obj) {
$ProductName = $obj['Name'];
$ProductQuantity= $obj['Quantity'];
$sql="Update productlist Set Quantity='$ProductQuantity' where Name='$ProductName';";
$retval = mysql_query( $sql, $link );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
$i++;
echo $ProductName." ".$ProductQuantity;
}
}else{
echo "empty";
}
?>
there's a missing options on your HttpPost request set the entity metadata and the resulting entity as string.
In your java code you can do this:
Map<String, String> postData = new HashMap<String, String>();
postData.put("KEY", "yourvalue");
JSONObject holder = new JSONObject(postData);
StringEntity jsonStringEntity = new StringEntity(holder.toString());
httpost.setEntity(jsonStringEntity);
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json");
in that way your PHP code could actually parse your post data since json_decode() expecting json as parameter.

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.

Using Hebrew on JSON code?

I am using this code to POST and GET data from MySQL database .
However when getting data that is not in English, it is displayed as question marks ?
what changes do I make to enable Hebrew language use ?
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {
}
public JSONObject makeHttpRequest(String url, String method,List<NameValuePair> params) {
try {
if(method == "POST"){
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"){
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());
}
return jObj;
}
}
Make sure your HTTP response comes out encoded in Unicode (UTF-8 for example), and also your client (the application consuming the service) must be aware that of that encoding to read your response.

Value of type org.json.JSONArray cannot be converted to JSONObject

Got stuck at this error:
3169-3190/com.meisolsson.app E/JSON Parser﹕ Error parsing data org.json.JSONException: Value [{"type":0,"can_see_custom_stories":true,"display":"","name":"jenniaim"},{"type":0,"can_see_custom_stories":true,"display":"","name":"lucasgardebrand"},{"type":0,"can_see_custom_stories":true,"display":"","name":"herr_anderzzon"},{"type":0,"can_see_custom_stories":true,"display":"","name":"chrillebile"},{"type":0,"can_see_custom_stories":true,"display":"","name":"meisolsson"},{"type":0,"can_see_custom_stories":true,"display":"","name":"sakanapanda"},{"type":0,"can_see_custom_stories":true,"display":"Team Snapchat","name":"teamsnapchat"},{"type":0,"can_see_custom_stories":true,"display":"","name":"fabianlindfors"},{"type":0,"can_see_custom_stories":true,"display":"Katja","name":"katjaawesome"},{"type":0,"can_see_custom_stories":true,"display":"","name":"swimkey"},{"type":1,"can_see_custom_stories":true,"display":"","name":"agnesholmberg"}] of type org.json.JSONArray cannot be converted to JSONObject
So here is the code:
public class JSONParser extends AsyncTask<Void, Void, Boolean> {
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);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username", LoginActivity.Suser));
nameValuePairs.add(new BasicNameValuePair("password", LoginActivity.Spass));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
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;
}
#Override
protected Boolean doInBackground(Void... params) {
getJSONFromUrl("http://flapplabs.se/development/snapchat/friends.php");
return null;
}
}
[..] means it should be an JSONArray and {..} means it should be a JSONObject.
Therefore:
try {
JSONArray jObj = new JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
Even though I had a single JSON object it was stored in an array as
Hariharan has pointed out with the square brackets [ { items:items, ... } ]
My solution was simply to parse out the only object, located in array position [0] like this
JSONArray jsonArray = new JSONArray(stringIn);
JSONObject obj = jsonArray.getJSONObject(0);

Categories