Friday 27 December 2013

Flickr API in Android


What is Flickr?

Flickr is the best online photo management and sharing application in the world. On Flickr, members upload photos, share them securely, supplement their photos with metadata like license information, geo-location, people, tags, etc., and interact with their family, friends, contacts or anyone in the community. Practically all the features on Flickr's various platforms -- web, mobile and desktop -- are accompanied by a longstanding API program. Since 2005, developers have collaborated on top of Flickr's APIs to build fun, creative, and gorgeous experiences around photos that extend beyond Flickr.
Overview
The Flickr API consists of a set of callable methods, and some API endpoints.
To perform an action using the Flickr API, you need to select a calling convention, send a request to its endpoint specifying a method and some arguments, and will receive a formatted response.
  • All request formats, listed on the API index page, take a list of named parameters.
  • The REQUIRED parameter method is used to specify the calling method.
  • The REQUIRED parameter api_key is used to specify your API Key.
  • The optional parameter format is used to specify a response format.
  • The arguments, responses and error codes for each method are listed on the method's spec page. Methods are lists on the API index page.
Note: The Flickr API exposes identifiers for users, photos, photosets and other uniquely identifiable objects. These IDs should always be treated as opaque strings, rather than integers of any specific type. The format of the IDs can change over time, so relying on the current format may cause you problems in the future.

Endpoints

https://api.flickr.com/services
http://api.flickr.com/services
Note : The Flickr API expects all data to be UTF-8 encoded.Checks are made for valid UTF-8 sequences. If an invalid sequence is found, the data is presumed to be ISO-8859-1 and converted accordingly to UTF-8.Sending data in any other encoding will result in garbage into Flickr. It won't be dangerous garbage (we will always store valid UTF-8) but it will still be garbage.

User Authentication

Many of Flickr’s API methods require the user to be signed in. In the past we were using our own authentication API, but now, users should only be authenticated using the OAuth specification which is the industry standard. By using the OAuth standard you will provide in your applications a secure way for people to sign-in into their Flickr accounts with all the different account types Flickr is supporting (Yahoo! ID, Google ID, Facebook). Flickr’s OAuth flows work for web-applications, desktop apps and mobile applications as well.


Using OAuth with Flickr

What is OAuth?

OAuth is an open, simple, and secure protocol that enables applications to authenticate users and interact with Flickr on their behalf. The end user's information is securely transferred without revealing the identity of the user. At Flickr, we use OAuth to verify that an application trying to interact with Flickr on your behalf is doing so only with the permissions you have granted it.
The simplest way to get started with OAuth is to use a library with your programming language. To find a library for your programming language, visit the OAuth Code page.
The OAuth flow has 3 steps:


Below is the Flickr OAuth Authorization Flow




Flickr provides different methods for authenticating your application depending on your deployment environment. For each method/environment, Flickr needs to know different information.

Web application and Callback URL

To use web authentication:
  1. Direct the user to a Flickr page; the exact URL is created using the API.
  2. The user will authorize your application on Flickr; or Flickr will remember an old authorization.
  3. Flickr redirects the user to your callback URL; the frob is sent as a GET attribute.

Flickr provide Flickr Services for outside developers to access Flickr photos using Flickr APIs. It's a example to query Flick using Flickr API. In order to make it simple, only ONE photo per page is request.


Signing Requests

First, you must create a base string from your request. The base string is constructed by concatenating the HTTP verb, the request URL, and all request parameters sorted by name, using lexicograhpical byte value ordering, separated by an '&'.
Use the base string as the text and the key is the concatenated values of the Consumer Secret and Token Secret, separated by an '&'.
  1. For example, using the following URL:
http://www.flickr.com/services/oauth/request_token
?oauth_nonce=89601180
&oauth_timestamp=1305583298
&oauth_consumer_key=653e7a6ecc1d528c516cc8f92cf98611
&oauth_signature_method=HMAC-SHA1
&oauth_version=1.0
&oauth_callback=http%3A%2F%2Fwww.example.com

Would have a base string that looks like the following:

