How to get Facebook details after log-in in android? - android

I am building an android application where user log-in in Facebook
page.
Here is the code -
package loginpck;
public class MainActivity extends Activity {
ImageView btnfb;
// Your Facebook APP ID
private static String APP_ID = "appid";
// Instance of Facebook Class
private Facebook facebook = new Facebook(APP_ID);
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
mAsyncRunner = new AsyncFacebookRunner(facebook);
btnfb = (ImageView) findViewById(R.id.btnfacebook);
btnfb.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
loginToFacebook();
}
});
}
private class ImagePagerAdapter extends PagerAdapter {
private int[] mImages = new int[] {
R.drawable.chiang_mai,
R.drawable.himeji,
R.drawable.petronas_twin_tower,
R.drawable.ulm
};
#Override
public int getCount() {
return mImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = MainActivity.this;
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(
R.dimen.padding_medium);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setImageResource(mImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
facebook.setAccessToken(access_token);
Log.d("FB Sessions", "" + facebook.isSessionValid());
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this,
new String[] { "email", "publish_stream" },
new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#SuppressWarnings("deprecation")
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
}
When I move to other Activity I need to toast the user details like
name, image and profile detail's.
How can I get the user detail's ?
Here is second activity :
public class BallDropActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.balldroplayout);
}
}

first create your project and get app. id then pass the cod in your code like this
public static final String mAPP_ID = "Your APP ID";
Facebook mFacebook= new Facebook(mAPP_ID);
and setOnClickListener on your button in On Create()
// facebook login button click event
try{
//mFacebook.logout(LoginActivity.this);
((Button)findViewById(R.id.loginPageFaceBookButton)).setOnClickListener(loginButtonListener);
SessionStore.restore(mFacebook,LoginPage.this);
}
catch (Exception e) {
Toast.makeText( LoginPage.this,"Exception"+e.toString(), Toast.LENGTH_SHORT).show();
}}
// loginButtonListener
//----------------------------------------------
private OnClickListener loginButtonListener = new OnClickListener()
{
public void onClick( View v )
{
if(!mFacebook.isSessionValid() )
{
mFacebook.authorize(LoginPage.this, new String[] {"publish_stream","email","user_groups","read_stream","user_about_me","offline_access"},Facebook.FORCE_DIALOG_AUTH, new LoginDialogListener());
}
else
{
try
{
JSONObject json = Util.parseJson(mFacebook.request("me"));
facebookID = json.getString("id");
facebookEmail = json.getString("email");
faceBooklastName=json.getString("last_name");
faceBookFirstName=json.getString("first_name");
}
catch (Exception e)
{
// TODO: handle exception
//Toast.makeText( LoginActivity.this,"Exception FB "+e.toString(), Toast.LENGTH_SHORT).show();
}
catch( FacebookError error )
{
Toast.makeText( LoginPage.this,error.toString(), Toast.LENGTH_SHORT).show();
}
}
}};
//onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
mFacebook.authorizeCallback(requestCode, resultCode, data);
}
// DialogListener CLASS STATRT HERE.
public final class LoginDialogListener implements DialogListener
{
public void onComplete(Bundle values)
{
try
{
JSONObject json = Util.parseJson(mFacebook.request("me"));
facebookID = json.getString("id");
facebookEmail = json.getString("email");
SessionStore.save(mFacebook, LoginPage.this); Toast.makeText( LoginPage.this,"facebookID :"+facebookID+" \n "+"facebookEmail : "+facebookEmail, Toast.LENGTH_SHORT).show();
}
catch( Exception error )
{
Toast.makeText( LoginPage.this, error.toString(), Toast.LENGTH_SHORT).show();
}
catch( FacebookError error )
{
Toast.makeText( LoginPage.this, error.toString(), Toast.LENGTH_SHORT).show();
}
}
public void onFacebookError(FacebookError error) {
Toast.makeText( LoginPage.this, "Something went wrong. Please try again.1"+error.toString(), Toast.LENGTH_LONG).show();
}
public void onError(DialogError error) {
Toast.makeText( LoginPage.this, "Something went wrong. Please try again.2"+error.toString(), Toast.LENGTH_LONG).show();
}
public void onCancel() {
Toast.makeText( LoginPage.this, "Something went wrong. Please try again.3", Toast.LENGTH_LONG).show();
}
/****** Facebook Login End *******/
}

