We'll be using the following stuff.
- GSON library, a java library by Google to deserialize JSON strings to java POJOs. Download the jar from here: https://code.google.com/p/google-gson/
- a free geonames.org JSON webservice. The webservice API is here: http://www.geonames.org/export/JSON-webservices.html#citiesJSON
- a free JSON-to-java converter, JSONgen. http://jsongen.byingtondesign.com/
Tutorial
Create a new Android project, with a MainActivity class inside. Create a "libs" folder inside the project, and put the GSON jar in there. When you refresh the project, Eclipse should automatically add the jar to the project's build path.
Let's have our activity extend ListActivity instead of Activity.
public class MainActivity extends ListActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
Now let's look at the "citiesJSON" webservice API.
Webservice Type : REST
Url : api.geonames.org/citiesJSON?
Parameters :
north,south,east,west : coordinates of bounding box
callback : name of javascript function (optional parameter)
lang : language of placenames and wikipedia urls (default = en)
maxRows : maximal number of rows returned (default = 10)
Result : returns a list of cities and placenames in the bounding box, ordered by relevancy (capital/population). Placenames close together are filterered out and only the larger name is included in the resulting list.
Webservice Type : REST
Url : api.geonames.org/citiesJSON?
Parameters :
north,south,east,west : coordinates of bounding box
callback : name of javascript function (optional parameter)
lang : language of placenames and wikipedia urls (default = en)
maxRows : maximal number of rows returned (default = 10)
Result : returns a list of cities and placenames in the bounding box, ordered by relevancy (capital/population). Placenames close together are filterered out and only the larger name is included in the resulting list.
We'll call the webservice with the 4 coordinates parameters. The webservice also requires an "username" parameter. You can use the "pimentoso" user for this test, or you can register your own username here: http://www.geonames.org/login
Go to the JSONgen website, and paste the sample URL for the webservice.
When you hit "generate", the website will have you download a zip file containing the generated classes. Unzip the file and copy the classes in your project. The classes will look like this
Go to the JSONgen website, and paste the sample URL for the webservice.
package com.example.placesjson;
import java.util.List;
public class GeonameList {
private List<Geonames> geonames;
public List<Geonames> getGeonames() {
return this.geonames;
}
public void setGeonames(List<Geonames> geonames) {
this.geonames = geonames;
}
}
package com.example.placesjson;
public class Geonames {
private String countrycode;
private String fcl;
private String fclName;
private String fcode;
private String fcodeName;
private Number geonameId;
private Number lat;
private Number lng;
private String name;
private Number population;
private String toponymName;
private String wikipedia;
[... getters and setters]
Now we're gonna work on the activity. We're going to create the "callService()" method that does the main job: starting a thread that calls the webservice, and deserialize the data. The comments in the code should be self-explanatory.
private void callService() {
// Show a loading dialog.
dialog = ProgressDialog.show(this, "Loading", "Calling GeoNames web service...", true, false);
// Create the thread that calls the webservice.
Thread loader = new Thread() {
public void run() {
// init stuff.
Looper.prepare();
cities = new GeonameList();
boolean error = false;
// build the webservice URL from parameters.
String wsUrl = "http://api.geonames.org/citiesJSON?lang=en&username=pimentoso";
wsUrl += "&north="+COORD_N;
wsUrl += "&south="+COORD_S;
wsUrl += "&east="+COORD_E;
wsUrl += "&west="+COORD_W;
String wsResponse = "";
try {
// call the service via HTTP.
wsResponse = readStringFromUrl(wsUrl);
// deserialize the JSON response to the cities objects.
cities = new Gson().fromJson(wsResponse, GeonameList.class);
}
catch (IOException e) {
// IO exception
Log.e(TAG, e.getMessage(), e);
error = true;
}
catch (IllegalStateException ise) {
// Illegal state: maybe the service returned an empty string.
Log.e(TAG, ise.getMessage(), ise);
error = true;
}
catch (JsonSyntaxException jse) {
// JSON syntax is wrong. This could be quite bad.
Log.e(TAG, jse.getMessage(), jse);
error = true;
}
if (error) {
// error: notify the error to the handler.
handler.sendEmptyMessage(CODE_ERROR);
}
else {
// everything ok: tell the handler to show cities list.
handler.sendEmptyMessage(CODE_OK);
}
}
};
// start the thread.
loader.start();
}
The code contains the "readStringFromUrl()" utility method which is not covered in this guide. Please download the project zip at the end of this post to grab the code.
When the thread has completed, the "cities" object shoud contain data returned from the webservice.
This is the simple handler that's called at the end of the method.
// This handler will be notified when the service has responded.
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
dialog.dismiss();
if (msg.what == CODE_ERROR) {
Toast.makeText(MainActivity.this, "Service error.", Toast.LENGTH_SHORT).show();
}
else if (cities != null && cities.getGeonames() != null) {
Log.i(TAG, "Cities found: " + cities.getGeonames().size());
buildList();
}
}
};
The last thing that remains is to actually populate the list, so let's write the "buildList()" method.
private void buildList() {
// init stuff.
List<Map<String, String>> data = new ArrayList<Map<String, String>>();
Map<String, String> currentChildMap = null;
String line1;
String line2;
// cycle on the cities and create list entries.
for (Geonames city : cities.getGeonames()) {
currentChildMap = new HashMap<String, String>();
data.add(currentChildMap);
line1 = city.getToponymName() + " (" + city.getCountrycode() + ")";
line2 = "Population: " + city.getPopulation();
currentChildMap.put("LABEL", line1);
currentChildMap.put("TEXT", line2);
}
// create the list adapter from the created map.
adapter = new SimpleAdapter(this, data, android.R.layout.simple_list_item_2,
new String[] { "LABEL", "TEXT" },
new int[] { android.R.id.text1, android.R.id.text2 });
setListAdapter(adapter);
}
Let's wrap it all up, by calling "callService()" when the activity is started.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
callService();
}
The final result should be something like this.
Error handling
You will notice that when the webservice returns an error, a JsonSyntaxException is not actually thrown. This is because GSON only throws the exception if your class has a field whose type didn't match what is in the JSON. So, in case of an error like this-{"status":{"message":"user does not exist.","value":10}}The exception is not actually thrown. So if you want to retrieve the error message, you could expand your GeonameList class to contain a Status object, so GSON can fill it when it is returned.
You can read more about it here-
Other libraries
If GSON is a bit too heavy for you (with its almost 200KB) you can look into JSONbeans, a lighter library by EsotericSoftware.
https://github.com/EsotericSoftware/jsonbeans
https://github.com/Pimentoso/AndroidPlacesJson
Alternatively, you can download the Eclipse project ZIP here.
http://www.pimentoso.com/uploads/PlacesFromJson.zip
Download
You can get the project on Github.https://github.com/Pimentoso/AndroidPlacesJson
Alternatively, you can download the Eclipse project ZIP here.
http://www.pimentoso.com/uploads/PlacesFromJson.zip
GOOOOOD!
ReplyDeleteVery useful ... thx for download!
Existing without the answers to the difficulties you’ve sorted out through this guide is a critical case, as well as the kind which could have badly affected my entire career if I had not discovered your website
ReplyDeletefull Stack developer Training in Bangalore
Thank you a lot for providing individuals with a very spectacular possibility to read critical reviews from this site.
ReplyDeleteClick here:
python training in tambaram
Click here:
python training in annanagar
Have you been thinking about the power sources and the tiles whom use blocks I wanted to thank you for this great read!! I definitely enjoyed every little bit of it and I have you bookmarked to check out the new stuff you post
ReplyDeleteExcellent blog, I wish to share your post with my folks circle. It’s really helped me a lot, so keep sharing post like this
ReplyDeletejava training in annanagar | java training in chennai
java training in marathahalli | java training in btm layout
I was recommended this web site by means of my cousin. I am now not certain whether this post is written through him as nobody else recognise such precise about my difficulty. You're amazing! Thank you!
ReplyDeleteangularjs Training in bangalore
angularjs Training in btm
angularjs Training in electronic-city
angularjs online Training
angularjs Training in marathahalli
Thanks for the informative article. This is one of the best resources I have found in quite some time. Nicely written and great info. I really cannot thank you enough for sharing.
ReplyDeletepython training in velachery | python training institute in chennai
Excellent blog!!! I got to know the more useful information by reading your blog. Thanks for posting this blog.
ReplyDeleteIELTS Coaching Center in JP Nagar
IELTS Course in JP Nagar
IELTS Training in JP Nagar Bangalore
English Speaking Course in Bangalore JP Nagar
Spoken English in JP Nagar
English Speaking Classes near me
Spoken English Classes in JP Nagar Bangalore
In the beginning, I would like to thank you much about this great post. Its very useful and helpful for anyone looking for tips. I like your writing style and I hope you will keep doing this good working.
ReplyDeleteAngularjs Training Institute in Bangalore
Angularjs Classes in Bangalore
Angularjs Coaching in Bangalore
Best ccna Institute in Bangalore
ccna Institute in Bangalore
Wonderful piece of work. Master stroke. I have become a fan of your words. Pls keep on writing.
ReplyDeletelist-your-blog
Technology
Well researched article and I appreciate this. The blog is subscribed and will see new topics soon.
ReplyDeleteMicrosoft Azure online training
Selenium online training
Java online training
Java Script online training
Share Point online training
thanks and i appreciate for your blog ethical hacking online training
ReplyDeleteThank you for shairing this information about how a Android app that retrieves data from a JSON webservice.
ReplyDeletebig data training in btm
Big data training institute in btm layout
This is a very helpful blog..
ReplyDeleteThanks for sharing with us,
We are again come on your website,
Thanks and good day,
Please visit our site,
buylogo
Usually I never comment on blogs but your article is so convincing that I never stop myself to say something about it. You’re doing a great job,Keep it up.
ReplyDeleteTry Our BLACK MAGIC REMOVAL EXPERT IN TORONTO Services and Get All the benefits of it in your life, we make All your Personal problems solved in just minutes.
Good to see the Powerful contents,Keep going with the same. thank you article awesome.
ReplyDeletepython training in chennai
python online training in chennai
python training in bangalore
python training in hyderabad
python online training
python flask training
python flask online training
python training in coimbatore
Great article insisting on the subject of Mining Engineering and it's career growth helping the students who opt for it. Thanks for sharing and keep posting such an informative content.
ReplyDeleteangular js training in chennai
angular js training in tambaram
full stack training in chennai
full stack training in tambaram
php training in chennai
php training in tambaram
photoshop training in chennai
photoshop training in tambaram
Thanks for the informative article. This is one of the best resources I have found in quite some time. Nicely written and great info. I really cannot thank you enough for sharing.
ReplyDeleteangular js training in chennai
angular js training in omr
full stack training in chennai
full stack training in omr
php training in chennai
php training in omr
photoshop training in chennai
photoshop training in omr
Amazing article. Your blog helped me to improve myself in many ways thanks for sharing this kind of wonderful informative blogs in live. I have bookmarked more article from this website. Such a nice blog you are providing
ReplyDeleteJava Training in Chennai
Java Training in Velachery
Java Training inTambaram
Java Training in Porur
Java Training in Omr
Java Training in Annanagar
Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing
ReplyDeleteDigital Marketing Training in Velachery
Digital Marketing Training in Tambaram
Digital Marketing Training in Porur
Digital Marketing Training in Omr
Digital MarketingTraining in Annanagar
This information is impressive; I am inspired with your post writing style & how continuously you describe this topic. After reading your post, thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic.
ReplyDeleteDevOps Training in Chennai
DevOps Course in Chennai
Thanks for such a nice content. Apppreciate it :)
ReplyDeleteCheers
If anyone interested similar one's have a look here thanks
Glock 17 for sale cheap online without License overnight delivery (glockgunstore.com)
shih tzu puppies for sale near me
listateacuppuppies for sale online
how to buy weed online
shih tzu puppies for sale near me
have also something to share here.
teacup poodle for sale
führerschein kaufen
I loved your post.Much thanks again. Fantastic.
ReplyDeleteonline training in java
online training on java
Tül perde modelleri
ReplyDeleteSMS ONAY
mobil ödeme bozdurma
Nft nasıl alinir
ankara evden eve nakliyat
trafik sigortası
dedektör
web sitesi kurma
aşk kitapları
smm panel
ReplyDeleteSmm Panel
iş ilanları
instagram takipçi satın al
Hirdavatci
HTTPS://WWW.BEYAZESYATEKNİKSERVİSİ.COM.TR
Servis
Jeton hilesi
Thankful to you for other brilliant case. in which else should everyone gather such an information in such an optimal assistance of making?.
ReplyDeletePandora One APK
I would like to be the letter I send this morning to the one I love. I love you without limitation. Always have and alwaysHot Good Morning Messages For Girlfriend
ReplyDeleteOxford migration
ReplyDelete