GET&http%3A%2F%2Fwww.flickr.com%2Fservices%2Foauth%2Frequest_token&oauth_callback%3Dhttp%253A%252F%252Fwww.example.com%26oauth_consumer_key%3D653e7a6ecc1d528c516cc8f92cf98611%26oauth_nonce%3D95613465%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1305586162%26oauth_version%3D1.0
Which would generate the following signature:


7w18YS2bONDPL%2FzgyzP5XTr5af4%3D
Getting a Request Token


Request Token URL:

http://www.flickr.com/services/oauth/request_token

The first step to obtaining authorization for a user is to get a Request Token using your Consumer Key. This is a temporary token that will be used to authenticate the user to your application. This token, along with a token secret, will later be exchanged for an Access Token.

The following is an example URL request for a request token:

http://www.flickr.com/services/oauth/request_token
?oauth_nonce=95613465
&oauth_timestamp=1305586162
&oauth_consumer_key=653e7a6ecc1d528c516cc8f92cf98611
&oauth_signature_method=HMAC-SHA1
&oauth_version=1.0
&oauth_signature=7w18YS2bONDPL%2FzgyzP5XTr5af4%3D
&oauth_callback=http%3A%2F%2Fwww.example.com

Flickr returns a response similar to the following:


oauth_callback_confirmed=true
&oauth_token=72157626737672178-022bbd2f4c2f3432
&oauth_token_secret=fccb68c4e6103197


Getting the User Authorization

User Authorization URL:

http://www.flickr.com/services/oauth/authorize

After getting the Request Token, your application needs to present the Flickr authorization page to the user, where they will be asked to give permission to your application to access their data.
Additionally, you can pass the optional
After authorization is complete, Flickr will redirect the user back to your application using the oauth_callback specified with your Request Token.

The following is an example authorization URL:

http://www.flickr.com/services/oauth/authorize
?oauth_token=72157626737672178-022bbd2f4c2f3432

The following is an example callback after authorization:


http://www.example.com/
?oauth_token=72157626737672178-022bbd2f4c2f3432
&oauth_verifier=5d1b96a26b494074


Exchanging the Request Token for an Access Token

Access Token URL:

http://www.flickr.com/services/oauth/access_token

After the user authorizes your application, you can exchange the approved Request Token for an Access Token. This Access Token should be stored by your application, and used to make authorized requests to Flickr.

The following is an example of a request for an Access Token:

http://www.flickr.com/services/oauth/access_token
?oauth_nonce=37026218
&oauth_timestamp=1305586309
&oauth_verifier=5d1b96a26b494074
&oauth_consumer_key=653e7a6ecc1d528c516cc8f92cf98611
&oauth_signature_method=HMAC-SHA1
&oauth_version=1.0
&oauth_token=72157626737672178-022bbd2f4c2f3432
&oauth_signature=UD9TGXzrvLIb0Ar5ynqvzatM58U%3D

Flickr returns a response similar to the following:


fullname=Jamal%20Fanaian
&oauth_token=72157626318069415-087bfc7b5816092c
&oauth_token_secret=a202d1f853ec69de
&user_nsid=21207597%40N07
&username=jamalfanaian


Calling the Flickr API with OAuth

After an Access Token has been granted to your application, you can make authenticated requests to the Flickr API. Flickr requires HMAC-SHA1 encryption because all requests are being made insecurely using HTTP.

The following is an example of a request made to the flickr.test.login API:

http://api.flickr.com/services/rest
?nojsoncallback=1 &oauth_nonce=84354935
&format=json
&oauth_consumer_key=653e7a6ecc1d528c516cc8f92cf98611
&oauth_timestamp=1305583871
&oauth_signature_method=HMAC-SHA1
&oauth_version=1.0
&oauth_token=72157626318069415-087bfc7b5816092c
&oauth_signature=dh3pEH0Xk1qILr82HyhOsxRv1XA%3D
&method=flickr.test.login

Flickr returns a response similar to the following:

{"user":{"id":"21207597@N07", "username":{"_content":"jamalfanaian"}}, "stat":"ok"}
The URL is:
FlickrQuery_url = "http://api.flickr.com/services/rest/?method=flickr.photos.search&per_page=1&nojsoncallback=1&format=json&tags=<search>&api_key=<API KEY>

