I have a problem with my first Android App. I want to ask a PHP server for a name and image, using an cardid. This works well, but JSONArray throws an exception when I try to split up the long string I get. This is the method I use on the Android device:
public static Object[] getIdCardOwner(String card)
{
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb=null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("cardid",card));
Object returnValue[] = new Object[2];
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(SERVER_URL);
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,"utf-8"), 16);
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();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//paring data
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
returnValue[0] = json_data.getString("name");
returnValue[1] = json_data.getString("image");
}
}
catch(JSONException e1){
Log.e("log_tag", "Error converting result "+e1.toString());
} catch (ParseException e1) {
e1.printStackTrace();
}
return returnValue;
}
This is the String result I get before the exception happens:
{"0":"4016612622","card":"4016612622","1":"Peter Poulsen","name":"Peter Poulsen","2":"\/9j\/4QAYRXhpZgAASUkqAAgAAAAAAAAAAAAAAP\/sABFEdWNreQABAAQAAAAeAAD\/4QMpaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLwA8P3hwYWNrZXQgYmVnaW49Iu+7vyIgaWQ9Ilc1TTBNcENlaGlIenJlU3pOVGN6a2M5ZCI\/PiA8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcHRrP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ciobdxICPXAO8PRtSnUJECTqPuiEgYyySsaNVnJJeUm7OrfG4c6pBy4GWSdQV23o2YW7i0spwlEDH5LO8onfDUajoUwXghwoaNFaR10u+Fk2l+VBu6uW3rPNn\/AKBM9E6oz7Gsfo60jcyhE+IXJ2b5mQwCoxPiFa0c1nNnAx0KLoQI4ZGM8aHKeAS0joq8t2pZgrXHMZw2lNmtHiBdvIppPn0UYc3juHq3btHGrpvL4lV9bSi\/ZdonITqxFqRtiCEeC17eIZwc3j1uK6c6kNkLn8nQSN0ZDrp0Wh7pG6W2smQYqnYDcW2xZtrAYZIr+uEiMOdXadtJEz27KcYyMt2gIyPVN4vEpoidkREy1ICldIRgT1Kh7wLK2U7BkqlZieFbnJoklUTLdMlVVGfY8DBL0UoywlBTicKjEZu+qFF0IAmo1XGmzadDp9EOoWx3RxqMhVA04NOMvciWS27jI0SOByBgS10KvTEd2OqmDerlCYCcjonASPizBMrgAexTPGI3dkmV+sVOWyDKpffuLdl3k3OS5wMhULLskpKpFrByLX6qvHAD66oc2S9FOUC4bQaqtGdpZ0FSicJbEKUThMiGtjHQoOhIQ1+6hKYbGUbUbU5N11c5IRJrPuDT+7+qv1coSiM5VOsBzE9UqyudR3Vlh2TE5q8Gr\/2TE6u6VdzW1KzPft6lLJlI+RdECd2yxZyDMnslSJkWXACdFYppc6IJSbO01EJhiz\/RWBXtiyRYWwOqhs0qtIUYuubU0DCGUyauqe0KYoTNvVCfszP41BBbCEJmpCWuNU3WPmGQhNGdytMVPgqIFb6oQqMx0BU+T+6uUivoUISY0StMm8Q\/qqmTLywhClmtSeFxCFJYIQhIR\/\/Z"}
And this is the error I get:
05-14 14:13:00.723: E/log_tag(359): Error converting result org.json.JSONException: Value {"image":"\/9j\/4QAYRXhpZgAASUkqAAgAAAAAAAAAAAAAAP\/sABFEdWNreQABAAQAAAAeAAD\/4QMpaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLwA8P3hwYWNrZXQgYmVnaW49Iu+7vyIgaWQ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ciWS27jI0SOByBgS10KvTEd2OqmDerlCYCcjonASPizBMrgAexTPGI3dkmV+sVOWyDKpffuLdl3k3OS5wMhULLskpKpFrByLX6qvHAD66oc2S9FOUC4bQaqtGdpZ0FSicJbEKUThMiGtjHQoOhIQ1+6hKYbGUbUbU5N11c5IRJrPuDT+7+qv1coSiM5VOsBzE9UqyudR3Vlh2TE5q8Gr\/2TE6u6VdzW1KzPft6lLJlI+RdECd2yxZyDMnslSJkWXACdFYppc6IJSbO01EJhiz\/RWBXtiyRYWwOqhs0qtIUYuubU0DCGUyauqe0KYoTNvVCfszP41BBbCEJmpCWuNU3WPmGQhNGdytMVPgqIFb6oQqMx0BU+T+6uUivoUISY0StMm8Q\/qqmTLywhClmtSeFxCFJYIQhIR\/\/Z","2":"\/9j\/4QAYRXhpZgAASUkqAAgAAAAAAAAAAAAAAP\/sABFEdWNreQABAAQAAAAeAAD\/4QMpaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLwA8P3hwYWNrZXQgYmVnaW49Iu+7vyIgaWQ9Ilc1TTBNcENlaGlIenJlU3pOVGN6a2M5ZCI\/PiA8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm
Can anyone tell me, what I'm doing wrong and how to fix it?
Thanks in advance
Peter
The data they're supplying for json_data.getString("image") is not a string.
It's an image.
Check the JSON manually. It it's outputting image data then you need to get them to change the JSON. E.g. it should look like this:
"src": "Images/theImage.png",
Related
Microsoft Academic provided an API to get some general information from Microsoft academic. The response type is a Json Object. Using org.Json and following code, I have tried to read the response object but I have failed (need to download these jars + common-logging and common-codec) :
URIBuilder builder = new URIBuilder("https://api.projectoxford.ai/academic/v1.0/evaluate?");
builder.setParameter("expr", "Composite(AA.AuN=='jaime teevan')");
builder.setParameter("count", "100");
builder.setParameter("attributes", "Ti,CC");
URI uri = builder.build();
HttpGet request = new HttpGet(uri);
request.setHeader("Ocp-Apim-Subscription-Key", "Your-Key");
HttpClient httpclient = HttpClients.createDefault();
HttpResponse response = httpclient.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
JSONObject obj = new JSONObject(entity);
JSONArray arr = obj.getJSONArray("entities");
for (int i = 0; i < arr.length(); i++){
String post_id = arr.getJSONObject(i).getString("Ti");
System.out.println(post_id);
}
System.out.println(EntityUtils.toString(entity));
}
Which returns the following exception:
Exception in thread "main" org.json.JSONException: JSONObject["entities"] not found.
at org.json.JSONObject.get(JSONObject.java:471)
at org.json.JSONObject.getJSONArray(JSONObject.java:618)
How to fix this?
EDIT
Although it is easy to see an example of the response from the link I provided at the beginning of my question (Microsoft Academic), but for ease of readers I show it in here:
{
"expr": "Composite(AA.AuN=='jaime teevan')",
"entities":
[
{
"logprob": -15.08,
"Ti": "personalizing search via automated analysis of interests and activities",
"CC": 372,
},
{
"logprob": -15.389,
"Ti": "the perfect search engine is not enough a study of orienteering behavior in directed search",
"CC": 237,
}
]
}
Seems like the problem to me is you are not converting your response to string , you need to convert your response to string before passing it to JSONObject
HttpEntity entity = response.getEntity();
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
entity.writeTo(os);
} catch (IOException e1) {
}
String contentString = new String(os.toByteArray());
or other way is
InputStream instream = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String contentString = sb.toString(); // you can pass sb.toString() directly to jsonobject as well
and now pass contentString to JSONObject
JSONObject obj = new JSONObject(contentString);
JSONArray arr = obj.getJSONArray("entities");
Update : your can also use this which is also suggested by #Ömer Fadıl Usta
but i would strongly recommend to use HttpURLConnection for security and performance
Try to pass string JsonData to JSONObject :
if (entity != null) {
String jsonData = EntityUtils.toString(entity);
JSONObject obj = new JSONObject(jsonData);
........
.....
}
What i am doing:
I am trying to make a reverse geocoding in android
I am getting error as::
java.lang.IllegalArgumentException: Illegal character in query at index 59: http://maps.google.com/maps/api/geocode/json?address=Agram, Bengaluru, Karnataka, India&sensor=false
NOte: that request gets a json response in browser but not from my class below
This line is giving this error::
HttpGet httpget = new HttpGet(url);
JSONfunctions.java
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "";
JSONObject jArray = null;
// Download JSON data from URL
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
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 {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
Use URLEncoder.encode() to encode the value of your address parameter "Agram, Bengaluru, Karnataka, India" before putting it in the URL string so that it becomes something like
http://maps.google.com/maps/api/geocode/json?address=Agram,+Bengaluru,+Karnataka,+India&sensor=false
i.e. spaces changed to + and other special octets represented as %xx.
Browsers do smart URL encoding for strings entered in the address bar automatically so that's why it works there.
Build your url like,
final StringBuilder request = new StringBuilder(
"http://maps.googleapis.com/maps/api/geocode/json?sensor=false");
request.append("&language=").append(Locale.getDefault().getLanguage());
request.append("&address=").append(
URLEncoder.encode(locationName, "UTF-8"));
I am using httpclient 4.3.3
String messagestr = "Welcome to Moqui World";
String url="http://my.example.com/api/sendhttp.phpauthkey="+URLEncoder.encode("17djssnvndkfjb110d3","UTF-8")+"&mobiles=91"+URLEncoder.encode(contactNumber,"UTF-8")+"&message="+URLEncoder.encode(messagestr,"UTF8")+"&sender="+URLEncoder.encode("WMOQUI","UTF-8")+"&route=4";
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
It's working fine for me. I hope this may help you.
I have a MySQL database with one unique table: geopoints, that has 3 columns: id, lat and long, and this table is filled up with 4 entrys already, 4 values of lat and long (1E6 because its to use on a mapview).
My objective is to mark on a mapview all these 4 geopoints dynamicly using a php script that generates json array, and with a httpPost etc...
This is the code I have so far:
getjson = (Button) findViewById(R.id.button1);
getjson.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();//Whats this for?
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(
"http://????????.com/????/getGeopoints.php");
HttpResponse response = httpclient.execute(httpPost);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error connecting to http " + e.toString());
}
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
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());
}
try {
jArray = new JSONArray(result);
for (int i = 0; i <= jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag", "id: " + json_data.getInt("id")
+ ", latitude: " + json_data.getInt("lat")
+ ", longitude: " + json_data.getInt("long"));
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
});
This is the php file:
<?php
mysql_connect("?????.com", "username", "password");
mysql_select_db("database_name");
$q = mysql_query("SELECT * FROM geopoints");
while ($e = mysql_fetch_assoc($q))
$output[] = $e;
print(json_encode($output));
mysql_close();
?>
I have this file running right because as I enter the url on a browser it generates the exact json array with the exact information I want.
There is only think I don't understand, what's HttpEntity for? Because I followed up a tutorial, and in there it uses an array with information to filter from the db, as I don't want to filter any info (I want all the database table entrys, not just one or two) I just leaved it blank.
What's wrong with my code?
The error I get in logcat is all the catch messages "11-29 12:47:29.662: E/log_tag(898): Error connecting to http Http android.os.NetworkOnMainThreadException".
android.os.NetworkOnMainThreadException
android >= 3.0 does not allow Network request on main UI thread. you need to use AsyncTask to call network request.
That's because you're are blocking the main UI thread. Try to use AsyncTasks for Http requests.
I'm using a MySQL database and php for my java/android app.
I haven't got any experience with php.
this is my php file (getAllDataFromSomeTable.php)
<?php
mysql_connect("someHosturl","someUsername","somePassword");
mysql_select_db("databasename");
$q=mysql_query("SELECT * FROM sometable");
while($e=mysql_fetch_assoc($q))
$output[]= $e;
print(json_encode($output));
mysql_close();
?>
and i work with HttpPosts and stuff like that in Java.
This way i can get all the data from 'sometable'
but if i want to use a different query like "select top 1 from sometable where username = 'thisuser'" for example. How can i change that dynamically in java?
How should my php file look and how should the code in java look?
this is the code i have now:
String result = "";
List<? extends NameValuePair> licenses = (List<? extends NameValuePair>) new ArrayList<DriversLicense>();
InputStream is = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://some-url.com/getAllDataFromSomeTable.php");
httpPost.setEntity(new UrlEncodedFormEntity(licenses));
HttpResponse response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.d("httpclient tag", e.getMessage());
}
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();
Log.d("result is", result);
}catch(Exception e){
Log.d("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);
Log.d("from jsonObject", "id= " + json_data.getInt("Id") + ", number = "
+json_data.getString("Number"));
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
Why don't you try adding parametes to the request?
For example:
http://some-url.com/getAllDataFromSomeTable.php?table=difftable&whereField.1=username&whereValue.1=xyz&whereField.2=surname&whereValue.2=Smith
This way you would need to parse these parameters and build a query based on the passed data.
I'm thinking that the above request would make this query:
select * from difftable where username = 'xyz' and surname ='Smith'
On the other hand, this is what webservices are for, so i would think about something like that, if possible.
currently, i retrieve data from database is like that
private void getdatafromphp(){
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/video.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);
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();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//paring data
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
json_data = jArray.getJSONObject(jArray.length()-1);
url=json_data.getString("VideoUrl");
}catch(JSONException e1){
}catch(ParseException e1) {
e1.printStackTrace();
}
}
with this php
<?php
mysql_connect("localhost","root","");
mysql_select_db("imammuda");
$sql=mysql_query("select * from Video");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>
now i want insert data into database. how to do that?
I had found the sql command which is "insert into table (column1, column2) values ('value1', 'value2')".
This is insert with constant values which is type in php.
What i want is from java there get input from user then copy this input into php 'value1' after that run the php to update the database.
Depending on whether you are using Get or Post
i will assume GET
$value = $_GET['value']; // this will retrieve the value from the url and save it in a variable
mysql_connect("localhost","root","");
// escape the value first
$value = mysql_real_escape_string($value);
mysql_select_db("imammuda");
$result = mysql_query("insert into Video (value) values ('$value')");
?>
learn more about working with the db here
UPDATE
to know the correct request method you can use this.
$req;
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$req = $_GET;
}else {
$req = $_POST;
}
now you can use $req as your request variable:
$value = $req['value'];