Android Facebook sdk friend list in listview - android

I need to show my facebook friends in listview..
my code is here..
when i launch it in emulator it stop working..
pls help me...
I need to show my facebook friends in listview..
my code is here..
when i launch it in emulator it stop working..
pls help me...
i refer code is [1]: http://pastebin.com/5fCRxtL
public class LoginActivity extends Activity{
private static final String[] PERMISSIONS = new String[] {"publish_stream","publish_checkins", "read_stream", "offline_access"};
public static final String APP_ID = "**************";
private Facebook facebook = new Facebook(APP_ID);
private AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
private ProgressDialog mProgress;
private Handler mHandler = new Handler();
private ProgressDialog mSpinner;
private Handler mRunOnUi = new Handler();
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
public static ArrayList<String> friends ;
String _error;
// private FriendsArrayAdapter friendsArrayAdapter;
// SharedPreferences.Editor editor;
TextView tv;
Button loginButton;
private UiLifecycleHelper uiHelper;
private ContextWrapper uiActivity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
setContentView(R.layout.login);
friends= new ArrayList<String>();
tv=(TextView)LoginActivity.this.findViewById(R.id.textview1);
loginButton=(Button)findViewById(R.id.button_login);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (! facebook.isSessionValid()) {
facebook.authorize(LoginActivity.this, PERMISSIONS, new LoginDialogListener());
}
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d("FB Demo App", "onActivityResult(): " + requestCode);
facebook.authorizeCallback(requestCode, resultCode, data);
}
private class LoginDialogListener implements DialogListener {
public void onComplete(Bundle values) {
saveCredentials(facebook);
getAlbumsData task = new getAlbumsData();
task.execute();
mHandler.post(new Runnable() {
public void run() {
//--- Intent i = new Intent(LoginActivity.this,FrndActivity.class);
//--- i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//--- startActivity(i);
}
});
mAsyncRunner.request("me/friends", new FriendsRequestListener());
}
private void saveCredentials(Facebook facebook) {
// TODO Auto-generated method stub
}
public void onFacebookError(FacebookError error) {
showToast("Authentication with Facebook failed!");
}
public void onError(DialogError error) {
showToast("Authentication with Facebook failed!");
}
public void onCancel() {
showToast("Authentication with Facebook cancelled!");
}
}
public void showToast(String string) {
// TODO Auto-generated method stub
}
public class getAlbumsData {
public void execute() {
// TODO Auto-generated method stub
}
}
private class FriendsRequestListener implements RequestListener {
String friendData;
//Method runs when request is complete
public void onComplete(String response, Object state) {
Log.v("", "FriendListRequestONComplete");
//Create a copy of the response so i can be read in the run() method.
friendData = response;
Log.v("friendData--", ""+friendData);
//Create method to run on UI thread
LoginActivity.this.runOnUiThread(new Runnable() {
public void run() {
try {
//Parse JSON Data
JSONObject json;
json = Util.parseJson(friendData);
//Get the JSONArry from our response JSONObject
JSONArray friendArray = json.getJSONArray("data");
Log.v("friendArray--", ""+friendArray);
for(int i = 0; i< friendArray.length(); i++)
{
JSONObject frnd_obj = friendArray.getJSONObject(i);
friends.add(frnd_obj.getString("name")+"~~~"+frnd_obj.getString("id"));
}
Intent ide = new Intent(LoginActivity.this,FrndActivity.class);
ide.putStringArrayListExtra("friends", friends);
// ide.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(ide);
// ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1,android.R.id.text1, friends_list);
// lv.setAdapter(adapter);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FacebookError e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
#Override
public void onIOException(IOException e, Object state) {
// TODO Auto-generated method stub
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
// TODO Auto-generated method stub
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
// TODO Auto-generated method stub
}
#Override
public void onFacebookError(FacebookError e, Object state) {
// TODO Auto-generated method stub
}
}

Please pay attention...the AsyncFacebookRunner is deprecated,as it's shown on the Facebook documentation.
https://developers.facebook.com/docs/reference/android/current/AsyncFacebookRunner/

Related

how to get the facebooklogin with custom login button

I am trying to get the facebook login for authentication in my app it is done but the problem is when i tried to logout inside the logout its not working can anyone help me please. the code is give below
public class Facebooklogin extends Activity implements OnClickListener
{
ImageView ivFacebook,btnLogout;
Facebook fb;
public static final String MyPREFERENCES = "MyPrefs" ;
String APP_ID;
private SharedPreferences sp;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loginscreen);
sp=getPreferences(Context.MODE_PRIVATE);
String access_token=sp.getString("access_token", null);
long expires=sp.getLong("access_expires", 0);
if(access_token !=null)
{
fb.setAccessToken(access_token);
}
if(expires !=0)
{
fb.setAccessExpires(expires);
}
APP_ID=getString(R.string.facebook_app_id);
fb=new Facebook(APP_ID);
ivFacebook=(ImageView)findViewById(R.id.ivFacebook);
ivFacebook.setOnClickListener(this);
}
#SuppressWarnings("deprecation")
private void updateButton()
{
// TODO Auto-generated method stub
Intent i = new Intent(Facebooklogin.this,MainAct.class);
startActivity(i);
}
#SuppressWarnings("deprecation")
public void onClick(View v)
{
// TODO Auto-generated method stub
if(fb.session != null && fb.session.isOpened())
{
try {
// fb.logout(getApplicationContext());
updateButton();
} catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else {
fb.authorize(Facebooklogin.this, new String[] {"email"},new DialogListener()
{
#Override
public void onFacebookError(FacebookError e)
{
// TODO Auto-generated method stub
}
#Override
public void onError(DialogError e)
{
// TODO Auto-generated method stub
}
#Override
public void onComplete(Bundle values)
{
// TODO Auto-generated method stub
Editor editor=sp.edit();
editor.putString("access_token", fb.getAccessToken());
editor.putLong("access_expires", fb.getAccessExpires());
editor.commit();
updateButton();
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
}
});
}
}
#SuppressWarnings("deprecation")
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
fb.authorizeCallback(requestCode, resultCode, data);
}
I do not see any lines for logout here, you can clear the session in order to perform the logout.
if (session != null){
session.closeAndClearTokenInformation();
session = null;
}
Also remove the tokens from the shared preferences and , note that you are using tan older version of facebook api here. Above methods are deprecated now.

Facebook returns data on running application multiple times in android

I am trying to retrieve my facebook pages information.But when I install and run the app first time it gives me.
{"error":{"message":"An active access token must be used to query information about the current user.","type":"OAuthException","code":2500}}
and the next time when I run the application it returns me the correct result.Why this is happening.I want it to return the data the first time i run the app after installation.
Here's my facebook sdk code:
private String access_Token="";
private final String APP_ID="MY_APP_ID";
private final String[] PERMS = new String[] { "publish_stream","manage_pages" };
private Bundle params=new Bundle();
private SharedPreferences sharedPrefs;
private AsyncFacebookRunner mAsyncRunner;
private Facebook mfacebook;
private TextView view;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view=(TextView)findViewById(R.id.Mozi);
this.SetConnection(); //Initialize Fb
this.getAccessToken(); //GetAccessToken
this.CheckSessionExpiry(); //Create Session with permissions if expired
this.RetrieveUserPages();
// this.EnableFBLogout();
}
public void onResume() {
super.onResume();
mfacebook.extendAccessTokenIfNeeded(this, null);
}
private void EnableFBLogout()
{
mAsyncRunner.logout(getApplicationContext(), new RequestListener() {
#Override
public void onComplete(String response, Object state) {
String method = "DELETE";
Bundle params = new Bundle();
/*
* this will revoke 'publish_stream' permission
* Note: If you don't specify a permission then this will de-authorize the application completely.
*/
params.putString("permission", "publish_stream");
mAsyncRunner.request("/me/permissions", params, method,new RequestListener() {
#Override
public void onMalformedURLException(MalformedURLException e, Object state) {
// TODO Auto-generated method stub
Log.e("PerMalform",e.getMessage());
}
#Override
public void onIOException(IOException e, Object state) {
// TODO Auto-generated method stub
Log.e("PerMalform",e.getMessage());
}
#Override
public void onFileNotFoundException(FileNotFoundException e, Object state) {
// TODO Auto-generated method stub
Log.e("PerMalform",e.getMessage());
}
#Override
public void onFacebookError(FacebookError e, Object state) {
// TODO Auto-generated method stub
Log.e("PerMalform",e.getMessage());
}
#Override
public void onComplete(String response, Object state) {
// TODO Auto-generated method stub
Log.e("PerMalform",response);
}
}, null);
}
#Override
public void onIOException(IOException e, Object state) {}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {}
#Override
public void onFacebookError(FacebookError e, Object state) {}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
this.mfacebook.authorizeCallback(requestCode, resultCode, data);
}
private void getAccessToken()
{
sharedPrefs= getPreferences(MODE_PRIVATE);
String access_token = sharedPrefs.getString("access_token", null);
long expires = sharedPrefs.getLong("access_expires", 0);
if(access_token != null) {
mfacebook.setAccessToken(access_token);
}
if(expires != 0) {
mfacebook.setAccessExpires(expires);
}
}
private void CheckSessionExpiry()
{
if(!mfacebook.isSessionValid()) {
mfacebook.authorize(this, this.PERMS , new DialogListener() {
#Override
public void onComplete(Bundle values) {
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putString("access_token", mfacebook.getAccessToken());
editor.putLong("access_expires", mfacebook.getAccessExpires());
editor.commit();
}
#Override
public void onFacebookError(FacebookError error) {
Log.e("mozi1",error.toString());
}
#Override
public void onError(DialogError e) {
Log.e("mozi2",e.toString());
}
#Override
public void onCancel() {
Log.e("sad","ww");
}
});
}
}
private void SetConnection()
{
this.mfacebook=new Facebook(this.APP_ID);
this.mAsyncRunner=new AsyncFacebookRunner(mfacebook);
}
private void RetrieveUserPages()
{
this.params.putString(Facebook.TOKEN, mfacebook.getAccessToken());
this.mAsyncRunner.request("me/accounts", this.params, "GET", new RequestListener() {
#Override
public void onMalformedURLException(MalformedURLException e, Object state) {
// TODO Auto-generated method stub
Log.e("Malformed",e.getMessage());
}
#Override
public void onIOException(IOException e, Object state) {
// TODO Auto-generated method stub
Log.e("IO",e.getMessage());
}
#Override
public void onFileNotFoundException(FileNotFoundException e, Object state) {
// TODO Auto-generated method stub
Log.e("FNF",e.getMessage());
}
#Override
public void onFacebookError(FacebookError e, Object state) {
// TODO Auto-generated method stub
Log.e("FBERR",e.getMessage());
}
#Override
public void onComplete(String response, Object state) {
// TODO Auto-generated method stub
Log.i("responsefromFB",response); //here the response is an error for the first time and data the second time.
// view.setText(response);
}
}, null);
}
mfacebook.authorize() is asynchronous, which means that code after the authorize() method is run even though authorize() is not completed. Because you call this.RetrieveUserPages() right after mfacebook.authorize(), you are calling
this.params.putString(Facebook.TOKEN, mfacebook.getAccessToken());
before mfacebook.authorize() has completed, so mfacebook.getAcessToken() returns null.
The answer to your issue is to only call this.RetrieveUserPages() in the onComplete method of mfacebook.authorize() to ensure that your access token is set before trying to retrieve it.
Let me know if that helps!

Facebook api not working in my emulator?

I have implemented login with facebook in my project.
The code is below:
public class login extends Activity{
ImageView fbtn;
private SharedPreferences mPrefs;
static Facebook facebook = new Facebook("271089732997803");
String access_token;
long expires;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.yf_login1);
mPrefs = getPreferences(MODE_PRIVATE);
access_token = mPrefs.getString("access_token", null);
expires = mPrefs.getLong("access_expires", 0);
fbtn = (ImageView)findViewById(R.id.fbtn);
fbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(access_token != null) {
facebook.setAccessToken(access_token);
Log.v("access_token", access_token);
}
if(expires != 0) {
facebook.setAccessExpires(expires);
Log.i("expires", ""+expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(login.this,new String[] {}, new DialogListener() {
#Override
public void onComplete(Bundle values) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token", facebook.getAccessToken());
editor.putLong("access_expires", facebook.getAccessExpires());
editor.commit();
}
#Override
public void onFacebookError(FacebookError error) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onCancel() {
}
});
}
else{
startActivity(new Intent(login.this,ChooseTeam.class));
}
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
#Override
public void onResume() {
super.onResume();
facebook.extendAccessTokenIfNeeded(this, null);
}
Now my question is when i click on the the fb button it will load the progress bar and after 30-40 second it returns the same page.
The most important thing is when i run the same project in my another pc it will run perfectly, opens the dialog of login for the facebook and got the value in my preferences. But in my case i cannot even get the preferences made in my data.
What will be the problem in my emulator?? I am using eclipse galilio and sdk20.
I got the solution actually my antivirus is blocked the internet for the emulator. So i have uninstalled the antivirus and run the app and it works.
Thank you all for helping me out.
Try this....
and use this Permission for Share in Facebook..
private String[] mPermissions={"publish_stream"};
mFb.authorize(SettingActivity.this, mPermissions,new com.fbintegration.Facebook.DialogListener()
{
public void onFacebookError(FacebookError e)
{
}
public void onError(DialogError e)
{
}
public void onComplete(Bundle values)
{
SessionStore.save(mFb, getApplicationContext());
}
public void onCancel()
{
// TODO Auto-generated method stub
}
});
and this is Facebook Connector Class....
public class FacebookConnector
{
private Facebook facebook = null;
private Context context;
private String[] permissions;
private Handler mHandler;
private Activity activity;
//private SessionListener mSessionListener = new SessionListener();;
public FacebookConnector(String appId,Activity activity,Context context,String[] permissions)
{
this.facebook = new Facebook(appId);
SessionStore.restore(facebook, context);
this.context=context;
this.permissions=permissions;
this.mHandler = new Handler();
this.activity=activity;
}
public void login()
{
if (!facebook.isSessionValid())
{
facebook.authorize(this.activity, this.permissions,new LoginDialogListener());
}
}
/*public void logout()
{
SessionEvents.onLogoutBegin();
AsyncFacebookRunner asyncRunner = new AsyncFacebookRunner(this.facebook);
asyncRunner.logout(this.context, new LogoutRequestListener());
}*/
public void postMessageOnWall(String msg)
{
if (facebook.isSessionValid())
{
Bundle parameters = new Bundle();
parameters.putString("message", msg);
try
{
//JSONObject response=Util.parseJson(facebook.request("me/feed", parameters,"POST"));
String response = facebook.request("me/feed", parameters,"POST");
System.out.println(response);
}
catch (IOException e)
{
e.printStackTrace();
}
}
else
{
}
}
private final class LoginDialogListener implements DialogListener
{
public void onComplete(Bundle values)
{
SessionEvents.onLoginSuccess();
}
public void onFacebookError(FacebookError error)
{
SessionEvents.onLoginError(error.getMessage());
}
public void onError(DialogError error)
{
SessionEvents.onLoginError(error.getMessage());
}
public void onCancel()
{
SessionEvents.onLoginError("Action Canceled");
}
}
private class SessionListener implements AuthListener, LogoutListener
{
public void onAuthSucceed()
{
SessionStore.save(facebook, context);
}
public void onAuthFail(String error) {
}
public void onLogoutBegin() {
}
public void onLogoutFinish() {
SessionStore.clear(context);
}
}
public Facebook getFacebook()
{
return this.facebook;
}
}

Calling new activity after facebook login | Android

I have 2 activities in my android application. On the first one, I ask the user to login with facebook. after the user logs in, i collect the user data such as email, name and call a new activity passing these parameters to it. below is my facebook authorize method:
public void loginFB(final View v)
{
facebook.authorize(this, new String[] { "email", "read_stream" }, new DialogListener() {
#Override
public void onComplete(Bundle values) {
this.getlogininfo(v);
}
private void getlogininfo(View v) {
// TODO Auto-generated method stub
logininfo(v);
}
#Override
public void onFacebookError(FacebookError error) {}
#Override
public void onError(DialogError e) {}
#Override
public void onCancel() {}
});
}
Below is my logininfo() method:
public void logininfo(final View v){
mAsyncRunner.request("me", new RequestListener(){
#Override
public void onComplete(String response, Object state) {
try{
Log.d("Profile", response.toString());
JSONObject json = Util.parseJson(response);
final String fname1 = json.getString("first_name");
final String lname1 = json.getString("last_name");
final String email = json.getString("email");
Intent fbLogged = new Intent();
Bundle passData = new Bundle();
passData.putString("fname", fname1);
passData.putString("lname", lname1);
passData.putString("email", email);
fbLogged.putExtras(passData);
fbLogged.setClass(v.getContext(), RequestFb.class);
startActivity(fbLogged);
}
catch(JSONException e){
Log.w("This", "eror");
}
}
#Override
public void onIOException(IOException e, Object state) {
// TODO Auto-generated method stub
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
// TODO Auto-generated method stub
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
// TODO Auto-generated method stub
}
#Override
public void onFacebookError(FacebookError e, Object state) {
// TODO Auto-generated method stub
}
});
}
So, my new activity is starting on OnComplete() of getting the user data.
This works perfectly, but when the user clicks login, and logs in with facebook, the first activity page remains on the screen for a few seconds and then the next activity is called. there is a lag. How can I fix the lag? When the user clicks login and after the login is authorized, it should take the user to directly the second activity. Any suggestions?
Thanks!
It's simple, you are running the fb graph request in a new thread (using the AsyncRunner) but only when that request is completed you start the new activity and that's why you get that "lag".
You should run the graph request in the new activity instead of the first one, something like:
public void loginFB(final View v) {
facebook.authorize(this, new String[] { "email", "read_stream" }, new DialogListener() {
#Override
public void onComplete(Bundle values) {
Intent fbLogged = new Intent(v.getContext(), RequestFb.class);
startActivity(fbLogged);
}
#Override
public void onFacebookError(FacebookError error) {}
#Override
public void onError(DialogError e) {}
#Override
public void onCancel() {}
});
}
public class RequestFb extend Activity {
protected void onCreate(Bundle savedInstanceState) {
Facebook facebook = new Facebook("YOUR_APP_ID");
AsyncFacebookRunner asyncRunner = new AsyncFacebookRunner(facebook);
asyncRunner.request("me", new RequestListener(){
try {
final JSONObject json = Util.parseJson(response);
final String fname1 = json.getString("first_name");
final String lname1 = json.getString("last_name");
final String email = json.getString("email");
runOnUiThread(new Runnable() {
public void run() {
// use the data
}
});
}
catch(JSONException e) {
Log.w("This", "eror");
}
});
}
}

getting facebook events

I am trying to get a list of facebook events with the name events host and a start time. I am using the official facebook sdk for android.
But for some reason whenever I click get event in the application it will load then retrieve no data.
Any help at all would be brilliant I have been stuck on this for weeks
My code:
public static final String APP_ID = "";
private static final String[] PERMISSIONS =
new String[]{ "offline_access", "read_stream",
"publish_stream","create_event","user_events","friends_events",
"publish_checkins", "friends_checkins","read_friendlists" };
private TextView mText;
private Handler mHandler = new Handler();
private ProgressDialog mSpinner;
private final ArrayList<Events> events = new ArrayList<Events>();
private EventsArrayAdapter eventsArrayAdapter;
private ListView listView;
private Facebook mFacebook;
private AsyncFacebookRunner mAsyncRunner;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Make sure the app client_app has been set
if (APP_ID == null) {
Util.showAlert(this,
"Warning", "Facebook Applicaton ID must be set...");
}
// Initialize the content view
setContentView(R.layout.main);
// Get the status text line resource
mText = (TextView) workdammit.this.findViewById(R.id.txt);
// Setup the ListView Adapter that is loaded when selecting "get events"
listView = (ListView) findViewById(R.id.eventsview);
eventsArrayAdapter = new EventsArrayAdapter(this, R.layout.rowlayout, events);
listView.setAdapter(eventsArrayAdapter);
// Define a spinner used when loading the events over the network
mSpinner = new ProgressDialog(listView.getContext());
mSpinner.requestWindowFeature(Window.FEATURE_NO_TITLE);
mSpinner.setMessage("Loading...");
// Initialize the Facebook session
mFacebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(mFacebook);
}
//////////////////////////////////////////////////////////////////////
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d("FB Sample App", "onActivityResult(): " + requestCode);
mFacebook.authorizeCallback(requestCode, resultCode, data);
}
//////////////////////////////////////////////////////////////////////
// Get events request listener
//////////////////////////////////////////////////////////////////////
/**
* eventsRequestListener implements a request lister/callback
* for "get events" requests
*/
public class EventsRequestListener implements
com.facebook.android.AsyncFacebookRunner.RequestListener {
/**
* Called when the request to get events has been completed.
* Retrieve and parse and display the JSON stream.
*/
public void onComplete(final String response) {
mSpinner.dismiss();
try {
// process the response here: executed in background thread
Log.d("Facebook-Example-events Request", "response.length(): " + response.length());
Log.d("Facebook-Example-events Request", "Response: " + response);
final JSONObject json = new JSONObject(response);
JSONArray d = json.getJSONArray("data");
int l = (d != null ? d.length() : 0);
Log.d("Facebook-Example-events Request", "d.length(): " + l);
for (int i=0; i<l; i++) {
JSONObject o = d.getJSONObject(i);
String n = o.getString("name");
String h = o.getString("host");
String L = o.getString("location");
Events f = new Events();
f.host = h;
f.name = n;
f.location =L;
events.add(f);
}
// Only the original owner thread can touch its views
workdammit.this.runOnUiThread(new Runnable() {
public void run() {
eventsArrayAdapter = new EventsArrayAdapter(
workdammit.this, R.layout.rowlayout, events);
listView.setAdapter(eventsArrayAdapter);
eventsArrayAdapter.notifyDataSetChanged();
}
});
} catch (JSONException e) {
Log.w("Facebook-Example", "JSON Error in response");
}
}
#Override
public void onComplete(String response, Object state) {
mSpinner.dismiss();
}
#Override
public void onIOException(IOException e, Object state) {
mSpinner.dismiss();
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
mSpinner.dismiss();
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
mSpinner.dismiss();
}
#Override
public void onFacebookError(FacebookError e, Object state) {
mSpinner.dismiss();
}
}
//////////////////////////////////////////////////////////////////////
// Wall Post request listener
//////////////////////////////////////////////////////////////////////
/**
* WallPostRequestListener implements a request lister/callback
* for "wall post requests"
*/
public class WallPostRequestListener implements
com.facebook.android.AsyncFacebookRunner.RequestListener {
/**
* Called when the wall post request has completed
*/
public void onComplete(final String response) {
Log.d("Facebook-Example", "Got response: " + response);
}
#Override
public void onComplete(String response, Object state) {
// TODO Auto-generated method stub
}
#Override
public void onIOException(IOException e, Object state) {
// TODO Auto-generated method stub
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
// TODO Auto-generated method stub
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
// TODO Auto-generated method stub
}
#Override
public void onFacebookError(FacebookError e, Object state) {
// TODO Auto-generated method stub
}
}
//////////////////////////////////////////////////////////////////////
// Wall post dialog completion listener
//////////////////////////////////////////////////////////////////////
/**
* WallPostDialogListener implements a dialog lister/callback
*/
public class WallPostDialogListener implements
com.facebook.android.Facebook.DialogListener {
/**
* Called when the dialog has completed successfully
*/
public void onComplete(Bundle values) {
final String postId = values.getString("post_id");
if (postId != null) {
Log.d("FB Sample App", "Dialog Success! post_id=" + postId);
mAsyncRunner.request(postId, new WallPostRequestListener());
} else {
Log.d("FB Sample App", "No wall post made");
}
}
#Override
public void onCancel() {
// No special processing if dialog has been canceled
}
#Override
public void onError(DialogError e) {
// No special processing if dialog has been canceled
}
#Override
public void onFacebookError(FacebookError e) {
// No special processing if dialog has been canceled
}
}
/////////////////////////////////////////////////////////
// Login / Logout Listeners
/////////////////////////////////////////////////////////
/**
* Listener for login dialog completion status
*/
private final class LoginDialogListener implements
com.facebook.android.Facebook.DialogListener {
/**
* Called when the dialog has completed successfully
*/
public void onComplete(Bundle values) {
// Process onComplete
Log.d("FB Sample App", "LoginDialogListener.onComplete()");
// Dispatch on its own thread
mHandler.post(new Runnable() {
public void run() {
mText.setText("Facebook login successful. Press Menu...");
}
});
}
/**
*
*/
public void onFacebookError(FacebookError error) {
// Process error
Log.d("FB Sample App", "LoginDialogListener.onFacebookError()");
}
/**
*
*/
public void onError(DialogError error) {
// Process error message
Log.d("FB Sample App", "LoginDialogListener.onError()");
}
/**
*
*/
public void onCancel() {
// Process cancel message
Log.d("FB Sample App", "LoginDialogListener.onCancel()");
}
}
/**
* Listener for logout status message
*/
private class LogoutRequestListener implements RequestListener {
/** Called when the request completes w/o error */
public void onComplete(String response) {
// Only the original owner thread can touch its views
workdammit.this.runOnUiThread(new Runnable() {
public void run() {
mText.setText("Thanks for using FB Sample App. Bye bye...");
events.clear();
eventsArrayAdapter.notifyDataSetChanged();
}
});
// Dispatch on its own thread
mHandler.post(new Runnable() {
public void run() {
}
});
}
#Override
public void onComplete(String response, Object state) {
// TODO Auto-generated method stub
}
#Override
public void onIOException(IOException e, Object state) {
// TODO Auto-generated method stub
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
// TODO Auto-generated method stub
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
// TODO Auto-generated method stub
}
#Override
public void onFacebookError(FacebookError e, Object state) {
// TODO Auto-generated method stub
}
}
///////////////////////////////////////////////////////////////////
// Menu handlers
///////////////////////////////////////////////////////////////////
/**
* Invoked at the time to create the menu
* #param menu is the menu to create
*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
/**
* Invoked when preparing to display the menu
* #param menu is the menu to prepare
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem loginItem = menu.findItem(R.id.login);
MenuItem postItem = menu.findItem(R.id.wallpost);
MenuItem geteventsItem = menu.findItem(R.id.getevent);
if (mFacebook.isSessionValid()) {
loginItem.setTitle("Logout");
postItem.setEnabled(true);
geteventsItem.setEnabled(true);
} else {
loginItem.setTitle("Login");
postItem.setEnabled(false);
geteventsItem.setEnabled(false);
}
loginItem.setEnabled(true);
return super.onPrepareOptionsMenu(menu);
}
/**
* Invoked when a menu item has been selected
* #param item is the selected menu items
*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Login/logout toggle
case R.id.login:
// Toggle the button state.
// If coming from login transition to logout.
if (mFacebook.isSessionValid()) {
AsyncFacebookRunner asyncRunner = new AsyncFacebookRunner(mFacebook);
asyncRunner.logout(this.getBaseContext(), new LogoutRequestListener());
} else {
// Toggle the button state.
// If coming from logout transition to login (authorize).
mFacebook.authorize(this, PERMISSIONS, new LoginDialogListener());
}
break;
// Wall Post
case R.id.wallpost: // Wall Post
mFacebook.dialog(workdammit.this, "stream.publish", new WallPostDialogListener());
break;
// Get Friend's List
case R.id.getevents: // Wall Post
// Get the authenticated user's events
mSpinner.show();
mAsyncRunner.request("me/events", new EventsRequestListener());
break;
default:
return false;
}
return true;
}
}

Categories

Resources