Integre flickr api en la aplicación para Android
Estoy creando una aplicación de integración de redes sociales para Android. Ya puedo publicar en Facebook, Twitter y Linkedin. Ahora tengo que integrar Flickr en la aplicación. No pude encontrar un ejemplo apropiado de cómo integrar el parpadeo en la aplicación para Android.
Mis códigos fuente son los siguientes:
Esta es la clase FlickrViewerActivity :
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) && (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("&"); //$NON-NLS-1$ if (data != null && 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 && oauth.getToken() != null && 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 && 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(); } }
La clase OAuthTask :
public class OAuthTask extends AsyncTask<Void, Integer, String> { 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 && !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(); } } }
El archivo de manifiesto :
<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"> <uses-sdk android:minSdkVersion="9" android:targetSdkVersion="15" /> <uses-permission android:name="android.permission.INTERNET"></uses-permission> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".FlickrViewerActivity" android:label="@string/title_activity_flickr_viewer" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:scheme="flickrj-android-sample-oauth" /> </intent-filter> </activity> </application> </manifest>
El archivo Main.xml :
<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" > <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" /> </RelativeLayout>
Yo estaba siguiendo el tutorial en:
http://code.google.com/p/flickrj-android/wiki/HowToGuide4Android
Los códigos no se están ejecutando, estoy buscando una solución o un ejemplo de código fuente de proyecto en Android con la integración de Flickr.
public static final Cadena CALLBACK_SCHEME = "flickrj-android-sample-oauth"; // $ NON-NLS-1 $ public static final Cadena PREFS_NAME = "flickrj-android-sample-pref"; // $ NON-NLS-1 $ public static final Cadena KEY_OAUTH_TOKEN = "flickrj-android-oauthToken"; // $ NON-NLS-1 $ public static final Cadena KEY_TOKEN_SECRET = "flickrj-android-tokenSecret"; // $ NON-NLS-1 $ public static final Cadena KEY_USER_NAME = "flickrj-android-userName"; // $ NON-NLS-1 $ public static final Cadena KEY_USER_ID = "flickrj-android-userId"; // $ NON-NLS-1 $
¿Cómo obtener este oauth token y token secreto ?? ¿Conseguí la llave del api y la llave secreta agregando mi uso en flickr pero estoy consiguiendo el error del oauth en mi código?