Related

Using Shared Preferences with Log in with Facebook

I'm trying to save user details after logging in (with Facebook). I'm able to fetch data but can't save it. I'm using SharedPreferences but can't save it. Data is not lost when I go on some other activity, but when I click back button and re-open this activity, all data is lost. Here is my code:
Profilee.java
public class Profilee extends Fragment {
String email1, birthday1, gender1;
ImageView imageView;
static int itis = 1;
TextView texty;
LoginButton button;
LinearLayout userinput;
private CallbackManager callbackManager;
private TextView textView;
SharedPreferences pref;
private TextView email, birthday, gende;
private AccessTokenTracker accessTokenTracker;
private ProfileTracker profileTracker;
private FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
GraphRequest graphrequest = GraphRequest.newMeRequest(loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
JSONObject jsonObject = response.getJSONObject();
if (jsonObject != null) {
try {
email1 = jsonObject.getString("email");
gender1 = jsonObject.getString("gender");
birthday1 = jsonObject.getString("birthday");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "email, gender, birthday");
graphrequest.setParameters(parameters);
graphrequest.executeAsync();
AppEventsLogger.activateApp(getContext());
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
};
public Profilee() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
callbackManager = CallbackManager.Factory.create();
Toast.makeText(getContext(), "Create", Toast.LENGTH_SHORT).show();
pref = getContext().getSharedPreferences("", getContext().MODE_PRIVATE);
pref.getString("name", "asdfgh");
pref.getString("email", "qwerty");
pref.getString("gender", "zxcvb");
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {
}
};
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
}
};
accessTokenTracker.startTracking();
profileTracker.startTracking();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_profilee, container, false);
button = (LoginButton) v.findViewById(R.id.login_button);
TextView button12 = (TextView) v.findViewById(R.id.edit);
button12.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getContext(), PrifileEdit.class);
i.putExtra("st", email1);
startActivity(i);
}
});
texty = (TextView) v.findViewById(R.id.emo);
imageView = (ImageView) v.findViewById(R.id.asd);
userinput = (LinearLayout) v.findViewById(R.id.userdetail);
int unicode = 0x1F60E;
String emoji = getEmijoByUnicode(unicode);
String text = "We will never post on your wall without permission ";
texty.setText(text + emoji);
Toast.makeText(getContext(), "CreateView", Toast.LENGTH_SHORT).show();
return v;
}
public String getEmijoByUnicode(int unicode) {
return new String(Character.toChars(unicode));
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
LoginButton loginButton = (LoginButton) view.findViewById(R.id.login_button);
textView = (TextView) view.findViewById(R.id.textView);
email = (TextView) view.findViewById(R.id.emailid);
gende = (TextView) view.findViewById(R.id.gender);
birthday = (TextView) view.findViewById(R.id.birth);
loginButton.setReadPermissions("email");
loginButton.setFragment(this);
loginButton.registerCallback(callbackManager, callback);
Toast.makeText(getContext(), "ViewCreate", Toast.LENGTH_SHORT).show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
onResume();
}
}, 2000);
}
public void displayMessage(final Profile profile) {
if (itis == 1) {
if (profile != null) {
textView.setText(profile.getName());
email.setText(email1);
gende.setText(gender1);
birthday.setText(birthday1);
button.setVisibility(View.GONE);
texty.setVisibility(View.GONE);
userinput.setVisibility(View.VISIBLE);
pref = getContext().getSharedPreferences("", getContext().MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("name", String.valueOf(textView));
editor.putString("email", String.valueOf(email));
editor.putString("gender", String.valueOf(gende));
editor.commit();
}
}
}
#Override
public void onStart() {
super.onStart();
Toast.makeText(getContext(), "Start", Toast.LENGTH_SHORT).show();
}
#Override
public void onStop() {
super.onStop();
accessTokenTracker.stopTracking();
profileTracker.stopTracking();
}
#Override
public void onResume() {
super.onResume();
Profile profile = Profile.getCurrentProfile();
displayMessage(profile);
AppEventsLogger.activateApp(getContext());
}
}
I think this problem is because of displayMessage() method .
when you reopen this Activity , onResume(); method will call , and then displayMessage() .
in displayMessage() you are setting sharedprefrecens values again , and this work cause you lost previous data from this sharedprefrecens.
for solve this problem you must cut onResume codes inside onCreate method
You aren't persisting the data in SharedPreferences correctly. getText() will retrieve the text that is currently displayed in the TextView, allowing you to store it into SharedPreferences.
editor.putString("name", String.valueOf(textView)); // wrong
editor.putString("name", textView.getText().toString()); // right
You can then retrieve the value and display it on screen by calling setText().
String myEmail = pref.getString("email", "qwerty");
textView.setText(myEmail);

