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')");
Related
This is my java code
public void login() {
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://192.168.0.104/rocket/assign_job.php"); // make sure the url is correct.
//add your data
nameValuePairs = new ArrayList<NameValuePair>(1);
// Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
//int smsNum = Integer.parseInt(smsCode.getText().toString());
nameValuePairs.add(new BasicNameValuePair("smsCode", smsCode));// $Edittext_value = $_POST['Edittext_value'];
//nameValuePairs.add(new BasicNameValuePair("userName", rocketName));
Log.d("smsCode ===", smsCode);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
//response=httpclient.execute(httppost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
runOnUiThread(new Runnable() {
public void run() {
Log.d("PHP Response: ", response);
pDialog.dismiss();
}
});
if (response.equalsIgnoreCase("success")) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(UserPage.this, "Job Assigned", Toast.LENGTH_SHORT).show();
}
});
} else {
showAlert();//testing bitbuckettt
}
} catch (Exception e) {
pDialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
This is my PHP Code:
<?php
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
if(isset($_POST['smsCode'])){
$smsCode = $_POST['smsCode'];
$query_search = "SELECT * FROM confirmedrequest WHERE smsCode='".$smsCode."'";
$query_exec = mysqli_query($db->getConnection(),$query_search) or die(mysqli_error($db->getConnection()));
$row = mysqli_num_rows($query_exec);
if($row == 0){
echo "failed";
}else{
echo "success";
$rocketName = mysqli_real_escape_string($db->getConnection(),$_POST["userName"]);
$sql_update = "UPDATE confirmedrequest SET jobTakenBy = '$rocketName' WHERE smsCode = $smsCode ";
$sql_exec = mysqli_query($db->getConnection(),$sql_update) or die(mysqli_error($db->getConnection()));
}
}else{
echo "Empty code";
}
?>
The PHP Response in logcat is always failed even though the code matches. I have tried to debug it for several hours but still cant solve. All I want is to run the code below (response.equalsIgnoreCase("success")) when the code matches.
You have to set the headers in order to the response to be formatted in a correct way:
$db = new DB_CONNECT();
if(isset($_POST['smsCode'])){
$smsCode = $_POST['smsCode'];
$query_search = "SELECT * FROM confirmedrequest WHERE smsCode='".$smsCode."'";
$query_exec = mysqli_query($db->getConnection(),$query_search) or die(mysqli_error($db->getConnection()));
$row = mysqli_num_rows($query_exec);
if($row == 0){
http_response_code(500);
echo "failed";
}else{
http_response_code(200);
echo "success";
$rocketName = mysqli_real_escape_string($db->getConnection(),$_POST["userName"]);
$sql_update = "UPDATE confirmedrequest SET jobTakenBy = '$rocketName' WHERE smsCode = $smsCode ";
$sql_exec = mysqli_query($db->getConnection(),$sql_update) or die(mysqli_error($db->getConnection()));
}
}else{
http_response_code(400);
echo "Empty code";
}
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 have to send byte array using Http post method,but in basicnamevalue pair class its gives
me error as the constructor BasicNameValuePair(String, byte[]) is undefined.is any onother way to solved this issue please help me.
AsyncTask :
public void SaveDatandImage() {
Byte[] image1,image2;
new AsyncTask<Void, Void, String>() {
protected void onPreExecute() {
pDialog = new ProgressDialog(DetailsAcceptActivity.this);
pDialog.setTitle("Sending Query");
pDialog.setMessage("Please Wait...");
pDialog.setCancelable(true);
pDialog.show();
};
protected String doInBackground(Void... params) {
String response = null;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
Date today = new Date();
nameValuePairs.add(new BasicNameValuePair("name","Name"));
nameValuePairs.add(new BasicNameValuePair("image1",image1));
nameValuePairs.add(new BasicNameValuePair("image2",image2));
if (Common.isInternetConnected(DetailsAcceptActivity.this)) {
try {
response = Common.httpPost(url_make_query, nameValuePairs, new String[] {});
// Jobj=jparser.makeHttpRequest(url_make_query, "POST", nameValuePairs);
Log.v(Common.TAG, "Record respose : " + response);
Intent intent = new Intent(DetailsAcceptActivity.this, LoginActivity.class);
DetailsAcceptActivity.this.finish();
startActivity(intent);
//Toast.makeText(MenuActivity.this,"Record Saved",Toast.LENGTH_SHORT).show();
/*JSONObject jObj = new JSONObject(response);
strRespCode = jObj.getString("success");
strRespMessage=jObj.getString("message");
int success=Jobj.getInt(TAG_SUCCESS);
if(success==1) {
Toast.makeText(MenuActivity.this,"inserted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MenuActivity.this,"Error", Toast.LENGTH_SHORT).show();
}*/
//if(response.e)
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
//groupMember.setSynced_with_server(StaticMembers.ZERO);
return "NO_NETWORK";
}
return response;
};
protected void onPostExecute(String result) {
if (result != null) {
if(!result.equals("NO_NETWORK")) {
//groupMember.setSynced_with_server(StaticMembers.ONE);
}
//Log.w("strRespMessage= "+strRespMessage, "********");
// Toast.makeText(MenuActivity.this, "Query Sent!!", Toast.LENGTH_LONG).show();
//finish();
}
pDialog.dismiss();
}
}.execute(null, null);
}
PHP Script to accept data from front end
<?php
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['sender_mobile_no'])) {
$name = $_POST['name'];
$image1= $_POST['image1'];
$image2= $_POST['image2'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
// mysql inserting a new row
$result = mysqli_query($con,"INSERT INTO tbl_query_master(name,image1,image2) VALUES('$name','$sender_name', '$image1', '$image2')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Order placed successfully.";
// 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);
}
?>
You can encode your image bytes into String and then send it on server. You can use
String strImage=Base64.encodeToString(image1, Base64.DEFAULT); // image1 is your byte[]
and then set this String in your namevaluepair as
nameValuePairs.add(new BasicNameValuePair("image1",strImage));
In php:
you can decode your string to get bytearray as follows.
$str=$_POST['image1'];
$abc=base64_decode($str);
I have an android app.
I want to send a get request to the get_categories.php file.
In the get_categories.php file I want to
$query_categories = "SELECT category_name FROM categories";
and return all the categories found in that table into a json array.
How can I do that?
This is my incomplete code:
if (!empty($_GET)) {
$query_categories = "SELECT category_name FROM categories";
$success = false;
try{
$sth = $connection->prepare($query_categories);
//$sth->execute(array(':user_id' => $user_id));
//$user_items_count = $sth->rowCount(); - these are lines from other php file I've used
foreach($)//??
$success = true;
} catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = $ex;
die(json_encode($response));
$connection = null;
}
if($success) {
$response["success"] = 1;
$response["message"] = "Kylie";
die(json_encode($response));
$connection = null;
} else {
$response["success"] = 2;
$response["message"] = "something went wrong";
die(json_encode($response));
$connection = null;
}
} else {
$response["success"] = 3;
$response["message"] = "Another brick in the wall";
echo json_encode($response);
$connection = null;
}
Later on, in my Java code, how do I decode that?
Usually up until this point, in my other JSON transfers, I've received normal Json object with no arrays and read them this way:
setUserLastSeen(json.getString(TAG_USER_LAST_SEEN)); //for example.
But how do I decode an array?
For php side this how you can get the categories array and make json,for prepared statements this is how you can accomplish
$success = false;
try {
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$success = true;
}
catch(PDOException $e) {
$response["success"] = 0;
$response["message"] = 'Connection failed: ' . $e->getMessage();
$response["data"]=null;
die(json_encode($response));
}
$query_categories = "SELECT category_name FROM categories";
try{
$sth = $sth->prepare($query_categories );
$success = true;
} catch(PDOException $e) {
$response["success"] = 0;
$response["message"] = 'Prepare failed: ' . $e->getMessage();
$response["data"]=null;
die(json_encode($response));
}
try{
$sth->execute();
$success = true;
} catch(PDOException $e) {
$response["success"] = 0;
$response["message"] = 'Execute failed: ' . $e->getMessage();
$response["data"]=null;
die(json_encode($response));
}
$categories = $sth->fetchAll(PDO::FETCH_COLUMN, 0);/* fetches all categories from db */
/* Output of $query_categories
Array
(
[0] => cat1
[1] => cat2
[2] => cat3
[3] => cat4
)
*/
/* json encode $query_categories
["cat1","cat2","cat3","cat4"]
*/
/* check if categories exist or not*/
if(empty($categories)){
$response["success"] = 0;
$response["message"] = "No categories found";
$response["data"]=null;
die(json_encode($response));
$connection = null;
}
if($success) {
$response["success"] = 1;
$response["message"] = "Kylie";
$response["data"]=$categories;
die(json_encode($response));
$connection = null;
/* output
{"success":0,"message":"Kylie","data":["cat1","cat2","cat3","cat4"]}
*/
} else {
$response["success"] = 2;/* don't where you are setting success to 2*/
$response["message"] = "something went wrong";
$response["data"]=null;
die(json_encode($response));
$connection = null;
}
} else {
$response["success"] = 3;/* don't where you are setting success to 3*/
$response["message"] = "Another brick in the wall";
$response["data"]=null;
die(json_encode($response));
$connection = null;
}
I am not good at java but here is the reference How to parse a JSON and turn its values into an Array?
/* store json string in the_json */
JSONObject myjson = new JSONObject(the_json);
JSONArray the_json_array = myjson.getJSONArray("data");
Note: make sure on java side you must check the success from json which
must be ==1 and the_json_array is not null
PHP Data Objects
you can use below code to ferch data using json and then decode that json array:
=================================================================================
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("your webservice");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse res = httpclient.execute(httppost);
HttpEntity entity = res.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result=sb.toString();
Log.d("Data",""+ result);
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
}
String fd_ono=null;
try
{
JSONArray jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++)
{
json_data = jArray.getJSONObject(i);
fd_ono=json_data.getString("your column name");
textView.settext(fd_ono.toString());
}
}
catch(JSONException e1)
{
Toast.makeText(getBaseContext(), "Record not found", Toast.LENGTH_LONG).show();
}
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".