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;
}
}
Related
I am writing a log in fragment that hosts Facebook and Google+ sign in. The fragment is a parent fragment for three fragments with user content that are called with view pager after successful log in. I am storing email and service name in shared preferences upon retrieval from Google or Facebook, and then if successful the view pager is displayed with user fragments. Facebook log in works fine but when I start Google+ sign in it does not get to the onConnected callback method. When I switch to other tabs and return to log in fragment it is somehow triggered and I get user fragments. How can i trigger the onConnected method upon pressing the Google+ sign in button?
to ensure the onActivityResult is called i added this in main activity
MainActivity.java
#Override
protected void onActivityResult(int arg0, int arg1, Intent arg2) {
// TODO Auto-generated method stub
super.onActivityResult(arg0, arg1, arg2);
LoginFragment lf = (LoginFragment)getSupportFragmentManager().findFragmentByTag("Login");
if (lf != null) {
lf.onActivityResult(arg0, arg1, arg2);
}
}
LoginFragment.java
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
// Session class instance
mSession = new SessionManager(getActivity());
setupGoogleplus();
loginButton = (SignInButton) getActivity().findViewById(R.id.sign_in_button);
loginButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (!mPlusClient.isConnected()) {
if (mConnectionResult == null) {
mConnectionProgressDialog.show();
} else {
try {
mConnectionResult.startResolutionForResult(getActivity(), REQUEST_CODE_RESOLVE_ERR);
} catch (SendIntentException e) {
// Try connecting again.
mConnectionResult = null;
mPlusClient.connect();
}
}
}
}
});
setupViewPager();
if (mSession.isLoggedIn()) {
onLoged();
}
}
private void setupViewPager() {
mMyFragmentPagerAdapter = new MyFragmentPagerAdapter(getChildFragmentManager());
mViewPager = (ViewPager) getActivity().findViewById(R.id.pager);
}
private void setupGoogleplus() {
// google+ part
mPlusClient = new PlusClient.Builder(getSherlockActivity(), new ConnectionCallbacks() {
#Override
public void onConnected(Bundle connectionHint) {
String accountName = mPlusClient.getAccountName();
// new
// DownloadImageTask(userPicture).execute(mPlusClient.getCurrentPerson().getImage().getUrl());
// Toast.makeText(getActivity(), accountName + " is connected.",
// Toast.LENGTH_LONG).show();
mConnectionProgressDialog.dismiss();
mSession.createLoginSession(mPlusClient.getCurrentPerson().getName().getGivenName().toString(), mPlusClient.getAccountName(), "Google+");
}
#Override
public void onDisconnected() {
Log.d(TAG, "disconnected");
}
}, new OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult result) {
if (mConnectionProgressDialog.isShowing()) {
// The user clicked the sign-in button already. Start to
// resolve
// connection errors. Wait until onConnected() to dismiss
// the
// connection dialog.
if (result.hasResolution()) {
try {
result.startResolutionForResult(getActivity(), REQUEST_CODE_RESOLVE_ERR);
} catch (SendIntentException e) {
mPlusClient.connect();
}
}
}
// Save the result and resolve the connection failure upon a
// user click.
mConnectionResult = result;
}
}).setActions("http://schemas.google.com/AddActivity", "http://schemas.google.com/BuyActivity").build();
mConnectionProgressDialog = new ProgressDialog(getActivity());
mConnectionProgressDialog.setMessage("Signing in...");
}
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (state.isOpened()) {
Log.i(TAG, "Logged in...");
// Request user data and show the results
Request.newMeRequest(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
// TODO Auto-generated method stub
if (user != null) {
// Display the parsed user info
// Set the id for the ProfilePictureView
// view that in turn displays the profile picture.
// profilePictureView.setProfileId(user.getId());
// Set the Textview's text to the user's name.
mSession.createLoginSession(user.getName(), user.getProperty("email").toString(), "Facebook");
onLoged();
}
}
}).executeAsync();
} else if (state.isClosed()) {
Log.i(TAG, "Logged out...");
}
}
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
}
};
#Override
public void onActivityResult(int requestCode, int responseCode, Intent intent) {
if (requestCode == REQUEST_CODE_RESOLVE_ERR) {
mConnectionResult = null;
mPlusClient.connect();
} else {
uiHelper.onActivityResult(requestCode, responseCode, intent);
}
super.onActivityResult(requestCode, responseCode, intent);
}
private static class MyFragmentPagerAdapter extends FragmentPagerAdapter {
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new FirstFragment();
case 1:
return new SecondFragment();
case 2:
return new ThirdFragment();
}
return null;
}
#Override
public int getCount() {
return NUMBER_OF_PAGES;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "1";
case 1:
return "2";
case 2:
return "3";
}
return null;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.login_fragment, container, false);
authButton = (LoginButton) view.findViewById(R.id.authButton);
authButton.setFragment(this);
authButton.setReadPermissions(Arrays.asList("email"));
return view;
}
#Override
public void onResume() {
super.onResume();
uiHelper.onResume();
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
}
#Override
public void onStart() {
mPlusClient.connect();
super.onStart();
}
#Override
public void onStop() {
super.onStop();
mPlusClient.disconnect();
}
public void googleLogout() {
if (mPlusClient.isConnected()) {
mPlusClient.clearDefaultAccount();
mPlusClient.disconnect();
mPlusClient.connect();
mSession.logoutUser();
}
}
public void onLoged() {
mViewPager.setAdapter(mMyFragmentPagerAdapter);
mViewPager.setVisibility(View.VISIBLE);
authButton.setVisibility(View.INVISIBLE);
loginButton.setVisibility(View.INVISIBLE);
}
public void onNotLoged() {
mViewPager.setAdapter(null);
mViewPager.setVisibility(View.INVISIBLE);
authButton.setVisibility(View.VISIBLE);
loginButton.setVisibility(View.VISIBLE);
}}
In onConnected method I call mySession object creation (shared preferences) to store the data and onLoged to display user fragments. Why do I have to switch tabs a few times for onConnected to be called?
Because the resolution for the connection failure was started with startIntentSenderForResult and the code REQUEST_CODE_RESOLVE_ERR, you need to capture the result inside Activity.onActivityResult.
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
if (requestCode == REQUEST_CODE_RESOLVE_ERR && responseCode == RESULT_OK) {
mConnectionResult = null;
mPlusClient.connect();
}
}
So in your case you should call mPlusClient.connect(); in LoginFragment onActivityResult after all needed checks.
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/
I am trying to show a toast when click on a button that button request's a listener. I am logging out through this button and i want to show toast on loggout completion so i put toast in onComplete method of request Listener. Here is my complete code
HomeActivity which contains button listeners
public class HomeActivity extends Activity implements OnClickListener{
private static final String TAG = "Facebook";
private Button mLogin, mLogout, mShare;
private Facebook facebook;
private AsyncFacebookRunner abRunner;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_home);
//mLogin.setBackgroundColor(Color.BLUE);
// Initialize facebook objects
facebook = new Facebook("479652662068145");
abRunner = new AsyncFacebookRunner(facebook);
// Setup VIews
mLogin= (Button) findViewById(R.id.Login);
mLogout= (Button) findViewById(R.id.Logout);
mLogin.setOnClickListener(this);
mLogout.setOnClickListener(this);
}
#Override
public void onClick(View v){
int id = v.getId();
switch(id){
case R.id.Login:
FacebookLoginDialog login = new FacebookLoginDialog();
facebook.authorize(this, login);
break;
case R.id.Logout:
FacebookLogoutRequest logout = new FacebookLogoutRequest(this);
abRunner.logout(this, logout);
break;
default:
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_home, menu);
return true;
}
}
And my RequestListener Code
public class FacebookLogoutRequest implements RequestListener{
private Context context;
public FacebookLogoutRequest (Context context){
this.context= context;
}
public void onComplete(String response, Object state) {
Toast toast = Toast.makeText(context, "You Are Logged Out", Toast.LENGTH_SHORT);
toast.show();
}
#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 Help I am stuck here..Thanks
Use Activity instead of Context because context is not for UI reference
public class FacebookLogoutRequest implements RequestListener{
private Activity context;
public FacebookLogoutRequest (Activity context){
this.context= context;
}
public void onComplete(String response, Object state) {
Toast toast = Toast.makeText(context, "You Are Logged Out", Toast.LENGTH_SHORT);
toast.show();
}
#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
}
}
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!
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");
}
});
}
}