logout from facebook generating error

in my application, I can easily login but when ever I click on logout button, it gives me an error
I want when I click on logout button,and after that I click on login button,I get the same dialog box appear for login that ask for emailid and the password.but when I click on login button after logout, it only show me the toast displaying you are already login.
MainActivity
public class MainActivity extends Activity {
Facebook fb;
Button login,getData,logout;
ImageView ig;
String app_id;
private AsyncFacebookRunner mAsyncRunner;
private SharedPreferences mPrefs;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
app_id= getString(R.string.app_id);
fb= new Facebook(app_id);
login=(Button) findViewById(R.id.login);
logout=(Button) findViewById(R.id.logout);
getData=(Button) findViewById(R.id.getData);
// ig= (ImageView) findViewById(R.id.profile_pic);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginToFacebook();
}
});
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(fb.isSessionValid()){
logoutFromFacebook();
}
}
});
mAsyncRunner = new AsyncFacebookRunner(fb);
}
#SuppressWarnings("deprecation")
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
fb.setAccessToken(access_token);
login.setVisibility(View.VISIBLE);
// Making get profile button visible
getData.setVisibility(View.VISIBLE);
Log.d("FB Sessions", "" + fb.isSessionValid());
}
if (expires != 0) {
fb.setAccessExpires(expires);
Toast.makeText(getApplication(), "already login", Toast.LENGTH_LONG).show();
//logoutFromFacebook();
}
if (!fb.isSessionValid()) {
fb.authorize(this,
new String[] { "email", "publish_stream" },
new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
editor = mPrefs.edit();
editor.putString("access_token",
fb.getAccessToken());
editor.putLong("access_expires",
fb.getAccessExpires());
editor.commit();
// Making Login button invisible
login.setVisibility(View.VISIBLE);
// Making logout Button visible
getData.setVisibility(View.VISIBLE);
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
fb.authorizeCallback(requestCode, resultCode, data);
}
#SuppressWarnings("deprecation")
public void logoutFromFacebook() {
mAsyncRunner.logout(this, new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Logout from Facebook", response);
if (Session.getActiveSession() != null) {
//editor.remove("access_token");
mPrefs.edit();
editor.clear();
editor.commit();
Session.getActiveSession().closeAndClearTokenInformation();
} Session.setActiveSession(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) {
}
});
}
}
logcat
04-17 11:05:53.375: E/AndroidRuntime(12371): FATAL EXCEPTION: Thread-1443
04-17 11:05:53.375: E/AndroidRuntime(12371): java.lang.IllegalArgumentException: Invalid context argument
04-17 11:05:53.375: E/AndroidRuntime(12371): at android.webkit.CookieSyncManager.createInstance(CookieSyncManager.java:86)
04-17 11:05:53.375: E/AndroidRuntime(12371): at com.facebook.internal.Utility.clearCookiesForDomain(Utility.java:286)
04-17 11:05:53.375: E/AndroidRuntime(12371): at com.facebook.internal.Utility.clearFacebookCookies(Utility.java:310)
04-17 11:05:53.375: E/AndroidRuntime(12371): at com.facebook.Session.closeAndClearTokenInformation(Session.java:614)
04-17 11:05:53.375: E/AndroidRuntime(12371): at com.facebook.android.Facebook.logoutImpl(Facebook.java:665)
04-17 11:05:53.375: E/AndroidRuntime(12371): at com.facebook.android.AsyncFacebookRunner$1.run(AsyncFacebookRunner.java:89)
facebook.java
#Deprecated
public String logout(Context context) throws MalformedURLException, IOException {
return logoutImpl(context);
}
String logoutImpl(Context context) throws MalformedURLException, IOException {
checkUserSession("logout");
Bundle b = new Bundle();
b.putString("method", "auth.expireSession");
String response = request(b);
long currentTimeMillis = System.currentTimeMillis();
Session sessionToClose = null;
synchronized (this.lock) {
sessionToClose = session;
session = null;
accessToken = null;
accessExpiresMillisecondsAfterEpoch = 0;
lastAccessUpdateMillisecondsAfterEpoch = currentTimeMillis;
sessionInvalidated = false;
}
if (sessionToClose != null) {
sessionToClose.closeAndClearTokenInformation();
}
return response;
}