where:
<search> - is the search word, (don't insert SPACE in this exercise!)
<API KEY> -  is your API Key


In order to access Flickr API, you have to apply your own API key at www.flickr.com/services/apps/create/apply/?.

The example access the API via HttpClient, using HttpGet() method.


public class AndroidFlickrActivity extends Activity {
String FlickrQuery_url = "http://api.flickr.com/services/rest/?method=flickr.photos.search";
String FlickrQuery_per_page = "&per_page=1";
String FlickrQuery_nojsoncallback = "&nojsoncallback=1";
String FlickrQuery_format = "&format=json";
String FlickrQuery_tag = "&tags=";
String FlickrQuery_key = "&api_key=";

// Apply your Flickr API:
// www.flickr.com/services/apps/create/apply/?
String FlickrApiKey = "2155e9406043b7494453105eec99ae37";
EditText searchText;
   Button searchButton;
   TextView textQueryResult, textJsonResult;
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       searchText = (EditText)findViewById(R.id.searchtext);
       searchButton = (Button)findViewById(R.id.searchbutton);
       textQueryResult = (TextView)findViewById(R.id.queryresult);
       textJsonResult = (TextView)findViewById(R.id.jsonresult);
       searchButton.setOnClickListener(searchButtonOnClickListener);

   }
   private Button.OnClickListener searchButtonOnClickListener
           = new Button.OnClickListener(){
          public void onClick(View arg0) {
            String searchQ = searchText.getText().toString();
            String searchResult = QueryFlickr(searchQ);
            textQueryResult.setText(searchResult);
           String jsonResult = ParseJSON(searchResult);
           textJsonResult.setText(jsonResult);

     }};
   private String QueryFlickr(String q){
            String qResult = null;
    String qString =FlickrQuery_url + FlickrQuery_per_page+ FlickrQuery_nojsoncallback+ FlickrQuery_format+ FlickrQuery_tag + q + FlickrQuery_key + FlickrApiKey;
    HttpClient httpClient = new DefaultHttpClient();
      HttpGet httpGet = new HttpGet(qString);
       try {
          HttpEntity httpEntity = httpClient.execute(httpGet).getEntity();
  if (httpEntity != null){
   InputStream inputStream = httpEntity.getContent();
   Reader in = new InputStreamReader(inputStream);
   BufferedReader bufferedreader = new BufferedReader(in);
   StringBuilder stringBuilder = new StringBuilder();
   String stringReadLine = null;
   while ((stringReadLine = bufferedreader.readLine()) != null)                     {
    stringBuilder.append(stringReadLine + "\n");
    }
   qResult = stringBuilder.toString();
  }
 } catch (ClientProtocolException e) {
  e.printStackTrace();

 } catch (IOException e) {
  e.printStackTrace();
 }
       return qResult;
    }

   private String ParseJSON(String json){

    String jResult = null;
    try {

  JSONObject JsonObject = new JSONObject(json);
  JSONObject Json_photos = JsonObject.getJSONObject("photos");
  JSONArray JsonArray_photo = Json_photos.getJSONArray("photo");
  //We have only one photo in this exercise
  JSONObject FlickrPhoto = JsonArray_photo.getJSONObject(0);
  jResult = "\nid: " + FlickrPhoto.getString("id") + "\n"

    + "owner: " + FlickrPhoto.getString("owner") + "\n"
    + "secret: " + FlickrPhoto.getString("secret") + "\n"
    + "server: " + FlickrPhoto.getString("server") + "\n"
    + "farm: " + FlickrPhoto.getString("farm") + "\n"
    + "title: " + FlickrPhoto.getString("title") + "\n";
 } catch (JSONException e) {
  e.printStackTrace();

 }
    return jResult;
  }
}

Here is the layout code:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 >
<TextView
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="@string/hello"
 />
<EditText
 android:id="@+id/searchtext"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 />
<Button
 android:id="@+id/searchbutton"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:text="Search"
 />
