My "nhanvien" table has 3 columns : "id", "Maso", "Hoten". I use the code below to get all data from this table but I've got an error.
<?php
// get all nhanvien from nhanvien table
$response = array();
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
$result = mysql_query("SELECT *FROM nhanvien") or die(mysql_error());
// looping through all results
// nhanvien node
if (mysql_num_rows($result) > 0) {
$response["nhanvien"] = array();
while ($row = mysql_fetch_array($result)) {
$nhanvien = array();
$nhanvien ["id"] = $row["id"];
$nhanvien ["Maso"] = $row["Maso"];
$nhanvien ["Hoten"] = $row["Hoten"];
array_push($response["nhanvien"], $nhanvien);
}
$response["success"] = 1;
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No nhanvien found";
echo json_encode($response);
?>
I have this error :
Error parsing data org.json.JSONException: Value Connected of type java.lang.String cannot be converted to JSONObject
Here is my android code:
try {
URL murl = new URL(url);
URLConnection urlConnection = murl.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(),"UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
reader.close();
json = sb.toString();
Log.d("connect...", json.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(new String(json));
Log.d("parse...", jObj.toString());
} catch (JSONException e) {
Log.e("JSON Parser 123", "Error parsing data " + e.toString());
//Log.e("JSON Parser", "Error parsing data [" + e.getMessage()+"] "+json);
}
// return JSON String
return jObj;
}
Related
I have a php file where i retrieve data from a db, then convert it to an array, and then encode it, so the Android app I'm developing gets the JSONArray parse it, and get the data.
This is the php file:
<?php
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
$dbh = $db->connect(); // here you get the connection
$query = "SELECT *FROM lost_pets";
$result = $dbh->prepare($query);
$result->execute();
if ($result->fetchAll() > 0) {
foreach($dbh->query($query) as $row){
$pet["id"] = $row['id'];
$pet["name"] = $row['name'];
$pet["breed"] = $row['breed'];
$response["pet"] = array($pet);
echo json_encode($response);
}
}
?>
This is the result:
{"pet":[{"id":"1","name":"Prueba","breed":"Yorkshire Terrier"}]}{"pet":[{"id":"2","name":"Prueba2","breed":"German Shepherd"}]}{"pet":[{"id":"3","name":"Prueba3","breed":"Beagle"}]}
The problem is, when I retrieve the JSONObject in Android, and do getJSONArray(), instead of giving me 3 arrays i just get the above result.
I really don't have a very good understanding of PHP but following the php documentation I don't see what I am doing wrong.
I'm very close to finish the app, this is the only big problem I couldn't solve by now, and it is really upsetting me. Thanks!
EDIT:
JSONParser
else if(method.equals("GET")){
// request method is GET
if (sbParams.length() != 0) {
url += "?" + sbParams.toString();
}
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept-Charset", charset);
conn.setConnectTimeout(15000);
conn.connect();
is = conn.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + '\n');
}
is.close();
json = sb.toString();
System.out.println(json.toString() + "This is the json");
} 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());
}catch (NullPointerException ex){
System.out.println("No internet");
}
return jObj;
}
conn.disconnect();
return jObj;
}
You need array_push where $pet pushed in array and print that array.
use,
<?php
$arr=array();
foreach($dbh->query($query) as $row){
$pet["id"] = $row['id'];
$pet["name"] = $row['name'];
$pet["breed"] = $row['breed'];
$response["pet"] = array_push($arr,$pet);
}
print_r($arr);
?>
You need to encode the final array structure once, encoding in your loop results in invalid json in the end as you will have multiple concatenated json strings.
The easiest way to get that, is to select only the fields you want:
$query = "SELECT id, name, breed FROM lost_pets";
$result = $dbh->prepare($query);
$result->execute();
echo json_encode($result->fetchAll(PDO::FETCH_ASSOC));
exit;
If you need a pet or pets key somewhere inbetween, you might need a loop but you can assign the rows at once just the same; no need to assign the individual fields.
I used below function in all my apps to get data from php & json arrays. Try this.
public void ParseJsonArray(json){ //json is the json array you got. pass it to this function. this can get specific data from json array.
try {
JSONArray jsonArray = json.getJSONArray("pet"); //get all data
int count = 0;
//if you have more columns & you want to get specific columns.
while (count<jsonArray.length()){
JSONObject JO = jsonArray.getJSONObject(count); //get data row by row.
String s1 = JO.getString("id"); //get id value to string s1.
String s2 = JO.getString("name"); //get name to string s2.
String s3 = JO.getString("breed"); //get breed to string s3.
count++; }
} catch (JSONException e) {
e.printStackTrace(); }
}
Below is the method in which I use to send data to PHP
public String createUser(String url,String method,List<Pair<String, String>> params){
//Making Http request
HttpURLConnection httpURLConnection = null;
StringBuffer response = null;
String lineEnd = "\r\n";
try{
if(method.equals("POST")){
URL urlPost = new URL(url);
httpURLConnection = (HttpURLConnection) urlPost.openConnection();
httpURLConnection.setDoOutput(true); //defaults request method to POST
httpURLConnection.setDoInput(true); //allow input to this HttpURLConnection
httpURLConnection.setUseCaches(false);
httpURLConnection.setRequestMethod("POST");
//httpURLConnection.setRequestProperty("Content-Type","application/json");
//httpURLConnection.setRequestProperty("Host", "192.168.0.101");
httpURLConnection.connect();
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
wr.writeBytes(params.toString());
//wr.writeBytes("user_email="+userEmailText);
//wr.writeBytes(lineEnd);
wr.flush(); //flush the stream when we're finished writing to make sure all bytes get to their destination
wr.close();
InputStream is = httpURLConnection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
}
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response.toString();
}
In my AsyncTask class:
params.add(new Pair<>("user_name", userNameText));
params.add(new Pair<>("user_email", userEmailText));
HttpHandler sh = new HttpHandler();
String jsonStrUserCreation = sh.createUser(url,"POST",params);
System.out.println("userNameText: " + userNameText);
System.out.println("userEmailText: " + userEmailText);
Log.e(TAG, "Response from userCreationURL: " + jsonStrUserCreation);
try{
JSONObject jsonObj = new JSONObject(jsonStrUserCreation);
} catch (JSONException e) {
e.printStackTrace();
}
Below is my PHP code:
<?php
require_once 'connecttodb.php';
$db = new DB();
$con = $db->db_connect();
if(isset($_POST['user_name']) && isset($_POST['user_email'])){
$user_name = $_POST['user_name'];
$user_email = $_POST['user_email'];
$sql = "INSERT INTO user_details(user_name,user_email) VALUES('$user_name','$user_email')";
$run = mysqli_query($con,$sql);
if($run){
$response["success"] = 1;
$response["message"] = "Account successfully created";
echo json_encode($response);
}else{
$response["success"] = 0;
$response["message"] = "Account failed to be created";
echo json_encode($response);
}
}else{
$response["success"] = 2;
$response["message"] = "Failed to run inner code";
echo json_encode($response);
}
The script always return "Failed to run inner code" when I have passed in the values for user_name and user_email.
Found the solution as below. Make sure that your string is in the format below
String urlParameters = "user_name="+userNameText+"&user_email="+userEmailText;
And then call it as below:
sh.createUser(url,urlParameters);
You will see the magic.
I trying to send this json data form android to php server.
this my json data{email:"user111#gmail.com",password:"00000"},
any one help how the decode this json data in php server
this my php server code
<?php
$response = array();`
require_once __DIR__ . '/db_connect.php';`
if(!isset($_POST['params'])){
$decoded=json_decode($_POST['params'],true)
$email=json_decode['email'];
$pass=json_decode['password'];
// connecting to db
$db = new DB_CONNECT();`
$result = mysql_query("SELECT *FROM user WHERE email = $email");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {`
$result = mysql_fetch_array($result);
$this->mylog("email".$email.",password".$pass);
if($pass==$result[password]){
echo " password is correct";
$response["code"]=0;
$response["message"]="sucess";
$response["user_id"]=$result["userid"];
$response["firstname"]=$result["fname"];
$response["lastname"]=$result["lname"];
echo json_encode($response);
}else{
$response["code"]=3;
$response["message"]="invalid password and email";
echo json_encode($response);
}
}else {
// required field is missing
$response["code"] = 1 ;
$response["message"] = "no data found";
// echoing JSON response
echo json_encode($response);
}
}
}else {
// required field is missing
$response["code"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response); }?>
**this my android code json praser **
public JSONObject loginUser(String email, String password) {
Uri.Builder loginURL2 = Uri.parse(web).buildUpon();
loginURL2.appendPath("ws_login.php");
JSONObject loginJSON = new JSONObject();
try {
loginJSON.put("email", email);
loginJSON.put("password", password);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject json = jsonParser.getJSONFromUrl(loginURL2.toString(),
loginJSON);
return json;
}
this my android json data send function
public JSONObject getJSONFromUrl(String url, JSONObject params) {
// Making HTTP request
try {
// defaultHttpClient
// boolean status=isNetworkAvailable();
HttpParams param = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(param, 10000);
HttpConnectionParams.setSoTimeout(param, 10000);
DefaultHttpClient httpClient = new DefaultHttpClient(param);
HttpPost httpPost = new HttpPost(url);
StringEntity se = new StringEntity(params.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
CONTENT_TYPE_JSON));
httpPost.setEntity(se);
Log.d("URL Request: ", url.toString());
Log.d("JSON Params: ", params.toString());
HttpResponse httpResponse = httpClient.execute(httpPost);
int code = httpResponse.getStatusLine().getStatusCode();
if (code != 200) {
Log.d("HTTP response code is:", Integer.toString(code));
return null;
} else {
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (ConnectTimeoutException e) {
// TODO: handle exception
Log.e("Timeout Exception", e.toString());
return null;
} catch (SocketTimeoutException e) {
// TODO: handle exception
Log.e("Socket Time out", e.toString());
return null;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
} catch (ClientProtocolException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
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();
Log.d("Content: ", sb.toString());
} catch (Exception e) {
Log.e("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) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jObj;
}
public boolean isNetworkAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
return false;
}
If $_POST['params'] is a JSON encoded string, you only have to call json_decode once, not the multiple times that you have shown.
$decoded = json_decode($_POST['params'], true);
// Decoded is now an array of the JSON data
$email = $decoded['email'];
$pass = $decoded['password'];
It should be noted that the string in your question is not valid JSON, as email and password need to be quoted, as well.
You can do live testing of the json_decode function here:
http://php.fnlist.com/php/json_decode
You can validate your JSON here:
http://jsonlint.com
I am echoing a json set of results back to android:
$result = mysql_query($query) or die(mysql_error());
$resultNo = mysql_num_rows($result);
// check for successful store
if ($result != null) {
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
return json_encode($rows);
} else {
return false;
}
}
But when I try to convert the string to a JSONObject at the other end i get:
11-13 22:18:41.990: E/JSON(5330): "[{\"email\":\"fish\"}]"
11-13 22:18:41.990: E/JSON Parser(5330): Error parsing data org.json.JSONException: Value [{"email":"fish"}] of type java.lang.String cannot be converted to JSONObject
I have tried this with a larger result set and thought that it would be something to do with null values however trying it as above with just one value still returns an error.
Any help greatly appreciated
EDIT:
Android methods...
public JSONObject searchPeople(String tower) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", search_tag));
params.add(new BasicNameValuePair("tower", tower));
// getting JSON Object
JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
// return json
return json;
}
JSON Parser class...
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
// 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, "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();
Log.e("JSON", json);
} 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;
}
As #MikeBrant mentioned above, you need to pass through JSONArray first.
Replace this:
//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());
}
With this:
// try parse the string to a JSON object
try {
JSONArray jArray = new JSONArray(json);
for(i=0; i < jArray.length(); i++) {
JSONObject jObj = jArray.getJSONObject(i);
Log.i("jObj", "" + jObj.toString());
// Parsing example
String email = jObj.getString("email");
Log.i("email", email);
}
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
PHP w/ str_replace:
$result = mysql_query($query) or die(mysql_error());
$resultNo = mysql_num_rows($result);
// check for successful store
if ($result != null) {
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
$json_string = json_encode($rows);
$json_string = str_replace("\\", "", $json_string, $i);
return $json_string;
} else {
return false;
}
}
$result = mysql_query($query) or die(mysql_error());
$resultNo = mysql_num_rows($result);
// check for successful store
if ($result != null) {
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
return json_encode($rows);
} else {
return false;
}
I think it's just your braces
What you are passing to JSONObject is in fact an array with a single object in it.
JSONObjectis expecting the syntax to be only representative of a single object containing key-value pairs (i.e. properties).
You need to not pass an array for this to work, or you need to use JSONArray to decode the JSON.
I had similar problem when I needed to pass json data from php to java app, this solved my problem:
$serialliazedParams = addslashes(json_encode($parameters));
You need to escape certain characters added by PHP, as well as substring your json string to cut out the additional characters at the front of the returned string.
One way to do it is like so:
ANDROID/JAVA code
JSONObject response = new JSONObject(responseString.substring(responseString.indexOf('{'),responseString.indexOf('}') +1).replace("\\",""));
You should do it a bit more neatly, but the point is that you have to ensure that the string you're passing in has no hidden characters, and to replace the first """ character with nothing as it can cause the exception.
I have an android application that requests data from my mysql database. This works fine but when I try to send a parameter for how many items to retrieve I get nothing.
This is my java code:
result = "";
client = new DefaultHttpClient();
post = new HttpPost("http://www.XXX.XXXX.XX/XX.php");
nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("itemsToGet", itemsToGet));
try {
post.setEntity((new UrlEncodedFormEntity(nameValuePairs)));
response = client.execute(post);
entity = response.getEntity();
inputStream = entity.getContent();
} catch (UnsupportedEncodingException e) {
Log.e(TAG, e.toString());
} catch (ClientProtocolException e) {
Log.e(TAG, e.toString());
} catch (IOException e) {
Log.e(TAG, e.toString());
}
try {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream ,"iso-8859-1"), 8);
stringBuilder = new StringBuilder();
String line = null;
while((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
inputStream.close();
result = stringBuilder.toString();
} catch (UnsupportedEncodingException e) {
Log.e(TAG, e.toString());
} catch (IOException e) {
Log.e(TAG, e.toString());
}
try {
JSONArray jsonArray = new JSONArray(result);
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
Log.i(TAG, object.getString("namn") + " " + i);
}
} catch (JSONException e) {
Log.e(TAG, e.toString());
}
And this is my server side PHP code:
<?php
mysql_connect("XXX.XXX.com", "XXX", "XXX") or die(mysql_error());
mysql_select_db("XXXXXXX") or die(mysql_error());
$data = mysql_query("SELECT * FROM artikel") or die(mysql_error());
$itemsToGet = intval($_POST['itemsToGet']);
$counter = 0;
while($info = mysql_fetch_array( $data ) && $counter < $itemsToGet)
{
$databaseInfo[] = $info;
$counter++;
}
print(json_encode($databaseInfo));
?>
I solved it. The condition in the while-loop was incorrect.
while($info = mysql_fetch_array( $data ) && $counter < $itemsToGet)
It should be
while(($info = mysql_fetch_array( $data )) && ($counter < $itemsToGet))