Why Facebook login page does not appear when I tried to re-login after I logged out in Android?

I followed this tutorial http://www.androidhive.info/2012/03/android-facebook-connect-tutorial/ to connect Facebook to my Android application. Instead of having many buttons, I have a button that will be used for both login and logout.
1) The first time I run the class, I could login and then logout successfully. And when I click on the same button to login again, the login page would not appear, however the Toast text "LOGGING IN" appear, which is after loginToFacebook() function in my if-else. Hence, I assume, it should have run the facebook login page like the first time I run the class. But the login page does not appear.
What did I do wrong? And what should I do?
2) And how do I display the username in String fbLoggedIn after logged in instead of the text "CONNECTED!!" ?
public class FacebookActivity extends Activity{
private static String APP_ID = "";
private Facebook facebook;
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
private Button backButton;
private String name = "CONNECTED!!";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_share);
facebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(facebook);
RelativeLayout fbButton = (RelativeLayout) findViewById(R.id.fbLayout);
fbButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (!facebook.isSessionValid())
{
System.out.println("Not Connected. Clicked and Login.");
loginToFacebook();
Toast.makeText(getApplicationContext(), "LOGGING IN", Toast.LENGTH_LONG).show();}
else
{
System.out.println("Connected. Logged Out.");
logoutFromFacebook();
Toast.makeText(getApplicationContext(), "LOGGED OUT", Toast.LENGTH_LONG).show();}
}
});
}
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
facebook.setAccessToken(access_token);
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this, new String[] { "email", "publish_stream" }, new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token", facebook.getAccessToken());
editor.putLong("access_expires", facebook.getAccessExpires());
editor.commit();
TextView fbUser = (TextView) findViewById(R.id.fbUser);
fbUser.setVisibility(View.VISIBLE);
String fbLoggedIn = name;
fbUser.setText(fbLoggedIn);
Toast.makeText(getApplicationContext(), "LOGGED IN AS " + name, Toast.LENGTH_LONG).show();
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
public void getProfileInformation() {
mAsyncRunner.request("me", new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response;
try {
JSONObject profile = new JSONObject(json);
// getting name of the user
final String name = profile.getString("name");
// getting email of the user
final String email = profile.getString("email");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Name: " + name + "\nEmail: " + email, Toast.LENGTH_LONG).show();
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
#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) { }
});
}
//logout from Facebook
public void logoutFromFacebook() {
mAsyncRunner.logout(this, new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Logout from Facebook", response);
if (Boolean.parseBoolean(response) == true) {
// User successfully Logged out
}
}
#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) { }
});
}
Just to be clearer, I set my if-else like this (extracted from the complete codes above).
RelativeLayout fbButton = (RelativeLayout) findViewById(R.id.fbLayout);
fbButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (!facebook.isSessionValid())
{
System.out.println("Not Connected. Clicked and Login.");
loginToFacebook();
Toast.makeText(getApplicationContext(), "LOGGING IN", Toast.LENGTH_LONG).show();}
else
{
System.out.println("Connected. Logged Out.");
logoutFromFacebook();
Toast.makeText(getApplicationContext(), "LOGGED OUT", Toast.LENGTH_LONG).show();}
}
});
This is the behavior that Facebook wants you to take with their API.Your login method checks to see if you have already signed in once and that the facebook session is active. If the session is active then it sets the properties of the facebook object and connects it behind the sences so that the login page does not show again.
So you're not doing anything wrong, it's suppose to happen this way.

How can i get the user id from the Facebook User?

