title: Integrate flickr api in Android App
body: <p>I am creating a Social network integration App for Android. I can already post on Facebook, Twitter and Linkedin. Now I have to integrate Flickr in the app. I was unable to find a proper      example of how to integrate flicker in Android App.</p>
  
  <p>My source codes are given below:</p>
  
  <p>This is the <strong>FlickrViewerActivity</strong> class:</p>
  
  <pre><code> public class FlickrViewerActivity extends Activity {
  
      public static final String CALLBACK_SCHEME = "flickrj-android-sample-oauth"; //$NON-NLS-1$
      public static final String PREFS_NAME = "flickrj-android-sample-pref"; //$NON-NLS-1$
      public static final String KEY_OAUTH_TOKEN = "flickrj-android-oauthToken"; //$NON-NLS-1$
      public static final String KEY_TOKEN_SECRET = "flickrj-android-tokenSecret"; //$NON-NLS-1$
      public static final String KEY_USER_NAME = "flickrj-android-userName"; //$NON-NLS-1$
      public static final String KEY_USER_ID = "flickrj-android-userId"; //$NON-NLS-1$
  
      private static final Logger logger = LoggerFactory.getLogger(FlickrjAndroidSampleActivity.class);
  
  
      private ListView listView;
      private TextView textUserTitle;
      private TextView textUserName;
      private TextView textUserId;
      private ImageView userIcon;
      private ImageButton refreshButton;
  
      /** Called when the activity is first created. */
      @Override
      public void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.main);
  
              this.textUserTitle = (TextView) this.findViewById(R.id.profilePageTitle);
              this.textUserName = (TextView) this.findViewById(R.id.userScreenName);
              this.textUserId = (TextView) this.findViewById(R.id.userId);
              this.userIcon = (ImageView) this.findViewById(R.id.userImage);
              this.listView = (ListView) this.findViewById(R.id.imageList);
              this.refreshButton = (ImageButton)     this.findViewById(R.id.btnRefreshUserProfile);
  
              this.refreshButton.setOnClickListener(new OnClickListener() {
                      @Override
                      public void onClick(View v) {
                              load(getOAuthToken());
                      }
              });
  
              OAuth oauth = getOAuthToken();
              if (oauth == null || oauth.getUser() == null) {
                      OAuthTask task = new OAuthTask(this);
                      task.execute();
              } else {
                      load(oauth);
              }
      }
  
      private void load(OAuth oauth) {
              if (oauth != null) {
                      new LoadUserTask(this, userIcon).execute(oauth);
                      new LoadPhotostreamTask(this, listView).execute(oauth);
              }
      }
  
       @Override
          public void onDestroy() {
      listView.setAdapter(null);
      super.onDestroy();
       }
  
         /* (non-Javadoc)
         * @see android.app.Activity#onNewIntent(android.content.Intent)
         */
         @Override
          protected void onNewIntent(Intent intent) {
              //this is very important, otherwise you would get a null Scheme in the onResume                        later on.
              setIntent(intent);
         }
  
        public void setUser(User user) {
              textUserTitle.setText(user.getUsername());
              textUserName.setText(user.getRealName());
              textUserId.setText(user.getId());
        }
  
            public ImageView getUserIconImageView() {
              return this.userIcon;
         }
  
      @Override
      public void onResume() {
              super.onResume();
              Intent intent = getIntent();
              String scheme = intent.getScheme();
              OAuth savedToken = getOAuthToken();
              if (CALLBACK_SCHEME.equals(scheme) &amp;&amp; (savedToken == null || savedToken.getUser() == null)) {
                      Uri uri = intent.getData();
                      String query = uri.getQuery();
                      logger.debug("Returned Query: {}", query); //$NON-NLS-1$
                      String[] data = query.split("&amp;"); //$NON-NLS-1$
                      if (data != null &amp;&amp; data.length == 2) {
                              String oauthToken = data[0].substring(data[0].indexOf("=") + 1); //$NON-NLS-1$
                              String oauthVerifier = data[1]
                                              .substring(data[1].indexOf("=") + 1); //$NON-NLS-1$
                              logger.debug("OAuth Token: {}; OAuth Verifier: {}", oauthToken, oauthVerifier); //$NON-NLS-1$
  
                              OAuth oauth = getOAuthToken();
                              if (oauth != null &amp;&amp; oauth.getToken() != null &amp;&amp; oauth.getToken().getOauthTokenSecret() != null) {
                                      GetOAuthTokenTask task = new GetOAuthTokenTask(this);
                                      task.execute(oauthToken, oauth.getToken().getOauthTokenSecret(), oauthVerifier);
                              }
                      }
              }
  
      }
  
            public void onOAuthDone(OAuth result) {
              if (result == null) {
                      Toast.makeText(this,
                                      "Authorization failed", //$NON-NLS-1$
                                      Toast.LENGTH_LONG).show();
                      } else {
                      User user = result.getUser();
                      OAuthToken token = result.getToken();
                      if (user == null || user.getId() == null || token == null
                                      || token.getOauthToken() == null
                                      || token.getOauthTokenSecret() == null) {
                              Toast.makeText(this,
                                              "Authorization failed", //$NON-NLS-1$
                                              Toast.LENGTH_LONG).show();
                              return;
                      }
             String message = String.format(Locale.US, "Authorization Succeed:        user=%s, userId=%s, oauthToken=%s, tokenSecret=%s", //$NON-NLS-1$
                                      user.getUsername(), user.getId(),   token.getOauthToken(), token.getOauthTokenSecret());
                        Toast.makeText(this,
                                      message,
                                      Toast.LENGTH_LONG).show();
                      saveOAuthToken(user.getUsername(), user.getId(), token.getOauthToken(), token.getOauthTokenSecret());
                      load(result);
              }
      }
  
  
          public OAuth getOAuthToken() {
       //Restore preferences
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        String oauthTokenString = settings.getString(KEY_OAUTH_TOKEN, null);
        String tokenSecret = settings.getString(KEY_TOKEN_SECRET, null);
          if (oauthTokenString == null &amp;&amp; tokenSecret == null) {
              logger.warn("No oauth token retrieved"); //$NON-NLS-1$
              return null;
          }
          OAuth oauth = new OAuth();
           String userName = settings.getString(KEY_USER_NAME, null);
          String userId = settings.getString(KEY_USER_ID, null);
           if (userId != null) {
              User user = new User();
              user.setUsername(userName);
              user.setId(userId);
              oauth.setUser(user);
           }
          OAuthToken oauthToken = new OAuthToken();
           oauth.setToken(oauthToken);
           oauthToken.setOauthToken(oauthTokenString);
            oauthToken.setOauthTokenSecret(tokenSecret);
            logger.debug("Retrieved token from preference store: oauth token={}, and token  secret={}", oauthTokenString, tokenSecret); //$NON-NLS-1$
             return oauth;
              }
  
         public void saveOAuthToken(String userName, String userId, String token, String  tokenSecret) {
         logger.debug("Saving userName=%s, userId=%s, oauth token={}, and token secret={}",    new String[]{userName, userId, token, tokenSecret}); //$NON-NLS-1$
         SharedPreferences sp = getSharedPreferences(PREFS_NAME,
                              Context.MODE_PRIVATE);
              Editor editor = sp.edit();
              editor.putString(KEY_OAUTH_TOKEN, token);
              editor.putString(KEY_TOKEN_SECRET, tokenSecret);
              editor.putString(KEY_USER_NAME, userName);
              editor.putString(KEY_USER_ID, userId);
              editor.commit();
        }
  
      }
  </code></pre>
  
  <p>The <strong>OAuthTask</strong> class:</p>
  
  <pre><code>public class OAuthTask extends AsyncTask&lt;Void, Integer, String&gt; {
  
  private static final Logger logger = LoggerFactory
                  .getLogger(OAuthTask.class);
  private static final Uri OAUTH_CALLBACK_URI = Uri.parse(FlickrjAndroidSampleActivity.CALLBACK_SCHEME
                  + "://oauth"); //$NON-NLS-1$
  
  /**
   * The context.
   */
  private Context mContext;
  
  /**
   * The progress dialog before going to the browser.
   */
  private ProgressDialog mProgressDialog;
  
  /**
   * Constructor.
   * 
   * @param context
   */
  public OAuthTask(Context context) {
          super();
          this.mContext = context;
  }
  
  @Override
  protected void onPreExecute() {
          super.onPreExecute();
          mProgressDialog = ProgressDialog.show(mContext,
                          "", "Generating the authorization request..."); //$NON-NLS-1$ //$NON-NLS-2$
          mProgressDialog.setCanceledOnTouchOutside(true);
          mProgressDialog.setCancelable(true);
          mProgressDialog.setOnCancelListener(new OnCancelListener() {
                  @Override
                  public void onCancel(DialogInterface dlg) {
                          OAuthTask.this.cancel(true);
                  }
          });
  }
  
  /*
   * (non-Javadoc)
   * 
   * @see android.os.AsyncTask#doInBackground(Params[])
   */
  @Override
  protected String doInBackground(Void... params) {
          try {
                  Flickr f = FlickrHelper.getInstance().getFlickr();
                  OAuthToken oauthToken = f.getOAuthInterface().getRequestToken(
                                  OAUTH_CALLBACK_URI.toString());
                  saveTokenSecrent(oauthToken.getOauthTokenSecret());
                  URL oauthUrl = f.getOAuthInterface().buildAuthenticationUrl(
                                  Permission.READ, oauthToken);
                  return oauthUrl.toString();
          } catch (Exception e) {
                  logger.error("Error to oauth", e); //$NON-NLS-1$
                  return "error:" + e.getMessage(); //$NON-NLS-1$
          }
  }
  
  /**
   * Saves the oauth token secrent.
   * 
   * @param tokenSecret
   */
  private void saveTokenSecrent(String tokenSecret) {
          logger.debug("request token: " + tokenSecret); //$NON-NLS-1$
          FlickrjAndroidSampleActivity act = (FlickrjAndroidSampleActivity) mContext;
          act.saveOAuthToken(null, null, null, tokenSecret);
          logger.debug("oauth token secret saved: {}", tokenSecret); //$NON-NLS-1$
  }
  
  @Override
  protected void onPostExecute(String result) {
          if (mProgressDialog != null) {
                  mProgressDialog.dismiss();
          }
          if (result != null &amp;&amp; !result.startsWith("error") ) { //$NON-NLS-1$
                  mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri
                                  .parse(result)));
          } else {
                  Toast.makeText(mContext, result, Toast.LENGTH_LONG).show();
          }
  }
  
  }
  </code></pre>
  
  <p>The <strong>Manifest</strong> file:</p>
  
  <pre><code>&lt;manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.example.flickr.test"
      android:versionCode="1"
      android:versionName="1.0" 
      android:installLocation="preferExternal"&gt;
  
      &lt;uses-sdk
          android:minSdkVersion="9"
          android:targetSdkVersion="15" /&gt;
      &lt;uses-permission android:name="android.permission.INTERNET"&gt;&lt;/uses-permission&gt;
      &lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"&gt;&lt;/uses-permission&gt;
      &lt;uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"&gt;&lt;/uses-permission&gt;
  
      &lt;application
          android:icon="@drawable/ic_launcher"
          android:label="@string/app_name"
          android:theme="@style/AppTheme" &gt;
          &lt;activity
              android:name=".FlickrViewerActivity"
              android:label="@string/title_activity_flickr_viewer" &gt;
              &lt;intent-filter&gt;
                  &lt;action android:name="android.intent.action.MAIN" /&gt;
  
                  &lt;category android:name="android.intent.category.LAUNCHER" /&gt;
  
  
                  &lt;action android:name="android.intent.action.VIEW" /&gt;
                                  &lt;category android:name="android.intent.category.DEFAULT" /&gt;
                                  &lt;category android:name="android.intent.category.BROWSABLE" /&gt;
                                  &lt;data android:scheme="flickrj-android-sample-oauth" /&gt;
  
              &lt;/intent-filter&gt;
          &lt;/activity&gt;
      &lt;/application&gt;
  
  &lt;/manifest&gt;
  </code></pre>
  
  <p>The <strong>Main.xml</strong> file:</p>
  
  <pre><code>&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:tools="http://schemas.android.com/tools"
      android:layout_width="match_parent"
      android:layout_height="match_parent" &gt;
  
      &lt;TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_centerHorizontal="true"
          android:layout_centerVertical="true"
          android:padding="@dimen/padding_medium"
          android:text="@string/hello_world"
          tools:context=".FlickrViewerActivity" /&gt;
  
  &lt;/RelativeLayout&gt;
  </code></pre>
  
  <p>I was following the tutorial at:</p>
  
  <p><a href="http://code.google.com/p/flickrj-android/wiki/HowToGuide4Android" rel="nofollow">http://code.google.com/p/flickrj-android/wiki/HowToGuide4Android</a></p>
  
  <p>The codes are not executing, I am looking for a solution or a sample project source code in Android with Flickr integration. </p>