Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Java Development

Reply
Developer
Posts: 253
Registered: ‎08-14-2010
My Device: Not Specified

facebook connect help

Hi,

 

How to create a FB login within an app? I found Strawberry sample.

 

But I can not see what I want.

 

Just wanna show a button and when click on that it should try to login to FB.

 

 

Thank you in advance

New Developer
Posts: 134
Registered: ‎01-11-2011
My Device: curve

Re: facebook connect help

In the StrawBerry example made some changes.

Make your own class and add a button on this.OnClick on this button push the Screen of the StrawBerry

Developer
Posts: 604
Registered: ‎12-27-2010
My Device: Not Specified

Re: facebook connect help

With the current version, calling Facebook.refreshAccessToken() works for me to display the login prompt.

Developer
Posts: 466
Registered: ‎03-04-2009
My Device: 8520
My Carrier: some

Re: facebook connect help

 

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;

import javax.microedition.io.HttpConnection;

import net.rim.blackberry.api.browser.URLEncodedPostData;
import net.rim.device.api.i18n.MessageFormat;
import net.rim.device.api.io.IOUtilities;
import net.rim.device.api.io.transport.ConnectionDescriptor;
import net.rim.device.api.io.transport.ConnectionFactory;
import net.rim.device.api.ui.UiApplication;

import com.blackberry.facebook.FBUser;
import com.blackberry.facebook.FacebookContext;
import com.blackberry.facebook.User;
import com.blackberry.facebook.ui.Action;
import com.blackberry.facebook.ui.ActionListener;
import com.blackberry.facebook.ui.LoginScreen;
import com.blackberry.facebook.ui.LogoutScreen;

public final class FacebookConnectHelper implements ActionListener {

	private static final String TAG = "FacebookConnectHelper";
	public final static String NEXT_URL = "http://www.facebook.com/connect/login_success.html";
	private static final String GRAPH_URL = "https://graph.facebook.com";
	private static final String FETCH_USER_PICTURE_URL_FORMAT = GRAPH_URL + "/" + "{0}" + "/picture";
	private static final MessageFormat urlFormatter = new MessageFormat(FETCH_USER_PICTURE_URL_FORMAT);


	private FacebookContext fbc;
	private String appId;
	private String appPermissions;
	private FacebookConnectListener fbConnectListener;
	private Executor executor;

	private LoginScreen loginScreen;
	private LogoutScreen logoutScreen;

	private String facebookUserName;

	private static FacebookConnectHelper instance;

	private FacebookConnectHelper() {
		executor = new Executor();
	}

	public static FacebookConnectHelper getInstance() {
		if (instance == null) {
			instance = new FacebookConnectHelper();
		}

		return instance;
	}

