Android Java jSON UTF-8 httpResponse Problems - php

I've got a problem with german characters in utf-8. I work with a MySQL database from which I'll get my data with PHP. The php script converts the data into a json object and sent it to the application. The database contains doubles and strings. First the application send a string with the name of a topic. The php search in the db for the topic, convert the content into a json and send it to the application.
I tried to sent the data without characters like "ä,ü,ö" and it work. When I'm using this german characters it stop on line
HttpResponse response =httpClient.execute(httppost);
I don't know why and what I'm doing wrong.
Here is my application code:
public void getData(String data){
String topic = data; //Parameter for PHP
String result = "";
InputStream isr = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); //PHP
nameValuePairs.add(new BasicNameValuePair("topic", topic)); //PHP
try{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.179.20:80/PHP/getData.php"); //PHP-Script on localhost
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); //PHP
HttpResponse response = httpClient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
}
catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
resultView.setText("Could not connect to database");
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
result=sb.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
try {
String s = "";
JSONArray jArray = new JSONArray(result);
for(int i=0; i<jArray.length();i++){
JSONObject json = jArray.getJSONObject(i);
double Lat = json.getDouble("Latitude");
double Lng = json.getDouble("Longitude");
String Title = new String(json.getString("Ueberschrift").getBytes("ISO-8859-1"),"UTF-8");
String ShortText = new String(json.getString("Kurzbeschreibung").getBytes("ISO-8859-1"),"UTF-8");
String LongText = new String(json.getString("Inhalt").getBytes("ISO-8859-1"),"UTF-8");
String Thema = new String(json.getString("Thema").getBytes("ISO-8859-1"),"UTF-8");
String Datum = json.getString("Date");
String Url = new String(json.getString("Url").getBytes("ISO-8859-1"),"UTF-8");
s = s +
"Latitude: "+Lat+", "+"Longitude: "+Lng+"\n"+
"Thema: "+Thema+"\n"+
"Titel: "+Title+"\n"+
"Kurzbezeichnung: "+ShortText+"\n"+
"Inhalt: "+LongText+"\n\n";
}
resultView.setText(s);
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error Parsing Data "+e.toString());
}
}
Here a part of my php:
mysql_select_db("database", $con);
mysql_query('SET CHARACTER SET utf8');
$thema = $_REQUEST['topic'];
$result = mysql_query("SELECT * FROM locations WHERE Thema='$thema'") or die('Errant query:');
while($row = mysql_fetch_assoc($result))
{
$output[]=$row;
}
//$output = serialize($output);
//$output = iconv('ISO-8859-1', 'UTF-8', $output);
if (function_exists('json_encode'))
{
echo json_encode($output);
echo "JSON Error: ".json_last_error();
}
else { echo "json_encode() is not supported"; }
mysql_close($con);
The json looks like this:
[{"id":"5","Longitude":"11.0730833333333","Latitude":"49.4530833333333","Height":"10","Ueberschrift":"Henkersteg","Kurzbeschreibung":"Der Henkersteg, auch","Inhalt":"Stadtbefestigung\u00a0| Marthakirch","Thema":"D\u00fcrer","Thema_id":"3","Datetime":"15\/02\/2015","Url":"http:\/\/de.wikipedia.org\/wiki\/Henkersteg"}]JSON Error: 0
Thanks in advance for any help.

I changed the line
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
to
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
I changed also the settings of my database. After changed them, I could display my string in the application, but unfortunately I get a "?" instead of a "ü".

Related

Retrieving image from mysql database into android

Good Day Internet!
I am trying to retrieve and display an image from mysql database into an image view (android). The image is a blob type. I have the following php code that gets the image from mysql.
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
require 'connect_aircraftoperator.php';
$image = $db->query("SELECT * FROM company");
while ($row = $image->fetch_assoc()) {
echo '<img src="data:image/png;base64,' . base64_encode($row['companyImage']) . '" />';
}
?>
Below is my android code for now with the use of JSON.
try {
//setting up the default http client
HttpClient httpClient = new DefaultHttpClient();
//specify the url and the name of the php file that we are going to use
//as a parameter to the HttpPost method
HttpPost httpPost = new HttpPost("http://10.0.2.2//aircraftoperatorapp/leimage.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//getting the response
HttpResponse response = httpClient.execute(httpPost);
//setting up the entity
HttpEntity httpEntity = response.getEntity();
//setting up the content inside an input stream reader
//lets define the input stream reader
is = httpEntity.getContent();
}
catch (Exception e) {
System.out.println("Exception 1 Caught ");
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
//create a string builder object to hold data
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line+"\n");
}
//use the toString() method to get the data in the result
fullNameResult = sb.toString();
is.close();
//checks the data by printing the result in the logcat
System.out.println("---Here's my data---");
System.out.println(fullNameResult);
}
catch (Exception e){
System.out.println("Exception 2 Caught ");
}
//result now contains the data in the form of json
//let's inflate it in the form of the list
try {
//creates json array
JSONArray jArray = new JSONArray(fullNameResult);
for (int i = 0; i < jArray.length(); i++)
{
//create a json object to extract the data
JSONObject json_data = jArray.getJSONObject(i);
imageTemp = json_data.getString("companyImage"); //gets the value from the php
}
//this line should display the image from the mysql database into an image view
}
catch (Exception e){
//System.out.println("Exception 3 Caught ");
Log.e("lag_tag", "Error Parsing Data " + e.toString());
}
Thanks in advance for any help!
First use Base64 decode the string to byte array:
byte[] data = Base64.decode(imageTemp);
Bitmap b = BitmapFactory.decodeByteArray(data,0,data.length,null);