I want to get the id from the Facebook User but what I've tried so far doesn't work...
public class fbLogin extends Activity {
public static final int LOGIN = Menu.FIRST;
public static final int GET_EVENTS = Menu.FIRST + 1;
public static final int GET_ID = Menu.FIRST + 2;
public static final String APP_ID = "361579407254212";
public static final String TAG = "FACEBOOK CONNECT";
private Facebook mFacebook;
private AsyncFacebookRunner mAsyncRunner;
private Handler mHandler = new Handler();
private static final String[] PERMS = new String[] { "user_events","email" };
private TextView mText;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
// setup the content view
initLayout();
// setup the facebook session
mFacebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(mFacebook);
if (mFacebook.isSessionValid()) {
AsyncFacebookRunner asyncRunner = new AsyncFacebookRunner(mFacebook);
asyncRunner.logout(this, new LogoutRequestListener());
} else {
mFacebook.authorize(this, PERMS, new LoginDialogListener());
}
mAsyncRunner.request("me", new IDRequestListener());
}
protected void initLayout() {
LinearLayout rootView = new LinearLayout(this.getApplicationContext());
rootView.setOrientation(LinearLayout.VERTICAL);
this.mText = new TextView(this.getApplicationContext());
this.mText.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
rootView.addView(this.mText);
this.setContentView(rootView);
}
private class LoginDialogListener implements DialogListener {
public void onComplete(Bundle values) {}
public void onFacebookError(FacebookError e) {}
public void onError(DialogError e) {}
public void onCancel() {}
}
private class LogoutRequestListener implements RequestListener {
public void onComplete(String response, Object state) {
// Dispatch on its own thread
mHandler.post(new Runnable() {
public void run() {
mText.setText("Logged out");
}
});
}
public void onIOException(IOException e, Object state) {}
public void onFileNotFoundException(FileNotFoundException e, Object state) {}
public void onMalformedURLException(MalformedURLException e, Object state) {}
public void onFacebookError(FacebookError e, Object state) {}
}
private class IDRequestListener implements RequestListener {
public void onComplete(String response, Object state) {
try {
// process the response here: executed in background thread
Log.d(TAG, "Response: " + response.toString());
JSONObject json = Util.parseJson(response);
final String id = json.getString("id");
fbLogin.this.runOnUiThread(new Runnable() {
public void run() {
mText.setText("Hello there, " + id + "!");
}
});
} catch (JSONException e) {
Log.w(TAG, "JSON Error in response");
mText.setText("catch1...");
} catch (FacebookError e) {
mText.setText("catch2");
}
}
public void onIOException(IOException e, Object state) {mText.setText("Logging out...1");}
public void onFileNotFoundException(FileNotFoundException e, Object state) {mText.setText("Logging out...2");}
public void onMalformedURLException(MalformedURLException e,Object state) {mText.setText("Logging out...3");}
public void onFacebookError(FacebookError e, Object state) {mText.setText("Logging out...4");}
}
}
It gives a Facebook Error when I go to the OnComplete method from the IDRequestListener class...
How can I fix it? Can anyone help me, please?
You can use socialauth android sdk. Can get user profile, post messages , gets friends list
http://code.google.com/p/socialauth-android/
authorize() is not synchronous and will return immediately. You'll need to wait for the authorization request to complete before submitting requests requiring an access token. Basically, fire the me request only when onComplete() has been called in the authorize() listener.
Also your activity seems to be missing the onActivityResult() implementation that feeds the Facebook object with authorization results, i.e.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mFacebook.authorizeCallback(requestCode, resultCode, data);
}

Android: Uploading photos from SD Card to Facebook Wall