	/**
	 * Do facebook login procedure.
	 * 
	 * @param listener
	 *            {@link FacebookConnectListener}
	 */
	public void performFacebookLogin(FacebookConnectListener listener) {
		fbConnectListener = listener;
		executor.execute(new Runnable() {
			public void run() {
					fbc = new FacebookContext(NEXT_URL, appId);

					URLEncodedPostData postData = new URLEncodedPostData("UTF-8", false);
					postData.append("scope", appPermissions);
					postData.append("redirect_uri", fbc.getNextUrl());
					postData.append("response_type", "token");
					postData.append("display", "touch");
					postData.append("client_id", fbc.getApplicationId());
					String url = LoginScreen.OAUTH_URL + postData.toString();
					loginScreen = new LoginScreen(fbc, url);
					loginScreen.addActionListener(FacebookConnectHelper.this);

					pushLoginScreen();
				}
			}
		});

	}

	public void logoutAndExit() {
		logoutScreen = new LogoutScreen(fbc);
		logoutScreen.addActionListener(this);
		logoutScreen.fetch();
	}

	public void onAction(Action event) {
		if (event.getSource() == loginScreen) {
			if (event.getAction().equals(LoginScreen.ACTION_LOGGED_IN)) {
				try {
					String accessToken = (String) event.getData();
					fbc.setAccessToken(accessToken);
					popLoginScreen();
					logoutAndExit(); // to provide ability to enter login/pass
					// next time. Not to use cached ones.
					processLogedInAction(accessToken);
				} catch (Throwable t) {
					Log.e(TAG, "Failed to receive fb access_token", t);
					fbConnectListener
							.onFacebookConnectFailed("Connecting with Facebook is currently not available. Try again later.");
				}

			} else if (event.getAction().equals(LoginScreen.ACTION_SUCCESS)) {
				logoutAndExit();
				popLoginScreen();
				Log.d(TAG, "success URL: " + loginScreen.getUrl());
			} else if (event.getAction().equals(LoginScreen.ACTION_ERROR)) {
				String errorMsg = (String) event.getData();
				Log.d(TAG, "Error: " + errorMsg);
				fbConnectListener.onFacebookConnectFailed(errorMsg);
			} else if (event.getAction().equals(LoginScreen.ACTION_CANCEL)) {
				popLoginScreen();
			}
		} else if (event.getSource() == logoutScreen) {
			if (event.getAction().equals(LogoutScreen.ACTION_LOGGED_OUT)) {
				// TODO: action logged out invoked
			}
		}

	}

	private void pushLoginScreen() {
		ScreenHelper.postRunnableLater(new Runnable() {

			public void run() {
				UiApplication.getUiApplication().pushScreen(loginScreen);

			}
		});
	}

	private void popLoginScreen() {
		ScreenHelper.postRunnableLater(new Runnable() {

			public void run() {
				if (UiApplication.getUiApplication().getActiveScreen().equals(loginScreen)) {
					UiApplication.getUiApplication().popScreen(loginScreen);
				}

			}
		});
	}

	private void processLogedInAction(final String accessToken) {
		executor.execute(new Runnable() {

			public void run() {
				try {
					User user = new FBUser("me", accessToken);
					boolean isSuccess = fbConnectListener.onFacebookConnectSuccess(user.getId(), accessToken);
				} catch (Exception e) {
					Log.e(TAG, "Error on processing loged in action.", e);
				}
			}
		});
	}

	public String getFacebookName() {
		if (facebookUserName == null) {
			String[] loadSessionData = loadSessionData();
			if (loadSessionData != null && loadSessionData.length > 1) {
				String accessToken = loadSessionData[1];
				User user = new FBUser("me", accessToken);
				facebookUserName = user.getFullName();
			}
		}
		
		return facebookUserName;

	}




	public static byte[] downloadFacebookUserPicture(String fbId) throws IOException {
		String url = buildFacebookUserPictureUrl(fbId);
		Log.i(TAG, "downloadFacebookUserPicture --> " + url);
		byte[] data = null;
		HttpConnection httpConnection = null;
		InputStream is = null;
		ConnectionDescriptor connectionDescriptor;
		try {
			ConnectionFactory connectionFactory = new ConnectionFactory();
			connectionDescriptor = connectionFactory.getConnection(url);
			httpConnection = (HttpConnection) connectionDescriptor.getConnection();
			int rc = httpConnection.getResponseCode();
			if (rc == 302) {// redirect
				url = httpConnection.getHeaderField("Location");
				httpConnection.close();
				connectionDescriptor = connectionFactory.getConnection(url);
				httpConnection = (HttpConnection) connectionDescriptor.getConnection();
				rc = httpConnection.getResponseCode();
			}
			is = httpConnection.openInputStream();
			data = IOUtilities.streamToBytes(is);
		} finally {
			if (is != null) {
				is.close();
			}
			if (httpConnection != null) {
				httpConnection.close();
			}
		}
		return data;
	}

	public static String buildFacebookUserPictureUrl(String fbId) {
		String url = urlFormatter.format(new Object[] { fbId });
		return url;
	}

}

 

 

Got resolved! Press kudo icon!
Developer
Posts: 466
Registered: ‎03-04-2009
My Device: 8520
My Carrier: some

Re: facebook connect help

in the post above we encapsulated the FB connect logic into one class. Feel free to use it as the example.

Your starting point is

 

performFacebookLogin(FacebookConnectListener listener)
Got resolved! Press kudo icon!
Developer
Posts: 253
Registered: ‎08-14-2010
My Device: Not Specified

Re: facebook connect help

Hi jbrofitt,

 

please have a look my code . Is this what did you suggest?

package uk.co.fb.bb.screens.main;

import uk.co.bbtrial.fb.FBoperations;