android retrieve data from web database through http request and PHP doesn't work

I tried to retrieve data from web database through Http request. But it doesn't work.
Only when the sql string include quotation marks, it will fails. Otherwise, it works fine.
When I debug, the return string is always like :
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/content/28/8269928/html/test.php on line 12 null (id=830020201688)
Android side code:
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("strSql", "select * from user where username='test'"));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://test.com/test.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e) {
System.out.println("Connectiong Error");
}
String js = "";
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();
js = sb.toString();
System.out.println("get = " + js);
}
catch(Exception e) {
System.out.println("Error converting to String");
}
web server PHP code:
$myconn=mysql_connect("68.178.139.15", "username", "password");
mysql_select_db("dbname");
mysql_query("set names 'utf8'");
$strSql = $_REQUEST['strSql'];
$result = mysql_query($strSql, $myconn);
while($row = mysql_fetch_array($result)) {
$output[]=$row;
}
print(json_encode($output));
mysql_close();
solved
android side:
URLEncoder.encode("select * from test where name=\'test\'")
php side:
urldecode($_REQUEST['strSql']);

Json data from php server not working.

I am uplodaing data in MYSQL data base and at the same time I want to retrieve one of the attribute which I have inserted, for the satisfaction of my successful upload. when I press the button for first time then, it only upload the data to the server, and return nothing. Again when I hit the button then it does both the processs(insertion and retrieving data), so I can't return value at a first time in form of json object.
This is my php code engrdatainsert.php
<?php
$sqlCon=mysql_connect("localhost","root","");
mysql_select_db("PeopleData");
//Retrieve the data from the Android Post done by and Engr...
$adp_no = $_REQUEST['adp_no'];
$building_no = $_POST['building_no'];
$contractor_name = $_POST['contractor_name'];
$officer_name = $_POST['officer_name'];
$area = $_POST['area'];
-------------------insert the received value from an Android----------||
$sql = "INSERT INTO engrdata (adp_no, building_no,area,contractor_name,officer_name) VALUES('$adp_no', '$building_no', '$are', '$contractor_name', '$officer_name')";
//--------Now check out the transaction status of the Inserted data---------||
$q=mysql_query("SELECT adp_no FROM engrdata WHERE adp_no='$adp_no'");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));//conveting into json array
mysql_close();
?>
My Android code
public void insertdata()
{
InputStream is=null;
String result=null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
nameValuePairs.add(new BasicNameValuePair("adp_no",adp));//"34"));
nameValuePairs.add(new BasicNameValuePair("building_no",bldng));//"72"));
nameValuePairs.add(new BasicNameValuePair("area",myarea));//"72"));
nameValuePairs.add(new BasicNameValuePair("contractor_name",cntrct));//"72"));
nameValuePairs.add(new BasicNameValuePair("officer_name",ofcr));//"72"));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/androidconnection/engrdatainsert.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.i("postData", response.getStatusLine().toString());
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert the input strem into a string value
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();
result=sb.toString();
}
catch(Exception e)
{ Log.e("log_tag", "Error converting result "+e.toString()); }
try
{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++)
{
JSONObject json_data = jArray.getJSONObject(i);
Toast.makeText(this, "data is "+json_data.getString("adp_no")+"\n", Toast.LENGTH_LONG).show();
String return_val = json_data.getString("adp_no");
if(return_val!=null)
{
Intent offff=new Intent(this,MainActivity.class);
offff.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
offff.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//startActivity(offff);
}
}
}
//}
catch(JSONException e)
{ Log.e("log_tag", "Error parsing data "+e.toString()); }
// return returnString;//*/
}
In you PHP code, you are not executing the INSERT query. You need to do something like this:
-------------------insert the received value from an Android----------||
$sql = "INSERT INTO engrdata (adp_no, building_no,area,contractor_name,officer_name) VALUES('$adp_no', '$building_no', '$are', '$contractor_name', '$officer_name')";
mysql_query($sql) or die(mysql_error());
//--------Now check out the transaction status of the Inserted data---------||
Notice the line I added, which actually executes the query.
Now of course you should upgrade your code to mysqli or mysqlPDO since the PHP mysql package is not supported anymore.
If you want to use JSON in android for server purposes. like if you want to send data and retrieve a response from the server, then You have to use the JSON in accurate manner which have been defined in this link Json in Android