I'm trying to upload pictures from my SD Card to my facebook account and still got no luck.
I'm not getting any errors but the pictures I'm trying to upload are not appearing on my wall.
Here's my code (full code of the Main Class):
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.Facebook.DialogListener;
public class Gallery extends Activity {
private static final String TAG = "Gallery";
// Constants
private static final int UPDATE_GRID_VIEW = 0;
// References to our images
private ArrayList<Uri> picUri = new ArrayList<Uri>();
private ArrayList<String> picName = new ArrayList<String>();
private GridView mGridview;
private ImageAdapter mImageAdapter;
// For FaceBook
private Facebook facebook;
private String fb_AppId = "MY_APP_ID";
// Progress Dialog
private ProgressDialog progressD;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.gallery);
initializeViews();
initFacebook();
authorizeFbUser();
}
public void initializeViews(){
PictureListThread picThread = new PictureListThread();
picThread.start();
mImageAdapter = new ImageAdapter(this);
mGridview = (GridView) findViewById(R.id.gallery_gridview);
mGridview.setAdapter(mImageAdapter);
mGridview.setOnItemClickListener(mOnItemClickListener);
}
// Facebook Methods and Classes
public void initFacebook(){
facebook = new Facebook(fb_AppId);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
public void authorizeFbUser(){
facebook.authorize(this, new String[] { "email", "read_stream" },
new DialogListener() {
#Override
public void onComplete(Bundle values) {
Log.d(TAG, "******************* FACEBOOK::authorize::onComplete *******************");
}
#Override
public void onFacebookError(FacebookError error) {
Log.d(TAG, "******************* FACEBOOK::authorize::onFacebookError *******************");
}
#Override
public void onError(DialogError e) {
Log.d(TAG, "******************* FACEBOOK::authorize::onError *******************");
}
#Override
public void onCancel() {
Log.d(TAG, "******************* FACEBOOK::authorize::onCancel *******************");
}
});
}
public class mRequestListener implements RequestListener{
#Override
public void onMalformedURLException(MalformedURLException e, Object state) {
Log.d(TAG, "******************* FACEBOOK::onMalformedURLException *******************");
}
#Override
public void onIOException(IOException e, Object state) {
Log.d(TAG, "******************* FACEBOOK::onIOException *******************");
}
#Override
public void onFileNotFoundException(FileNotFoundException e, Object state) {
Log.d(TAG, "******************* FACEBOOK::onFileNotFoundException *******************");
}
#Override
public void onFacebookError(FacebookError e, Object state) {
Log.d(TAG, "******************* FACEBOOK::onFacebookError *******************");
}
#Override
public void onComplete(String response, Object state) {
Log.d(TAG, "******************* FACEBOOK::onComplete *******************");
}
}
// Methods
private Handler mHandler = new Handler() {
#Override public void handleMessage(Message msg) {
if(msg.what == UPDATE_GRID_VIEW) {
mImageAdapter.notifyDataSetChanged();
}
}
};
// Inner Classes
private OnItemClickListener mOnItemClickListener = new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Log.d(TAG,"[][][][][][][][][][]-------------> PATH: "+picUri.get(position).toString());
byte[] data = null;
Bitmap bi = BitmapFactory.decodeFile(picUri.get(position).toString());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bi.compress(Bitmap.CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
Log.d(TAG,"[][][][][][][][][][]-------------> DATA: "+data);
Bundle param = new Bundle();
param.putString("method", "photos.upload");
param.putString("message", picName.get(position));
param.putByteArray("picture", data);
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request("me/photos", param, "POST", new mRequestListener(), null);
Log.d(TAG,"[][][][][][][][][][]-------------> Gallery::mOnItemClickListener END!");
}
};
private class PictureListThread extends Thread {
#Override
public void run() {
Log.d(TAG, "******************* PictureListThread::run() STARTED! *******************");;
System.gc();
String[] proj = { MediaStore.Images.Media.DATA, MediaStore.Images.Media.TITLE};
Cursor picturecursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
proj, null, null, MediaStore.Images.Media.TITLE);
if (picturecursor == null)
return;
if (!picturecursor.moveToFirst())
return;
do {
String picTitle = picturecursor.getString(picturecursor.getColumnIndex(MediaStore.Images.Media.TITLE));
if(picTitle.contains("KEYWORD")){
picName.add(picTitle);
picUri.add(Uri.parse(picturecursor.getString(picturecursor.getColumnIndex(MediaStore.Images.Media.DATA))));
Log.d(TAG,"[][][][][][][][][][]-------------> PICTURE ADDED: "+picTitle);
mHandler.sendEmptyMessage(UPDATE_GRID_VIEW);
}
} while (picturecursor.moveToNext());
}
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return picUri.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(150, 100));
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageURI(picUri.get(position));
return imageView;
}
}
}
My
mRequestListener()::onComplete()
is being called with no errors and so I'm wondering why the pictures are not displaying on my wall.
Am I missing something here?
Please help.
Thanks in advance!
put this line.
mAsyncRunner.request("me/photos", param, "POST", new mRequestListener(), null);
instead of
mAsyncRunner.request(null, param, "POST", new mRequestListener(), null);
and check photo will appear on wall or not?
add "publish_stream" in permission..
If I am not mistaken, your Bundle param is missing "method" property. Try adding:
param.putString("method", "photos.upload");

Categories

Resources