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.
Related
I am trying to use Json for an android online db connection. Problem is no matter what i try i get the ever so popular Unexpected character (<) at position 0 error.
here is my method:
public void getData(){
String result = "";
InputStream isr = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http:link to my file.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());
resulString="Couldn't connect to database";
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(newInputStreamReader(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());
}
//parse json data
try {
String s = "";
JSONParser parser_obj = new JSONParser();
JSONArray jArray = (JSONArray) parser_obj.parse(result.toString());
for(int i=0; i<jArray.length();i++){
JSONObject json = jArray.getJSONObject(i);
s = s +
"Id : "+json.getInt("Id")+" Name: "+json.getString("ShopName")+"\n"+
"Icon : "+json.getInt("ShopIcon")+"Description:"+json.getString("ShopDesc")+"\n\n";
}
resulString=s;
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error Parsing Data "+e.toString());
}
}
tried both get and post methods
heres my php file:
!php1
the connection is established but theres no result and loggcat displays that error.
Can you help me please?
After 2 days I finally found the solution:
simply added these 2 headers:
request.setHeader("Accept", "application/json"); // or application/jsonrequest
request.setHeader("Content-Type", "application/json");
also make sure that the url in your HTTP is perfect.
And this was of awesome help for testing the connection:
http://www.requestmaker.com
HI I have this code to retrieve a mysql database but there is an error when it comes to parsing the info. I think its because the information is in one string,
#Override
protected Void doInBackground(String... params) {
String result = "";
InputStream is = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://cs1.ucc.ie/~am32/getDB.php");
//httppost.setEntity(new UrlEncodedFromEntity(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();
sb.append(reader.readLine() + "\n");
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
result=sb.toString();
Log.i("json string", result);
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try{
List<String> myList= new ArrayList<String>(Arrays.asList(result.split(" ")));
JSONArray jArray = new JSONArray(myList);
System.out.println("Length"+ jArray.length());
Log.d("DB","Length"+jArray.length());
for(int i=0; i<jArray.length(); i++){
JSONObject json_data = null;
json_data = jArray.getJSONObject(i);
int id = i +1;
//String title = json_data.getString("Title");
double latitude = json_data.getDouble("Lat");
double longitude = json_data.getDouble("Lon");
//Adds proximity to POI's
ProxAlert inst = new ProxAlert();
inst.addProximityAlert(latitude,longitude, id);
//
inst.saveCoordinatesInPreferences((float)latitude, (float)longitude);
//prints to logCat
System.out.println(id+"&"+latitude+"&"+longitude);
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
Log.e("log_tag","Failed data as:\n"+result);
}
return null;
}
and the logCat reads
09-04 19:13:13.997: E/log_tag(28100): Error parsing data org.json.JSONException: Value at 0 of type java.lang.String cannot be converted to JSONObject
In your code, you doing http request (http://cs1.ucc.ie/~am32/getDB.php) and getting content like this
51.899429 -8472801 51.898525 -8.472176 51.899522 -8.47293 51.899495 -8.472844 51.899456 -8.472823 51.899628 -8.473016 51.899442 -8.47278 51.89931 -8.472587 51.808514 -8.472248 51.899174 -8.472649 51.899469 -8.472823 51.8932045 -8.500971 51.893623 -8.501472
This is not a valid Json.
For check Json Validation use JsonLint .
[EDIT]
Please read some Json Document first for better understanding.
Here android-json-parsing-tutorial is a good tutorial which explains Json parsing with example.
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");
}
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
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.