String cannot be converted to JSONArray

I am trying to get data from a php file.
This is my PHP code:
$sql=mysql_query("select * from `tracking`");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
And I really need all the data. This is the code I use to get and convert the data:
String result = null;
InputStream is = null;
StringBuilder sb = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://server/getData.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch(Exception e) {
Log.e("log_tag", "Error in http connection"+e.toString());
}
//convertion de la réponse en String
try {
//BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"),8);
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
//sb.append(line);
}
is.close();
result=sb.toString();
} catch(Exception e) {
Log.e("log_tag", "Error converting result "+e.toString());
}
// Affectation des données
try {
JSONArray jArray = new JSONArray(result);
Log.d("jArray", ""+jArray);
JSONObject json_data= null;
for(int i=0; i<jArray.length(); i++) {
p = new Position();
json_data = jArray.getJSONObject(i);
Log.d("js", ""+json_data);
id=json_data.getInt("id");
lat=(float) json_data.getDouble("lat");
lon=(float) json_data.getDouble("lon");
speed=(float) json_data.getDouble("speed");
alt=json_data.getDouble("alt");
time=json_data.getString("time");
date=json_data.getString("date");
p.setId(id);
p.setLat(lat);
p.setLon(lon);
p.setSpeed(speed);
p.setAlt(alt);
p.setDate(date);
p.setTime(time);
datasource.createPosition(p);
}
} catch(JSONException e1) {
Log.e("JSONEX", ""+e1);
} catch (ParseException e1) {
e1.printStackTrace();
}
This really works on emulator nicely but not on my android phone and I don't get the reason.
Now this is my json result from the server:
[{"id":"180","lat":"33.894707","lon":"-6.327312","speed":"0.00000","alt":"397","date":"29/07/2012","time":"23:44"}]
It's a valid JSONArray validated on http://jsonlint.com/
I found what was wrong with JSON.
I found at the beginning a character "?" added somewhere in the code and it was not visible until I stored the logCat entry to a file. So I added the code line and it works fine now.
result = result.substring(1);
I hope it may help someone in the future thanx to Waqas
Put this lines:
while(result.charAt(0)!='[') //or result.charAt(0)!='{'
{
result = result.substring(1);
Log.d("Tag1", "remove 1st char");
}
after:
result = sb.toString();
To become like this:;
result = sb.toString();
while(result.charAt(0)!='[')
{
result = result.substring(1);
Log.d("Tag1", "remove 1st char");
}

Problems with json.GetJSONArray("?") in Android

I am trying to get my code work. I want to make a mysql connection
and send the data with json to my android app.
I guess it almost works but my logcat gives me this warning almost at the end:
"error parsing data" value [{"staff_phone":"123","staff_name":"fabian" etc.
I guess i did something wrong in my sql script. This is the script:
mysql_connect($db_host,$db_user,$db_pwd);
mysql_select_db($database);
$result = mysql_query("SELECT * FROM contactlijst");
$array = array();
while ($row = mysql_fetch_assoc($result))
{
array_push($array, $row);
}
print json_encode($array);
mysql_close();
These are my java codes:
public static JSONObject getJSONfromURL(String url){
//initialize
InputStream is = null;
String result = "";
JSONObject jArray = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
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();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//try parse the string to a JSON object
try{
jArray = new JSONObject(result);
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return jArray;
} }
AND this one:
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
//Get the data (see above)
JSONObject json =
Database.getJSONfromURL("http://fabian.nostradamus.nu/Android/getcontactinfo.php");
try{
JSONArray contactinfo = json.getJSONArray("contactlijst");
//Loop the Array
for(int i=0;i < contactinfo.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = contactinfo.getJSONObject(i);
map.put("voornaam", e.getString("staff_name"));
map.put("achternaam", e.getString("staff_lastname"));
map.put("geboortedatum", e.getString("staff_dateofbirth"));
map.put("adres", e.getString("staff_address"));
map.put("postcode", e.getString("staff_address_postal"));
map.put("woonplaats", e.getString("staff_address_city"));
map.put("email", e.getString("staff_email"));
map.put("telefoon", e.getString("staff_phone"));
mylist.add(map);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
So what am I doing wrong?
Thanks alot!
getJSONArray() expects to be given a key whose value is an array. So it expects JSON that looks more like this:
{"contactlijst": [{"staff_phone":"123","staff_name":"fabian"...
If this doesn't work, try validating your JSON to ensure it is formatted correctly. I often use JSONLint for that purpose.

Categories