I am trying to execute query on database in the localhost and send the JSON object to the client in android. I m not been able to know what is the problem in my code. So some one please help me on this regard.
My php code is the one where i m sending the JSON object.
php code
query executed successfully..
$row=mysql_fetch_array($result1);
$email=$row['EM'];
$pass=$row['PASS'];
$post=array("email"=>$email, "pass"=>$pass);
$posts[] = array("post"=>$post);
//echo "SUCCESS";
header('Content-type: application/json');
echo json_encode(array("posts"=>$posts));
And in android side i ve this code below;
HttpResponse response = doPost(url, kvPairs);
String responseBody=response.toString();
String temp = EntityUtils.toString(response.getEntity());
if (temp.compareTo("SUCCESS")==0)
{
Toast.makeText(this, "Working", Toast.LENGTH_LONG).show();
}
Above part executes ..
Below code throws a JSON exception
JSONObject json = new JSONObject(responseBody);
JSONArray jArray = json.getJSONArray("posts");
no_of_obj=jArray.length();
nemail=new String[no_of_obj];
npass=new String[no_of_obj];
for (int i = 0; i < jArray.length(); i++) {
JSONObject e = jArray.getJSONObject(i);
String s = e.getString("post");
JSONObject jObject = new JSONObject(s);
Toast.makeText(context,jObject.getString("email")+":"+jObject.getString("pass") , duration).show();
nemail[i]=jObject.getString("email");
npass[i]=jObject.getString("pass");
}
In the log cat i can see : The json string must begin with "{"....
Probably you cannot do this
String s = e.getString("post");
because there is no "post" key in the array of Strings you have given,...
Try doing this,
String s = e.has("post")?e.getString("post"):null;
and then on next line keep a null check before Creating JSONObject..
Try this
$posts['data'] = $post;
//echo "SUCCESS";
header('Content-type: application/json');
echo json_encode($posts);
Related
I am trying to send data from MSSQL table on server to Android app via PHP. I am using Volley to send the request for data.
The issue is that no matter what I try, Android says the returned JSON encoded string is "Malformed".
I have put the returned JSON string "response" into online JSON decoders and it displays perfectly, yet Andoid says: "Syntax error, malformed JSON{"data":[{"claimNumber":"f265e5e.....}]".
However, if I hardcode a copy and paste of the returned "response" string into a variable "input" in the Android
response function, it works perfectly.
JSONObject jObj = new JSONObject(response); ** Fails - Android says Malformed.
JSONObject jObj = new JSONObject(input); ** Android uses it with no issues.
The following is the method in Android used to receive the PHP response. Have included Log outputs of both the "response" string and
the manually entered "input" string. They are identical, yet Android won't use the actual "response" string.
public void onResponse(String response) {
if (response.equals("failed")) {
Log.d("failed", "failed");
callback.onResponse(null);
return;
}
try {
// Android sees the response returned from the PHP function as always Malformed.
Log.d("response", response);
D/response: - Syntax error, malformed JSON {"data":[{"claimNumber":"f265e5e6513070abd1f711232cfd3a491075f15bc9714cf723e373f02e71a214","xlsLine":"8b3490231cd923c133989dd93574de131b6c388a86153a74eb6ae2507193a008c9d3d0264452cc1bd1113d5a722f3ea7975f322461f486be96e789424459e20bcbaf878f5d0efe09426b90c046d881100e166ef0bfcf8721266383aabf3837a213854e8425e92b722791640576d3c0ce7722ff3de2e6005c85df840bea3b10982b7bcf8bec3398ea03e08e6a2879cb29e0e6c3c05370e1c2cf819e6156991c762b2247e8a5b51edb852bb371aca011eccaa581ed577e74d6bf0f2a71e43e7751e3fa6e5f68c2a6e4ccd4fc338fc2a2ea4a9d98018c52fe5953741a53d7f7a6f1c1e57901d64c957dc1776ab0ed28f5754f7d44008ebc5864cfd34dd3b1f1bf82db49674b8e7a3e381882f7cc1035bfdba114280f6c173e337d1813fb47a9b1aaf1d52faac197f90cced9eea754cf441cb262b3117444ad3a265cefb9593d40cdb8a3ae0235cc06baffbcac493bf45852908b014f063c29d85347e808e7ed4be8688327bf3280759ea1ff187287dcabaaee8859a6da782cd2451e2911fe16ca7d","markerColor":"0","edited":"0"}]}
// If I copy the returned "response" string manually into a variable "input", Android says it's fine.
String input = "{\"data\":[{\"claimNumber\":\"f265e5e6513070abd1f711232cfd3a491075f15bc9714cf723e373f02e71a214\",\"xlsLine\":\"8b3490231cd923c133989dd93574de131b6c388a86153a74eb6ae2507193a008c9d3d0264452cc1bd1113d5a722f3ea7975f322461f486be96e789424459e20bcbaf878f5d0efe09426b90c046d881100e166ef0bfcf8721266383aabf3837a213854e8425e92b722791640576d3c0ce7722ff3de2e6005c85df840bea3b10982b7bcf8bec3398ea03e08e6a2879cb29e0e6c3c05370e1c2cf819e6156991c762b2247e8a5b51edb852bb371aca011eccaa581ed577e74d6bf0f2a71e43e7751e3fa6e5f68c2a6e4ccd4fc338fc2a2ea4a9d98018c52fe5953741a53d7f7a6f1c1e57901d64c957dc1776ab0ed28f5754f7d44008ebc5864cfd34dd3b1f1bf82db49674b8e7a3e381882f7cc1035bfdba114280f6c173e337d1813fb47a9b1aaf1d52faac197f90cced9eea754cf441cb262b3117444ad3a265cefb9593d40cdb8a3ae0235cc06baffbcac493bf45852908b014f063c29d85347e808e7ed4be8688327bf3280759ea1ff187287dcabaaee8859a6da782cd2451e2911fe16ca7d\",\"markerColor\":\"0\",\"edited\":\"0\"}]}";
// Log showing Androids interpretation of the manually entered "input" string
// It matches the "response" string exactly yet "response" string fails.
Log.d("input", input);
D/input: {"data":[{"claimNumber":"f265e5e6513070abd1f711232cfd3a491075f15bc9714cf723e373f02e71a214","xlsLine":"8b3490231cd923c133989dd93574de131b6c388a86153a74eb6ae2507193a008c9d3d0264452cc1bd1113d5a722f3ea7975f322461f486be96e789424459e20bcbaf878f5d0efe09426b90c046d881100e166ef0bfcf8721266383aabf3837a213854e8425e92b722791640576d3c0ce7722ff3de2e6005c85df840bea3b10982b7bcf8bec3398ea03e08e6a2879cb29e0e6c3c05370e1c2cf819e6156991c762b2247e8a5b51edb852bb371aca011eccaa581ed577e74d6bf0f2a71e43e7751e3fa6e5f68c2a6e4ccd4fc338fc2a2ea4a9d98018c52fe5953741a53d7f7a6f1c1e57901d64c957dc1776ab0ed28f5754f7d44008ebc5864cfd34dd3b1f1bf82db49674b8e7a3e381882f7cc1035bfdba114280f6c173e337d1813fb47a9b1aaf1d52faac197f90cced9eea754cf441cb262b3117444ad3a265cefb9593d40cdb8a3ae0235cc06baffbcac493bf45852908b014f063c29d85347e808e7ed4be8688327bf3280759ea1ff187287dcabaaee8859a6da782cd2451e2911fe16ca7d","markerColor":"0","edited":"0"}]}
JSONObject jObj = new JSONObject(input);
jArray = jObj.getJSONArray("data");
} catch (JSONException e) {
e.printStackTrace();
}
}
// GSON print of JSON Object from the manually entered "input" variable.
I/System.out: {
"nameValuePairs": {
"data": {
"values": [
{
"nameValuePairs": {
"claimNumber": "f265e5e6513070abd1f711232cfd3a491075f15bc9714cf723e373f02e71a214",
"xlsLine": "8b3490231cd923c133989dd93574de131b6c388a86153a74eb6ae2507193a008c9d3d0264452cc1bd1113d5a722f3ea7975f322461f486be96e789424459e20bcbaf878f5d0efe09426b90c046d881100e166ef0bfcf8721266383aabf3837a213854e8425e92b722791640576d3c0ce7722ff3de2e6005c85df840bea3b10982b7bcf8bec3398ea03e08e6a2879cb29e0e6c3c05370e1c2cf819e6156991c762b2247e8a5b51edb852bb371aca011eccaa581ed577e74d6bf0f2a71e43e7751e3fa6e5f68c2a6e4ccd4fc338fc2a2ea4a9d98018c52fe5953741a53d7f7a6f1c1e57901d64c957dc1776ab0ed28f5754f7d44008ebc5864cfd34dd3b1f1bf82db49674b8e7a3e381882f7cc1035bfdba114280f6c173e337d1813fb47a9b1aaf1d52faac197f90cced9eea754cf441cb262b3117444ad3a265cefb9593d40cdb8a3ae0235cc06baffbcac493bf45852908b014f063c29d85347e808e7ed4be8688327bf3280759ea1ff187287dcabaaee8859a6da782cd2451e2911fe16ca7d",
"markerColor": "0",
"edited": "0"
}
}
]
}
}
}
Have tried php output with and without slashes. No change... still malformed.
Have tried stripping non-standard chars. There are none.
Have forced charset "UTF-8". No difference.
Have searched and tried every conceivable solution for this on Google. Nothing works.
I'm at a loss as to what to try next. Totally confused on why Android can't use the returned Json string,
but can use it if you manually take the same string and put it in a variable in the code directly.
Can someone tell me if this is a known bug, if the JSON really is malformed or if something else comes to mind?
Thank you
EDIT
Here is the PHP that creates the json to return to Android.
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$stmt2 = sqlsrv_query( $conn3, $tsql1, $params, $options);
$row_count = sqlsrv_num_rows($stmt2);
if ($row_count === false) {
echo("failed");
} else {
while( $userClaims = sqlsrv_fetch_array($stmt2, SQLSRV_FETCH_ASSOC) ) {
$claimNum = $userClaims['ClaimNumber'];
$xls = $userClaims['XLS'];
$color = $userClaims['Color'];
$edited = "0";
$keyvals = (object) array("claimNumber" => $claimNum, "xlsLine" => $xls, "markerColor" => $color, "edited" => $edited);
array_push($response,$keyvals);
}
$encoded = json_encode(array('data' => $response));
EDIT 2
The following is the complete php section of code that creates the json return string. The array is initialized at the top. Have written the php json string to a text file on server and copied the text to a json checker and it works fine.
$response = array();
$i = 0;
$param1 = $token;
$params = array( &$param1);
$tsql1 = "SELECT * FROM Claims WHERE Token = ? AND DeletionFlag = 0";
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$stmt2 = sqlsrv_query( $conn3, $tsql1, $params, $options);
$row_count = sqlsrv_num_rows($stmt2);
if ($row_count === false) {
echo("failed");
} else {
while( $userClaims = sqlsrv_fetch_array($stmt2, SQLSRV_FETCH_ASSOC) ) {
$claimNum = $userClaims['ClaimNumber'];
$xls = $userClaims['XLS'];
$color = $userClaims['Color'];
$edited = "0";
$keyvals = (object) array("claimNumber" => $claimNum, "xlsLine" => $xls, "markerColor" => $color, "edited" => $edited);
array_push($response,$keyvals);
}
$encoded = json_encode(array('data' => $response));
echo $encoded;
}
sqlsrv_close($conn3);
Thank you for your help Andy. I finally figured it out. I found a line of code in the php file that was out of place. It was trying to json_decode an empty string. This is what was generating the extra 36 chars about the malformed string in my actual response. Once I moved it to the correct place, everything started working beautifully. Should have known better, most likely a blasted copy/paste error. Should teach me not to be lazy and actually type ALL my code. Thanks, again!!
Am retrieving data from MySQL table using Android HttpURLConnection
And am getting this error:
W/System.err: org.json.JSONException: Value br of type
java.lang.String cannot be converted to JSONObject
Error is at this line:
JSONObject jsonObj = new JSONObject(myJSON);
my code:
try {
JSONObject jsonObj = new JSONObject(myJSON);
Challenges = jsonObj.getJSONArray(TAG_RESULTS);
for (int i = 0; i < Challenges.length(); i++) {
JSONObject c = Challenges.getJSONObject(i);
String id = c.getString(TAG_ID);
String trackCoordinates = c.getString(TAG_COORDINATES);
HashMap<String, String> challengesFromDB = new HashMap<>();
challengesFromDB.put(TAG_ID, id);
challengesFromDB.put(TAG_COORDINATES, trackCoordinates);
ChallengesList.add(challengesFromDB);
}
.php file:
$sql = "select * FROM Challenges";
$res=mysqli_query($con, $sql);
$result=$array();
while($row = mysqli_fetch_array($res)){
array_push($result,array('id'=>$row[0],'userMail'=>$row[1],'trackCoordinates'=>$row[2]));
}
header('Content-Type: application/json');
print json_encode(array("result"=>$result));
mysqli_close($con);
Maybe error occuring because of my table field:trackCoordinates , am storing here googleMaps latitude, longtitude coordinates array, for example:
[lat/lng: (54.892597770959945,23.87877881526947), lat/lng: (54.89242519582151,23.876227363944054), lat/lng: (54.8917038430203,23.877791762351986)]
You aren't getting JSON, you're getting html. Either something on your server is outputting html, or you're hitting the wrong URL.
My goal is to send request from asp.net's page to php's page, and send email from php page.
my code on asp.net's page is
Dictionary<string, string> keyValues = new Dictionary<string, string>();
keyValues.Add("to", "to#gmail.com");
keyValues.Add("from", "from#gmail.com");
keyValues.Add("message", "Conent of Email");
keyValues.Add("Subject", "Subject of Email");
JavaScriptSerializer js = new JavaScriptSerializer();
string json = js.Serialize(keyValues);
WebClient webClient = new WebClient();
NameValueCollection formData = new NameValueCollection();
formData.Add("a", json);
byte[] response = webClient.UploadValues("http://example.com/emailme.php", "POST", formData);
string responsebody = Encoding.UTF8.GetString(response);
the value which i'm passing after Serializing is
and the code written in my php page is
if (isset($_POST['a']))
{
echo "Value Exists";
echo "<br> Value before decoding is ".$_POST['a']."<br>";
$result=json_decode($_POST['a'],true);
echo "the value after decoding is ";
echo $result;
echo "<br> now for print_r <br>";
print_r($result);
} else
{echo "Value Does Not Exists";}
it was the code, now i'm attaching the image of result for my request.
As you can see the it shows the result before decoding for after decoding it shows nothing.
i will proceed for sending email after the result.
$result=json_decode(stripslashes($_POST['a']),true);
will do the trick ;)
I am fetching data from a php server in its normal format..the columns are details and image..
I want the image in base64 format nd the details in utf8 format..all this data into one array that will be json encoded and will then be parsed at android side..How do i do this..so that i can Json parse in this manner..
String result= convertStreamToString(is);
JSONObject json=new JSONObject(result);
jArray=json.getJSONArray("details");
for(int i=0;i<jArray.length();i++)
{
JSONObject c=jArray.getJSONObject(i);
String detail=c.getString("details");
String image=c.getString("image");
Log.v("topics", topic);
is.close();
}
The php code:
while($out=mysql_fetch_assoc($result))
{
echo $out;
print_r(base64_encode($out[image]));
echo base64_encode($out['image']);
echo utf8_encode($out['details']);
$tempImage = base64_encode($out['image']);
echo $tempImage;
$tempDetails = utf8_encode($out['details']);
$post[] = array("image"=>$tempImage);
$post []= array("details"=>$tempDetails);
}
echo json_encode(array("login"=>$post));
i think that you can use this link to learn about this
Issues-parsing data to the php and jsons
or visit this : http://androidexample.com/JSON_Parsing_-_Android_Example/index.php?view=article_discription&aid=71&aaid=95
I have read through many other questions regarding PHP and JSONArray looping. I am sending in a JSONArray of values of different students with their class and studentId from my Android device. Using these values, I search the database for their names and return a JSONArray.
JSON Input: [{"studentId":"2","class":"2a","dbname":"testDb"}]
<?php
$jsonString = $_POST['json']; //see comment below
$jArray = json_decode($jsonString, true);
$conn = mysql_connect('localhost', 'user', 'pwd' );
mysql_select_db('dbname', $conn);
foreach( $jArray as $obj ){
$className = $obj['class']; //String
$id= $obj['studentId']; //int
$result = mysql_query("SELECT name FROM student WHERE class='$className' AND id='$id'");
$e=mysql_fetch_assoc($result); //will only fetch 1 row of result
$output[]=$e;
}
echo (json_encode($output));
?>
Android
HttpClient client = new DefaultHttpClient();
HttpResponse response;
try{
HttpPost post = new HttpPost("http://abc/getName.php");
List<NameValuePair> nVP = new ArrayList<NameValuePair>(2);
nVP.add(new BasicNameValuePair("json", studentJson.toString())); //studentJson is the JSON input
//student.Json.toString() produces the correct JSON [{"studentId":"2","class":"2a","dbname":"testDb"}]
post.setEntity(new UrlEncodedFormEntity(nVP));
response = client.execute(post);
if(response!=null){
//process data send from php
}
}
SOLVED: See answer below
SOLVED: Finally understood what was the problem. After posting from Android to PHP script, my JSONArray becomes [{\"studentId\":"2\",\"class\":\"2a\",\"dbname\":\"testDb\"}] To remove the "\", use PHP command stripslashes Spent 4 hours debugging!
Hope this will be a good guide for those that wants to send and retrieve data between Android and PHP
Here's your problem:
print_r(json_decode('[{"regNo":"2","class":"2a","dbname":"TestData"}]',true));
returns Array ( [0] => Array ( [regNo] => 2 [class] => 2a [dbname] => TestData ) ) meaning your decoded json is put within an array
Use array_shift(json_decode($jsonString, true)); to remove the parent array.