Friday, 18 October 2013

Taking Screenshot of a layout in android programatically

Here is a brief explanation on how to save part of screen as an image – taking screenshot programmatically !

Example :

For Screen :

 Output :
Screenshot as image

Tuesday, 4 June 2013

JSON Parsing in Android

JSON parsing is just a cakewalk once you are familiar with JSON format

Generally JSON response consists of :

1.)  Objects
2.)  Array of Objects

Each object has its attributes as name : value pair.
Object, called as JSONObject, starts with { and array, called as JSONArray, starts with [.

For example :

a.) JSON Structure Example
To parse a response that looks like array example above :

1.) Use jObj.getJSONArray("arrayName") to retrieve the array

2.) Iterate over all the objects in that array using length()

3.) Fetch each object

4.) Retrieve each item of object (retrieved as name-value pair) using getString("name") or other appropriate method

5.) In case there is a single object, it can be retrieved directly using step 3, and if there is only name-value pair, use step 4.

Here, jObj is the JSONObject – the response obtained after executing HTTP Post request.

A quick look at how its done :

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(“URL”);
HttpEntity entity = null;
String json = "";
JSONObject jObj = null;

//Add your data, if any, for the request
List pairs = new ArrayList();
pairs.add(new BasicNameValuePair("sample", “sample”));
post.setEntity(new UrlEncodedFormEntity(pairs));

//Execute the request
HttpResponse response = client.execute(post);  

//Retrieve the response which is InputStreamReader

entity = response.getEntity();
InputStreamReader is = new InputStreamReader(entity.getContent(), "UTF-8");
if (is != null) {
        BufferedReader reader = new BufferedReader(is);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) 
        sb.append(line + "\n");
       json = sb.toString();
       jObj = new JSONObject(json);

PS :  HTTP Post request should be used in non-UI thread (use AysncTask) .


Friday, 24 May 2013

Android - Google Maps API V2 (Part -3) : Geocoding and Reverse Geocoding

In previous article, we plotted hard coded latitude-longitude coordinates on map.

Here we will delve into
1. Geocoding : Retrieving Lat-Lng from a known address
2. Reverse Geocoding : Retrieve Address from known Lat-Lng coordinates

Well, there are two approaches to achieve the same :
1. Using Geocoder Class
2. Using Google Maps APIs

Lets look at both of them and the scenario where each can be used.

Approach 1 : Using Geocoder Class

Geocoding : Is generally required while accepting address from user.

public void geocodeAddress(String addressInput) {
        Geocoder geocoder = new Geocoder(getApplicationContext(),Locale.getDefault());
addresses = null; try { addresses = geocoder.getFromLocationName(addressInput,1); } catch (IOException e) { e.printStackTrace(); } if (addresses != null && addresses.size() > 0) { Address address = addresses.get(0); double lat = address.getLatitude(); double lng = address.getLongitude(); } }

getFromLocationName() is our saviour here :D It just accepts address and returns a list of Addresses that describe the location. You can also specify the number of results you want too have, which is 1 in above case!
Phew! And you are done. Using methods of Address class, we can retrieve lat-lng. Complete address can also be retrieved using 
String title = address.getAddressLine(0)+address.getAdminArea()+address.getCountryName();

Reverse Geocoding :Is required when user taps on map and you need to show the location that he tapped.

Once user taps, we have lat/lng available. To retrieve address :
public String reverseGeocode(double latitude, double longitude) {
 Geocoder geocoder = new Geocoder(getApplicationContext(),Locale.getDefault());
addresses = null; String result = null; try { // Call the synchronous getFromLocation() method by passing in the lat/long values. addresses = geocoder.getFromLocation(latitude, longitude, 1); } catch (IOException e) { e.printStackTrace(); } if (addresses != null && addresses.size() > 0) { Address address = addresses.get(0); // Format the first line of address (if available), city, and country name. result = String.format("%s, %s, %s", address .getMaxAddressLineIndex () > 0 ? address.getAddressLine(0) : "", address.getAdminArea(), address.getCountryName()); } return result; }
Approach 2 : Using Google Maps APIs

Performing same tasks using Google Maps APIs require making Post request to google servers, which return JSON response. Just Parse it to get details.

More Details on this can be found here.
Geocoding Strategies explains when to use which approach.

Problem that generally occurs while using Geocoder class!

Happy Coding!

Friday, 17 May 2013

Android - Google Maps(Part 2) : Plotting a location on map using Google Maps API V2

In previous article, there was an explaination on how to load a map. 
Lets move ahead to plot a location on map.

To plot a location on map, we need

a.) Latitude and Longitude of location to be shown
b.) A marker to display location
c.) Optionally, we can use zoom level of the camera to determine the scale of the map

Have a look before diving into the implementation :

Friday, 10 May 2013

Android - Google Maps (Part 1) : Loading map using Google Maps API V2

A step-by-step guide on using google maps API v2 in android :

High level overview of different steps involved :

1.) Create project, add all the required libraries
2.) Generate API Key from Google APIs console
3.) And the CODE !