I am trying to retrieve multiple rows of data. However, I am getting a error.
I want to retrieve rows of which the name (under the column name) = the name of the user. Which part of my code do I have to alter?
protected String doInBackground(String... args) {
// Building Parameters
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_coupons, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String couponexpires = c.getString(TAG_COUPONEXPIRES);
String coupondetails = c.getString(TAG_COUPONDETAILS);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_COUPONEXPIRES, couponexpires);
map.put(TAG_COUPONEXPIRES, coupondetails);
// adding HashList to ArrayList
couponsList.add(map);
My php code
<?php
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
if (isset($_GET["name"])) {
$name= $_GET['name'];
$result = mysql_query("SELECT * FROM coupons WHERE name = '$name'") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
$response["products"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product["couponcreated"] = $row["couponcreated"];
$product["couponexpires"] = $row["couponexpires"];
$product["coupondetails"] = $row["coupondetails"];
array_push($response["products"], $product);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No products found";
// echo no users JSON
echo json_encode($response);
}
?>
My logcat
5202-5251/info.androidhive.loginandregistration E/JSON Parser﹕ Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
12-21 11:24:50.750 5202-5251/info.androidhive.loginandregistration W/dalvikvm﹕ threadid=11: thread exiting with uncaught exception (group=0x41b9f700)
12-21 11:24:50.755 5202-5251/info.androidhive.loginandregistration E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NullPointerException
at info.androidhive.loginandregistration.CouponPageActivity$LoadAllProducts.doInBackground(CouponPageActivity.java:103)
at info.androidhive.loginandregistration.CouponPageActivity$LoadAllProducts.doInBackground(CouponPageActivity.java:76)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
There is syntax error in script(if condition not closed). use below script:
<?php
// array for JSON response
$response = array();
$response["success"] = 0;
$response["message"] = "No products found";
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
if (isset($_GET["name"])) {
$name = $_GET['name'];
$result = mysql_query("SELECT * FROM coupons WHERE name = '$name'") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
$response["products"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product["couponcreated"] = $row["couponcreated"];
$product["couponexpires"] = $row["couponexpires"];
$product["coupondetails"] = $row["coupondetails"];
array_push($response["products"], $product);
}
// success
$response["success"] = 1;
$response["message"] = '';
} else {
// no products found
// echo no users JSON
}
}
echo json_encode($response);
?>
Related
I'm trying to store Arabic characters in a database on server. But when I add something it will be displayed as ???????????? in the database! I tried too add from my php to check if the problem from the php file, but it added the text correctly in database. So the error from android and json, how can I make the encoding of json to utf8 in android?
Here's my code:
class AddStories extends AsyncTask<String, String, String> {
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Caregiver_ID", ID));
params.add(new BasicNameValuePair("Title", "قصة"));
params.add(new BasicNameValuePair("Story", "قصتي بدأت عندما"));
JSONObject json = jsonParser.makeHttpRequest(url_add_story,"POST", params);
Log.d("Create Response", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
suc=1;
sucess();
}
else {
suc=0;
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
PHP for adding:
<?php
header("Content-Type: text/html; charset=utf-8");
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['Caregiver_ID']) && isset($_POST['Title'])&& isset($_POST['Story'])) {
$Caregiver_ID = $_POST['Caregiver_ID'];
$Title = $_POST['Title'];
$Story = $_POST['Story'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
mysql_query("SET NAMES 'utf8'"); mysql_query('SET CHARACTER SET utf8');
// mysql inserting a new row
$result = mysql_query("INSERT INTO Stories(Caregiver_ID, Title, Story) VALUES('$Caregiver_ID', '$Title','$Story')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "glossary successfully created.";
// echoing JSON response
echo json_encode($response,JSON_UNESCAPED_UNICODE );
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response );
}
?>
Also when I tried to retrieve from android I got this for the text:
نةيىؤتيلالاؤتيلاارلابارابي-الالالتعا
while its retrieved correctly in php.
PHP code
<?php
header("Content-Type: text/html; charset=utf-8");
$response = array();
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
$result = mysql_query("SELECT *FROM Stories ") or die(mysql_error());
mysql_query("SET NAMES 'utf8'"); mysql_query('SET CHARACTER SET utf8');
if (mysql_num_rows($result) > 0) {
$response["story"] = array();
while ($row = mysql_fetch_array($result)) {
$story = array();
$story ["Caregiver_ID"] = $row["Caregiver_ID"];
$story ["Title"] = mb_convert_encoding($row["Title"],'HTML-ENTITIES','utf-8');
$story ["Story"] = mb_convert_encoding($row["Story"],'HTML-ENTITIES','utf-8');
array_push($response["story"], $story);
}
$response["success"] = 1;
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No locations found";
// echo no users JSON
echo json_encode($response);
}
?>
Try below code in android
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
byte[] buffer = new byte[1024];
int nread;
while ((nread = stream.read(buffer)) > 0) {
baos.write(buffer, 0, nread);
}
} catch (ClientProtocolException | IOException e) {
}
//Create a JSON from the String that was return.
JSONObject jsonObject = new JSONObject();
try {
String jsonText = new String(baos.toByteArray(), StandardCharsets.UTF_8);
jsonObject = new JSONObject(jsonText);
You have to put N before the columns which you need to add the Arabic text.
For example N'مختار'.
According to your code,you should change this line
$result = mysql_query("INSERT INTO Stories(Caregiver_ID, Title, Story) VALUES('$Caregiver_ID', '$Title','$Story')");
........
.....
...
to be
$result = mysql_query("INSERT INTO Stories(Caregiver_ID, Title, Story) VALUES('$Caregiver_ID', N'$Title',N'$Story')");
I am developing an Android app which is based on a custom soft keyboard and
contains different languages.
How do I convert these php files to utf8?
create_product.php
<html>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<body>
<?php
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['name']) && isset($_POST['price']) && isset($_POST['description'])) {
$name = $_POST['name'];
$price = $_POST['price'];
$description = $_POST['description'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
mysql_query("SET NAMES UTF8");
$result = mysql_query("INSERT INTO products(name, price, description) VALUES('$name', '$price', '$description')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Product successfully created.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
</body>
</html>
get_all_products.php
<html>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<body>
<?php
/*
* Following code will list all the products
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// get all products from products table
mysql_query("SET NAMES UTF8");
$result = mysql_query("SELECT *FROM products") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["products"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product["pid"] = $row["pid"];
$product["name"] = $row["name"];
$product["price"] = $row["price"];
$product["description"] = $row["description"];
$product["created_at"] = $row["created_at"];
$product["updated_at"] = $row["updated_at"];
// push single product into final response array
array_push($response["products"], $product);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No products found";
// echo no users JSON
echo json_encode($response);
}
?>
</body>
</html>
get_product_detail.php
<html>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<body>
<?php
/*
* Following code will get single product details
* A product is identified by product id (pid)
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for post data
mysql_query("SET NAMES UTF8");
if (isset($_GET["pid"])) {
$pid = $_GET['pid'];
// get a product from products table
$result = mysql_query("SELECT *FROM products WHERE pid = $pid");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$product = array();
$product["pid"] = $result["pid"];
$product["name"] = $result["name"];
$product["price"] = $result["price"];
$product["description"] = $result["description"];
$product["created_at"] = $result["created_at"];
$product["updated_at"] = $result["updated_at"];
// success
$response["success"] = 1;
// user node
$response["product"] = array();
array_push($response["product"], $product);
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?></body></html>
update_product.php
<html>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<body>
<?php
/*
* Following code will update a product information
* A product is identified by product id (pid)
*/
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['pid']) && isset($_POST['name']) && isset($_POST['price']) && isset($_POST['description'])) {
$pid = $_POST['pid'];
$name = $_POST['name'];
$price = $_POST['price'];
$description = $_POST['description'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql update row with matched pid
$result = mysql_query("UPDATE products SET name = '$name', price = '$price', description = '$description' WHERE pid = $pid");
// check if row inserted or not
if ($result) {
// successfully updated
$response["success"] = 1;
$response["message"] = "Product successfully updated.";
// echoing JSON response
echo json_encode($response);
} else {
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
</body></html>
delete_product.php
<html>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<body>
<?php
/*
* Following code will delete a product from table
* A product is identified by product id (pid)
*/
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['pid'])) {
$pid = $_POST['pid'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql update row with matched pid
$result = mysql_query("DELETE FROM products WHERE pid = $pid");
// check if row deleted or not
if (mysql_affected_rows() > 0) {
// successfully updated
$response["success"] = 1;
$response["message"] = "Product successfully deleted";
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?></body></html>
JSONparser.java
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 = "";
// 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 == "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 == "GET"){
// request method is 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 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;
}
}
Well if it is an encoding error like you say, you can use Notepad++ (which if you don't have it, get it). In the settings of the file, you would go to:
Encoding > Encode in UTF-8 (without BOM) at the top of the page.
This is what I use, so if it is an encoding error, this would fix it.
I am having an issue where my json object array isn't passing the values. I know they are there, but I can't get them to pass into the variables in my android app.
The Java function to handle the JSONObject:/**
* Function to get all userlogs
**/
public JSONObject getUserLogs(String userid){
// userlogs JSONArray
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", getUserLogs_tag ));
params.add(new BasicNameValuePair("userid", userid));
JSONObject json = jsonParser.getJSONFromUrl(getAllUserLogs,params);
return json;
}
Here is the Java do in backgrond:
protected String doInBackground(String... args) {
//List<NameValuePair> params = new ArrayList<NameValuePair>();
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
HashMap<String,String> user = new HashMap<String, String>();
user = db.getUserDetails();
userid = user.get("uid");
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.getUserLogs(userid);
Log.d("All userlogs: ", json.toString());
// return json;
try {
if (json.getString(KEY_SUCCESS) != null) {
userlogs = json.getJSONArray(KEY_USERLOGS);
// looping through All Products
for (int i = 0; i < userlogs.length(); i++) {
JSONObject c = userlogs.getJSONObject(i);
// Storing each json item in variable
String userID = c.getString(KEY_USERID);
String medname = c.getString(KEY_MEDNAME);
String medtaken = c.getString(KEY_MEDTAKEN);
String tabsleft = c.getString(KEY_TABSLEFT);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_USERID, userid);
map.put(KEY_MEDNAME, medname);
map.put(KEY_MEDTAKEN, medtaken);
map.put(KEY_TABSLEFT, tabsleft);
// adding HashList to ArrayList
logList.add(map);
}
}
}
catch (JSONException e) {
e.printStackTrace();
}
return null;
}
Here is the results:
03-20 04:47:01.212: E/JSON(7034): {"tag":"getUserLogs","success":1,"error":0,"userlogs":[{"userlogs":{"userid":"3705","medname":"atorvastatin 20mg","medtaken":"2014-03-20 03:48:49","tabsleft":"30"}},{"userlogs":{"userid":"3705","medname":"atorvastatin 20mg","medtaken":"2014-03-20 03:55:54","tabsleft":"30"}}]}
03-20 04:47:01.212: D/All userlogs:(7034): {"error":0,"success":1,"userlogs":[{"userlogs":{"userid":"3705","medtaken":"2014-03-20 03:48:49","tabsleft":"30","medname":"atorvastatin 20mg"}},{"userlogs":{"userid":"3705","medtaken":"2014-03-20 03:55:54","tabsleft":"30","medname":"atorvastatin 20mg"}}],"tag":"getUserLogs"}
03-20 04:47:01.212: W/System.err(7034): org.json.JSONException: No value for userid
03-20 04:47:01.212: W/System.err(7034): at org.json.JSONObject.get(JSONObject.java:355)
03-20 04:47:01.212: W/System.err(7034): at org.json.JSONObject.getString(JSONObject.java:515)
03-20 04:47:01.212: W/System.err(7034): at com.jipe.medicationstation.UserlogListActivity$LoadAllLogs.doInBackground(UserlogListActivity.java:104)
03-20 04:47:01.212: W/System.err(7034): at com.jipe.medicationstation.UserlogListActivity$LoadAllLogs.doInBackground(UserlogListActivity.java:1)
03-20 04:47:01.212: W/System.err(7034): at android.os.AsyncTask$2.call(AsyncTask.java:288)
03-20 04:47:01.212: W/System.err(7034): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
03-20 04:47:01.212: W/System.err(7034): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
03-20 04:47:01.212: W/System.err(7034): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
03-20 04:47:01.212: W/System.err(7034): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
03-20 04:47:01.212: W/System.err(7034): at java.lang.Thread.run(Thread.java:841)
The PHP:
else if ($tag == 'getUserLogs') {
$userid = $_POST['userid'];
//Special case (normally conntections handled in functions/config or connect)
$link = new mysqli($host, getDBuser(), getDBpassword(), getDBname());
/* check connection */
if (mysqli_connect_errno()) {
$response["error"] = 1;
$response["error_msg"] = mysqli_connect_error();
echo json_encode($response);
}
$query = "SELECT * FROM userlog WHERE userid = '$userid'";
$result = mysqli_query($link, $query);
$row_cnt = mysqli_num_rows($result);
//If results, then
if( $row_cnt > 0){
$response["userlogs"] = array();
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)){
$userlog = array();
$userlog["userlogs"]["userid"] = $row["userid"];
$userlog["userlogs"]["medname"] = $row["medname"];
$userlog["userlogs"]["medtaken"] = $row["medtaken"];
$userlog["userlogs"]["tabsleft"] = $row["tabsleft"];
array_push($response["userlogs"], $userlog);
}
$response["success"] = 1;
echo json_encode($response);
mysqli_close($link);
}
else {
// userlogs not found
// echo json with error = 1
$response["error"] = 1;
$response["error_msg"] = "No Userlogs found";
echo json_encode($response);
}
}
else {
$response["error"] = 3;
$response["error_msg"] = "JSON ERROR";
echo json_encode($response);
}
}
Any suggestions?
You have
"userlogs": [ // jsonarray userlogs
{ // json object node
"userlogs": { // json object userlogs
Then
userlogs = json.getJSONArray(KEY_USERLOGS); // fine
for (int i = 0; i < userlogs.length(); i++) {
JSONObject c = userlogs.getJSONObject(i);
But you have a JSONObject userlogs also
JSONObject userlogsobject = c.getJSONObject("userlogs");
String userID = userlogsobject.getString(KEY_USERID);
I'm trying to read one row from my database table "cond" using the ID of the row. In this case I only have one row with the ID=1. The problem is that this code always returns that $result is empty. I've been trying to fix it for a long time and I tried to do it with PDO or mysqli too but my knowledge of coding is really limited. How can I get the read the row properly?
This is my php code:
$response = array();
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
if (isset($_GET["pid"])) {
$pid = $_GET['pid'];
$result = mysql_query("SELECT *FROM cond WHERE id = $pid");
if (!empty($result)) {
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$product = array();
$product["id"] = $result["id"];
$product["name"] = $result["name"];
$product["mon"] = $result["mon"];
$product["tue"] = $result["tue"];
$product["wed"] = $result["wed"];
$product["thu"] = $result["thu"];
$product["fri"] = $result["fri"];
$product["sat"] = $result["sat"];
$product["sun"] = $result["sun"];
$product["version"]=$result["version"];
// success
$response["success"] = 1;
// user node
$response["product"] = array();
array_push($response["product"], $product);
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found. Result=0";
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found.Result=empty";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
And this is the java code:
List<NameValuePair> params2 = new ArrayList<NameValuePair>();
params2.add(new BasicNameValuePair("pid", "1"));
JSONObject json = jsonParser.makeHttpRequest(url_product_detials, "GET", params2);
Log.d("Single Product Details", json.toString());
Thanks!
Edit: Using suggested PDO
After being suggested to use PDO I uploaded the next code:
<?php
$id=$_POST["pid"];
try {
require_once 'conf.php';
$conn = mysqlConnector();
$stmt = $conn->prepare('SELECT * FROM cond WHERE id = :id');
$stmt->execute(array('id' => $id));
$result = $stmt->fetchAll();
if ( count($result) ) {
foreach($result as $row) {
echo json_encode($result);
}} else {
echo "No rows returned.";
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
But now I get this error:
Error parsing data org.json.JSONException: End of input at character 0 of
threadid=12: thread exiting with uncaught exception (group=0x40cd7930)
FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.NullPointerException
at com.goout.ListClubs$GetProductDetails.doInBackground(ListClubs.java:456)
at com.goout.ListClubs$GetProductDetails.doInBackground(ListClubs.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
... 4 more
Activity com.goout.ListClubs has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{410fb410 V.E..... R......D 0,0-480,144} that was originally added here
android.view.WindowLeaked: Activity com.goout.ListClubs has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{410fb410 V.E..... R......D 0,0-480,144} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:354)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:216)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:281)
at com.goout.ListClubs$GetProductDetails.onPreExecute(ListClubs.java:435)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at com.goout.ListClubs.onCreate(ListClubs.java:87)
at android.app.Activity.performCreate(Activity.java:5104)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2262)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358)
at android.app.ActivityThread.access$600(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1247)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5227)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
at dalvik.system.NativeStart.main(Native Method)
So I guess the php code is wrong?
An empty response means there was error in the query.
Mysql won't tell you what was the error unless asked explicitly. So, you have to always check the result of every mysql function interacting with server and if result is FALSE - check mysql_error().
Also, you are using outdated mysql library. Quit it and start using PDO, which has built-tin error reporting.
You said you database name is cond. Then what is your table name in the database?
mysql_* is deprecated. Try the following
$mysqli = new mysqli("localhost", "username", "password", "cond");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($result = $mysqli->query("SELECT *FROM table_name WHERE id = $pid")) {
/* determine number of rows result set */
$row_cnt = $result->num_rows;
if ($row_cnt>0)
{
while ($row = $result->fetch_row())
{
$product = array();
$product["id"] = $result["id"];
$product["name"] = $result["name"];
$product["mon"] = $result["mon"];
$product["tue"] = $result["tue"];
$product["wed"] = $result["wed"];
$product["thu"] = $result["thu"];
$product["fri"] = $result["fri"];
$product["sat"] = $result["sat"];
$product["sun"] = $result["sun"];
$product["version"]=$result["version"];
// success
$response["success"] = 1;
// user node
$response["product"] = array();
array_push($response["product"], $product);
// echoing JSON response
echo json_encode($response);
}
}
else
{
// no product found
$response["success"] = 0;
$response["message"] = "No product found. Result=0";
// echo no users JSON
echo json_encode($response);
/* close result set */
}
$result->close();
}
From http://php.net/manual/en/mysqli-result.num-rows.php
I get following error:
Error parsing data org.json.JSONException: Value [] of type org.json.JSONArray cannot be converted to JSONObject
Here is the Android and PHP code I have:
private void eventUpdatePoint(String eventStatus,int lat,int lon){
JSONParser jsonParserEUP = new JSONParser();
try
{
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("longtitude", Integer.toString(lon)));
params.add(new BasicNameValuePair("latitude", Integer.toString(lat)));
params.add(new BasicNameValuePair("eventstatus", eventStatus));
String url_updatePoint = "http://10.0.2.2/android_connect/event_update_point.php";
JSONObject json = jsonParserEUP.makeHttpRequest(url_updatePoint,"POST", params);
Log.d("Response", json.toString());
}
catch(Exception e)
{
e.printStackTrace();
Log.d("ERROR:","ERROR:" + e.getClass().getName() + ":" + e.getMessage());
}
}
php code:
$response = array(); if (isset($_POST['longtitude']) && isset($_POST['latitude']) &&isset($_POST['eventstatus'])) {
$longtitude = $_POST['longtitude'];
$latitude = $_POST['latitude'];
$eventstatus = $_POST['eventstatus'];
$e_id=0;
$score=0;
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
$result = mysql_query("SELECT id FROM cordinates WHERE longtitude=$longtitude AND latitude=$latitude") or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$e_id = $row["id"];
}
$result = mysql_query("SELECT score FROM point WHERE e_id=$e_id") or die(mysql_error());
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$score = $row["score"];
}
if($eventstatus=="inc")
{
$score+=10;
$result = mysql_query("UPDATE point SET score=$score where e_id=$e_id") or die(mysql_error());
$response["success"] = 1;
$response["message"] ="Score point increased";
}
else if($eventstatus=="dec")
{
$score-=10;
$result = mysql_query("UPDATE point SET score=$score where e_id=$e_id") or die(mysql_error());
$response["success"] = 0;
$response["message"] ="Score point decreased";
}
}
echo json_encode($response);
What am I doing wrong?
The webservice you are using returns a JSONArray. You have to use an object of type JSONArray to store it. You can't use a JSONObject.
Change this line:
JSONObject json = jsonParserEUP.makeHttpRequest(url_updatePoint,"POST", params);
...to this:
JSONArray json = jsonParserEUP.makeHttpRequest(url_updatePoint,"POST", params);
Log your response.If it starts with"[" and ends with "]",you have to store it in variable of type "JSONArray".With attention to your log,your response must be a "JSONArray",so simply save your response in a variable of type "JSONArray".