Json data from php server not working. - php

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

Related

Android Java jSON UTF-8 httpResponse Problems

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 "ü".

How to get a count value from server into json in android?

I am trying to retrieve the number of rows in my server table using json parsing and php in android.
I have done the following coding in php and I am getting the value also, but I don 't know how to proceed with the json. Please guide me step by step what to do or where I am going wrong. My codes and error logs are as follows:
php code:
<?php
mysql_connect("localhost","user","pswd");
mysql_select_db("demo");
$username= (isset($_POST['receivenumber'])) ? $_POST['receivenumber'] : '';
$q=mysql_query("SELECT COUNT(receivenumber) FROM `addtasknew` where `receivenumber` = '$username'") or die(mysql_error());
$row=mysql_fetch_assoc($q);
print (json_encode($row));
mysql_close();
?>
json codes in android
String result = null;
InputStream is = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.mydomainname.org/task/getmytaskcount.php");
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
// String h="123";
//nameValuePairs.add(new BasicNameValuePair("to",h.toString()));
nameValuePairs.add(new BasicNameValuePair("receivenumber","9595959595"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("log_tag", "connection success "+nameValuePairs);
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection "+e.toString());
Toast.makeText(getActivity(), "Connection fail", Toast.LENGTH_SHORT).show();
}
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,HTTP.UTF_8),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result=sb.toString();
Log.e("log_tag", "result "+result.toString());
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
Toast.makeText(getActivity(), " Input reading fail", Toast.LENGTH_SHORT).show();
}
try
{
// I don't know wht to do here to get the count value
JSONArray jArray = new JSONArray(result);
Log.w("Lengh",""+jArray);
}
catch(JSONException e)
{
Log.e("log_tag", "Error parsing data "+e.toString());
Toast.makeText(getActivity(), "JsonArray fail", Toast.LENGTH_SHORT).show();
}
error logs:
E/log_tag(2386): result ?{"COUNT(receivenumber)":"2"}
E/log_tag(2386): Error parsing data org.json.JSONException: Value {"COUNT(receivenumber)":"2"} of type org.json.JSONObject cannot be converted to JSONArray
You are trying to interpret your JSON as a JSONArray but it's a JSONObject.
To retrieve your value try this:
JSONObject jObj = new JSONObject(result);
String count= jObj.getString("COUNT(receivenumber)");
You can check this tutorial to learn more about JSON in android.
Try this
try {
JSONObject jObj = new JSONObject(result);
Log.i("COUNT",jObj.getString("COUNT") + " COUNT");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and change the sql query like
"SELECT COUNT(receivenumber) as COUNT FROM addtasknew where receivenumber = '$username'";

android app wrote to get place name of id 2 php gives null

I was trying out this code but it gives null. where it should be giving me the place name. what seems to be the problem in my code? i want to get place details by giving the place ID. But i debugged too, it was always returning null
Code
String result = "";
InputStream is = null;
// the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("place_id", "2"));
// http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://example.com/getAllPeopleBornAfter.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());
}
// 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());
}
// parse json data
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
TextView z = (TextView)findViewById(R.id.textView1);
z.setText(json_data.getString("place_id"));
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
});
PHP
<?php
include "db_config.php";
$q=mysql_query("SELECT 'name' FROM places WHERE place_id='".$_REQUEST['place_id']."'");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
mysql_close();
?>
Too less information to help. Are you sure your PHP script returns anything? What logging of http response shows? Maybe it is all fine with your code and null is what you should get as problem lurks elsewhere?
BTW: your PHP code is very bad. You are open to exploitation with SQL Injection and in general you should always check if query (or fopen or anything) succeeded before you try to consume expected data it should return, as there is NO guarantee all went fine. Habit of error checking is crucial to solid software development. I also recomment to not use "?>" if it is just pure PHP script file, not mixed with HTML or anything (mixing is bad too).
THIS IS THE ANSWER
ref.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String result = "";
InputStream is = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("place_id", "3"));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://hopscriber.com/test.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());
}
// 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());
}
// parse json data
String version = null;
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
version = json_data.getString("name");
Toast.makeText(getBaseContext(), version,
Toast.LENGTH_LONG).show();
TextView x = (TextView) findViewById(R.id.textView1);
x.setText(version);
}
} catch (JSONException e1) {
Toast.makeText(getBaseContext(), version, Toast.LENGTH_LONG)
.show();
} catch (ParseException e1) {
e1.printStackTrace();
}
}
});
php
<?php
include "db_config.php";
$query = mysql_query("SELECT * FROM places WHERE place_id='".mysql_real_escape_string($_POST[place_id])."'");
while($e=mysql_fetch_assoc($query))
$output[]=$e;
print(json_encode($output));
mysql_close();
?>
thanx all for the help

Problems with multiple queries between Android, PHP and JSON

I have to do a few queries to get all the information I need from the database. It's around 7 queries. If I do it with just one it works perfectly, but when I try to add more i get an error.
Here's my PHP code.
<?php
//connection etc
$sql="SELECT * FROM paramedic";
$result=mysql_query($sql) or die(mysql_error());
$sql2="SELECT * FROM doctor";
$result2=mysql_query($sql2) or die(mysql_error());
while($row=mysql_fetch_array($result))
$output[]=$row;
while($rows=mysql_fetch_array($result2))
$output2[]=$rows;
print(json_encode(array($output, $output2)));
mysql_close();
?>
Here is my android code:
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Check Login
String username = etUsername.getText().toString().trim();
String passwrd = etPassword.getText().toString().trim();
try{
httpclient=new DefaultHttpClient();
httppost= new HttpPost("websitegoesher.php");
nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("user1",username));
nameValuePairs.add(new BasicNameValuePair("pass1",passwrd));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response=httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Eror at httpost "+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 "+e.toString());
}
//Parse JSON data
try{
jArray = new JSONArray(result);
for(int i =0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
if(!json_data.getString("paramedic_serial").equals(null))
Log.i("log_tag","paramedic_license: "+json_data.getString("paramedic_serial"));
// if(!json_data.getString("dr_serial").equals(null)) Log.i("log_tag","dr_serial: "+json_data.getString("dr_serial"));
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
So when I receive and try to run it, I get this error
11-18 02:26:28.905: E/log_tag(27401): Error parsing data org.json.JSONException: Value [{"3":"1","2":"passwrd","inst_serial":"1","passwrd":"passwrd","username":"carlis","1":"carlis","paramedic_license":"123443","paramedic_serial":"100","0":"100","email":"gusti#upr.edu","5":"123443","4":"gusti#upr.edu"},{"3":"23","2":"passwrd","inst_serial":"23","passwrd":"passwrd","username":"paramedic","1":"paramedic","paramedic_license":"123111","paramedic_serial":"111","0":"111","email":"paramedic#aki.com","5":"123111","4":"paramedic#aki.com"},{"3":"23","2":"bb","inst_serial":"23","passwrd":"bb","username":"aa","1":"aa","paramedic_license":"1234","paramedic_serial":"138","0":"138","email":"email#email.com","5":"1234","4":"email#email.com"}] at 0 of type org.json.JSONArray cannot be converted to JSONObject
Thanks in advance.
your code in php:
print(json_encode(array($output, $output2)));
You are making mistake here. I think your output is something like: {{{"":"","":""}}}
You need to write your code like this:
$output3[]=array_merge($output,$output2);
print(json_encode($output3));
Put this code instead of above and try. Now check out. Hope this helps.

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