import com.ka.facebook.Facebook;
import com.ka.facebook.FacebookException;

import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.container.MainScreen;

public class FBMainLogScreen extends MainScreen {
	
	FBoperations fbo;
	
	public FBMainLogScreen() {
		// TODO Auto-generated constructor stub
		
		fbo=new FBoperations();
		
		add(new ButtonField("Login"){
			
			protected boolean invokeAction(int action) {
				// TODO Auto-generated method stub
				try {
					fbo.getFb().refreshAccessToken(true);
				} catch (FacebookException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				return true;
			}
			
		});
	}

}

 

Cheers 

 

Developer
Posts: 604
Registered: ‎12-27-2010
My Device: Not Specified

Re: facebook connect help

I'm using refreshAccessToken(false) just so it will use a token if it has it already, but other than that yeah looks good.

Developer
Posts: 253
Registered: ‎08-14-2010
My Device: Not Specified

Re: facebook connect help

it does not seems to be working ... I tried but no result  where can I be wrong?

 

cheers

Developer
Posts: 604
Registered: ‎12-27-2010
My Device: Not Specified

Re: facebook connect help

Is it firing your invokeAction() at all?

Developer
Posts: 253
Registered: ‎08-14-2010
My Device: Not Specified

Re: facebook connect help

 

Hi Jp,
The app shows connceting to facebook spinner animation.
Then I am getting a web page view with "Error requesting content for :"
I capture event log 
[0.0] 2011-04-14 18:31:36 [INFO] BF-Navigate: http://www.facebook.com/dialog/oauth?scope=user_about_me,use[0.0] r_activities,user_birthday,user_education_history,user_events,user_groups,user_hometown,user_interes[0.0] ts,user_likes,user_location,user_notes,user_online_pres[0.0] ence,user_photo_video_tags,user_photos,user_relationships,user_relationship_details,user_religion_po[0.0] litics,user_status,user_videos,user_website,user_work_history,email,read_friendlists,read_insights,r[0.0] ead_mailbox,read_requests,read_stream,xmpp_login,ads_ma[0.0] nagement,user_checkins,friends_about_me,friends_activities,friends_birthday,friends_education_histor[0.0] y,friends_events,friends_groups,friends_hometown,friends_interests,friends_likes,friends_location,fr[0.0] iends_notes,friends_online_presence,friends_photo_video[0.0] _tags,friends_photos,friends_relationships,friends_relationship_details,friends_religion_politics,fr[0.0] iends_status,friends_videos,friends_website,friends_work_history,manage_friendlists,friends_checkins[0.0] ,publish_stream,create_event,rsvp_event,offline_access,[0.0] publish_checkins,manage_pages&redirect_uri=http://www.facebook.com/connect/login_success.html&respon[0.0] se_type=token&display=touch&client_id=203367179686417
[0.0] 2011-04-14 18:31:38 [INFO] BF-DocumentLoaded(): error://http//www.facebook.com/dialog/oauth?scope=us[0.0] er_about_me,user_activities,user_birthday,user_education_history,user_events,user_groups,user_hometo[0.0] wn,user_interests,user_likes,user_location,user_notes,u[0.0] ser_online_presence,user_photo_video_tags,user_photos,user_relationships,user_relationship_details,u[0.0] ser_religion_politics,user_status,user_videos,user_website,user_work_history,email,read_friendlists,[0.0] read_insights,read_mailbox,read_requests,read_stream,xm[0.0] pp_login,ads_management,user_checkins,friends_about_me,friends_activities,friends_birthday,friends_e[0.0] ducation_history,friends_events,friends_groups,friends_hometown,friends_interests,friends_likes,frie[0.0] nds_location,friends_notes,friends_online_presence,frie[0.0] nds_photo_video_tags,friends_photos,friends_relationships,friends_relationship_details,friends_relig[0.0] ion_politics,friends_status,friends_videos,friends_website,friends_work_history,manage_friendlists,f[0.0] riends_checkins,publish_stream,create_event,rsvp_event,[0.0] offline_access,publish_checkins,manage_pages&redirect_uri=http://www.facebook.com/connect/login_succ[0.0] ess.html&response_type=token&display=touch&client_id=203367179686417

 what I am actually missing??

 

Cheers