<TextView
 android:id="@+id/queryresult"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 />
</LinearLayout>

You need to grant permission of "android.permission.INTERNET".


Output:







References:

  • http://www.flickr.com/services/developer/ 
  • http://android-er.blogspot.in/2011/07/access-flickr-api-using-httpclient.html 
  • https://code.google.com/p/flickrj-android/ 
  • http://www.flickr.com/services/developer/api/ 
  • http://www.flickr.com/groups/api/discuss/72157624166264367/ 
  • https://code.google.com/p/flickr-viewer-for-honeycomb/source/checkout 
  • https://github.com/luminousman/Flickr 
  • http://blog.theunical.com/java/flickr-example-to-upload-photos-using-java/ 

Monday 2 December 2013

How to make Text flow around images in TextView(api8) like webpage?

Hello Friends,

Today i am going to show you how the Text in TextView flow around the Image in Android.
This example will help you use the space under the picture, which is usually empty.
Starting from api 8 (Android 2.2) has a new interface LeadingMarginSpan2, which lets you create text indent for the first N rows. The picture created indented 50 pixels for the first 3 rows.

First of create an application in android and create the layout as below:

main.xml
 <?xml version="1.0" encoding="UTF-8"?>  
 <RelativeLayout  
 xmlns:android="http://schemas.android.com/apk/res/android"  
  android:layout_width="match_parent"  
  android:layout_height="wrap_content"  
  android:padding="5dp">  
  <TextView  
  android:textSize="18.0sp"  
  android:id="@+id/message_view"  
  android:layout_width="match_parent"  
  android:layout_height="wrap_content"  
  android:text="@string/text" />  
  <ImageView  
  android:layout_width="wrap_content"  
  android:layout_height="wrap_content"  
  android:id="@+id/icon" />  
 </RelativeLayout>  

After creating the layout in your MainActivity.java file create a class MyLeadingMarginSpan2 which extends a LeadingMarginSpan2 interface as below:
 class MyLeadingMarginSpan2 implements LeadingMarginSpan2 {  
     private int margin;  
     private int lines;  
     MyLeadingMarginSpan2(int lines, int margin) {  
       this.margin = margin;  
       this.lines = lines;  
     }  
    /*Returns the value to which must be added indentation*/  
     @Override  
     public int getLeadingMargin(boolean first) {  
       if (first) {  
        / *This * indentation is applied to the number of          rows returned * getLeadingMarginLineCount ()*/   
       return margin;  
       }  
      else  
      {  
     //Offset for all other Layout layout ) { }  
     /*Returns * the number of rows which should be applied *     indent returned by getLeadingMargin (true)   
     * Note:* Indent only applies to N lines of the first paragraph.*/   
       return 0;  
       }  
     }  
     @Override  
     public void drawLeadingMargin(Canvas c, Paint p, int x, int dir,  
         int top, int baseline, int bottom, CharSequence text,   
         int start, int end, boolean first, Layout layout) {}  
   @Override  
     public int getLeadingMarginLineCount() {  
       return lines;  
     }  
   };  

In OnCreate, create an object SpannableString and apply a new style.
 @Override  
 Public void onCreate ( Bundle savedInstanceState )   
 {  
     super . onCreate ( savedInstanceState ) ;  
     setContentView ( R. layout . main ) ;   
   String text = getString ( R. string . text ) ;   
   // Get the icon and its width  
   Drawable DICON = getResources ( ).getDrawable(R.drawable.icon);   
   int = leftMargin DICON. getIntrinsicWidth ( ) + 10 ;   
   //Set the icon in R.id.icon   
    ImageView icon =(ImageView)findViewById(R.ID.icon ) ;  
    icon.setBackgroundDrawable (DICON) ;  
   SpannableString SS = New SpannableString (text);   
   //Expose the indent for the first three rows  
    SS.setSpan(New MyLeadingMarginSpan2(3,leftMargin),0,SS.length(),0);  
    TextView MessageView = ( TextView ) findViewById ( R. ID . message_view ) ;  
     MessageView. setText ( SS ) ;   
 }  

Output: