NullPointer exception in facebook logout - android

Can some one please help me to solve nullpointer exception in my following code in
I've got the following FoodStarLoginActivity. The following line is throwing a NullPointer but I don't understand why :facebook.logout(FoodStarLoginActivity.this); could anyone help me out? I even tried getApplicationcontext() instead of my FoodStarLoginActivity but it didn't work.
I am getting following exception :
java.lang.NullPointerException
at android.context.ContextWrapper.getApplicationContext(ContextWrapper.java:100)
at android.webkit.CookieSyncManager.createInstance(CookiesSyncManager.java:96)
at com.facebook.android.Util.clearCookies(Util.java:241)
at com.facebook.android.Facebook.logout(Facebook.java:617)
at ten.mob.socialapp.FoodStarLoginActivity.logout(FoodStarLoginActivity.java:131)
package ten.mob.socialapp;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import ten.mob.socialapp.FacebookConnector;
import ten.mob.socialapp.SessionEvents;
import ten.mob.socialapp.FacebookConnector.LogoutRequestListener;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
public class FoodStarLoginActivity extends Activity{
private static final String faceBookAppId = "*******************";
private static final String faceBookPermission = "publish_stream";
static Facebook facebook = new Facebook(faceBookAppId);
private SharedPreferences mPrefs;
FacebookConnector facebookConnector ;
AsyncFacebookRunner asyncRunner;
private Handler mHandler = new Handler();
Context context;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
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 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(){}
});
}
if(facebook.isSessionValid()){
Intent intent = new Intent(this,SearchMyActivity.class);
startActivity(intent);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
public void logout(){
try {
facebook.logout(FoodStarLoginActivity.this);
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
asyncRunner = new AsyncFacebookRunner(facebook);
System.out.println(asyncRunner);
asyncRunner.logout(FoodStarLoginActivity.this, new LogoutRequestListener() {
public void onComplete(String response, Object state) {}
public void onFileNotFoundException(FileNotFoundException e,Object state) {}
public void onFacebookError(FacebookError e, Object state) {}
});
System.out.println(asyncRunner);
System.out.println(facebook.isSessionValid());
}
private class LogoutRequestListener implements RequestListener {
public void onComplete(String response, Object state) {
mHandler.post(new Runnable() {
public void run() {
SessionEvents.onLogoutFinish();
}
});
}
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) {}
}
}
public class SearchMyActivity(){
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.menu_create:
Intent intent = new Intent(this, CreateRestaurantActivity.class);
startActivity(intent);
break;
case R.id.menu_foodstars:
intent = new Intent(this, RestaurantList.class);
startActivity(intent);
break;
case R.id.menu_logout:
FoodStarLoginActivity logoutFoodStar = new FoodStarLoginActivity();
logoutFoodStar.logout();
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
}

Related

get profile information from facebook in android app

I am trying to integrate facebook sdk with my android application and want to retrieve username,email and profile pic of the person logged in but I am getting a System error. My code is as follow-
package com.example.facebooklogin;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import org.json.JSONException;
import org.json.JSONObject;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import android.net.ParseException;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener
{
// Your Facebook APP ID
private static String APP_ID = "801614236517742"; // Replace your App ID here
//private static String APP_ID = "308180782571605"; // Replace your App ID here
// Instance of Facebook Class
private Facebook facebook;
#SuppressWarnings("deprecation")
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
Button btn;
String name;
String email;
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
facebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(facebook);
btn=(Button)findViewById(R.id.btnFbLogin);
btn.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
loginToFacebook();
//getProfileInformation();
}
#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)
{
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();
}
#Override
public void onError(DialogError error)
{
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror)
{
// Function to handle Facebook errors
}
});
}
else
getProfileInformation();
}
#SuppressWarnings("deprecation")
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
name = profile.getString("name");
// getting email of the user
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 onFacebookError(FacebookError e, Object state) {
}
#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
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
}
Logcat of my app-
05-22 06:55:53.774: W/dalvikvm(3713): VFY: unable to find class referenced in signature (Landroid/support/v4/app/Fragment;)
05-22 06:55:53.774: W/dalvikvm(3713): VFY: unable to find class referenced in signature (Landroid/support/v4/app/Fragment;)
05-22 06:55:53.784: I/dalvikvm(3713): Could not find method android.support.v4.content.LocalBroadcastManager.getInstance, referenced from method com.facebook.Session.postActiveSessionAction
05-22 06:55:53.784: W/dalvikvm(3713): VFY: unable to resolve static method 216: Landroid/support/v4/content/LocalBroadcastManager;.getInstance (Landroid/content/Context;)Landroid/support/v4/content/LocalBroadcastManager;
05-22 06:55:53.784: D/dalvikvm(3713): VFY: replacing opcode 0x71 at 0x0009
05-22 06:55:54.514: D/dalvikvm(3713): GC_FOR_ALLOC freed 224K, 9% free 3058K/3360K, paused 54ms, total 57ms
05-22 06:55:54.604: D/Facebook-Util(3713): GET URL: https://graph.facebook.com/me?access_token=CAAEhug8jDagBAP7mXTSAg9pqFittCCALpgdciZCzhWya9pqRH0sB5puv36fD5bta2dNGTKHctWvaoaIBbCIDKLZACX3fNVFAv75u0YOULJZC7MLEZBiEpSOmUADEmB51gllXRTEAi5ZCLAfJGXuKOJIl9ZBJLqiWZAK51nHs5prITm5HrFOUr64D6f2M26ZAxZAk0Y2l5AZATZCznmzCGSDksXQ&format=json
05-22 06:55:57.034: D/Profile(3713): {"error":{"message":"Error validating application. Application has been deleted.","type":"OAuthException","code":190}}
05-22 06:55:57.044: W/System.err(3713): org.json.JSONException: No value for name
05-22 06:55:57.044: W/System.err(3713): at org.json.JSONObject.get(JSONObject.java:355)
05-22 06:55:57.044: W/System.err(3713): at org.json.JSONObject.getString(JSONObject.java:515)
05-22 06:55:57.044: W/System.err(3713): at com.example.facebooklogin.MainActivity$2.onComplete(MainActivity.java:145)
05-22 06:55:57.084: W/System.err(3713): at com.facebook.android.AsyncFacebookRunner$2.run(AsyncFacebookRunner.java:276)

facebook login android app crashes

The code is posted here and the app crashes when the login button is clicked with null pointer exception at homefragment on click.im a beginer.please help.logcat http://postimg.org/image/6d1qyszkd/
simple facebook class basically is :
public SimpleFacebook()
{
mSessionStatusCallback = new SessionStatusCallback();
}
public static void initialize(Activity activity)
{
if (mInstance == null)
{
mInstance = new SimpleFacebook();
}
mActivity = activity;
}
public static SimpleFacebook getInstance(Activity activity)
{
if (mInstance == null)
{
mInstance = new SimpleFacebook();
}
mActivity = activity;
return mInstance;
}
public static SimpleFacebook getInstance()
{
return mInstance;
}
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.parse.GetDataCallback;
import com.sromku.simple.fb.SimpleFacebook;
import com.sromku.simple.fb.Properties;
import com.sromku.simple.fb.SimpleFacebook;
import com.sromku.simple.fb.SimpleFacebook.OnFriendsRequestListener;
import com.sromku.simple.fb.SimpleFacebook.OnLoginListener;
import com.sromku.simple.fb.SimpleFacebook.OnLogoutListener;
import com.sromku.simple.fb.SimpleFacebook.OnProfileRequestListener;
import com.sromku.simple.fb.entities.Profile;
import com.sromku.simple.fb.example.utils.Utils;
import com.sromku.simple.fb.utils.Attributes;
import com.sromku.simple.fb.utils.PictureAttributes;
import com.sromku.simple.fb.utils.PictureAttributes.PictureType;
public class HomeFragment extends Fragment {
protected static final String TAG = HomeFragment.class.getName();
private SimpleFacebook mSimpleFacebook;
ProgressDialog mProgress;
Button mButtonLogin;
Button mButtonLogout;
TextView mTextStatus;
// Login listener
private OnLoginListener mOnLoginListener = new OnLoginListener()
{
#Override
public void onFail(String reason)
{
mTextStatus.setText(reason);
Log.w(TAG, "Failed to login");
}
#Override
public void onException(Throwable throwable)
{
mTextStatus.setText("Exception: " + throwable.getMessage());
Log.e(TAG, "Bad thing happened", throwable);
}
#Override
public void onThinking()
{
// show progress bar or something to the user while login is happening
mTextStatus.setText("Thinking...");
}
#Override
public void onLogin()
{
// change the state of the button or do whatever you want
mTextStatus.setText("Logged in");
loggedInUIState();
toast("You are logged in");
}
#Override
public void onNotAcceptingPermissions()
{
toast("You didn't accept read permissions");
}
};
// Logout listener
private OnLogoutListener mOnLogoutListener = new OnLogoutListener()
{
#Override
public void onFail(String reason)
{
mTextStatus.setText(reason);
Log.w(TAG, "Failed to login");
}
#Override
public void onException(Throwable throwable)
{
mTextStatus.setText("Exception: " + throwable.getMessage());
Log.e(TAG, "Bad thing happened", throwable);
}
#Override
public void onThinking()
{
// show progress bar or something to the user while login is happening
mTextStatus.setText("Thinking...");
}
#Override
public void onLogout()
{
// change the state of the button or do whatever you want
mTextStatus.setText("Logged out");
loggedOutUIState();
toast("You are logged out");
}
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.homend_home_fragment, container, false);
// test local language
Utils.updateLanguage(getActivity(), "en");
Utils.printHashKey(getActivity());
mButtonLogin = (Button)rootView.findViewById(R.id.button_login);
mButtonLogout = (Button)rootView.findViewById(R.id.button_logout);
mTextStatus = (TextView)rootView.findViewById(R.id.text_status);
mButtonLogin.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0)
{
mSimpleFacebook.login(mOnLoginListener);
}
});
// 2. Logout example
mButtonLogout.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0)
{
mSimpleFacebook.logout(mOnLogoutListener);
}
});
return rootView;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
mSimpleFacebook.onActivityResult(getActivity(), requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);
}
private void setUIState()
{
if (mSimpleFacebook.isLogin())
{
loggedInUIState();
}
else
{
loggedOutUIState();
}
}
/**
* Show toast
*
* #param message
*/
private void toast(String message)
{
Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
}
private void loggedInUIState()
{
mButtonLogin.setEnabled(false);
mButtonLogout.setEnabled(true);
mTextStatus.setText("Logged in");
}
private void loggedOutUIState()
{
mButtonLogin.setEnabled(true);
mButtonLogout.setEnabled(false);
mTextStatus.setText("Logged out");
}
private void showDialog()
{
mProgress = ProgressDialog.show(getActivity(), "Thinking",
"Waiting for Facebook", true);
}
private void hideDialog()
{
mProgress.hide();
}
public class OnProfileRequestAdapter implements OnProfileRequestListener
{
#Override
public void onThinking()
{
}
#Override
public void onException(Throwable throwable)
{
}
#Override
public void onFail(String reason)
{
}
#Override
public void onComplete(Profile profile)
{
}
}
}
I think problem might be here. You have just declared your variable
private SimpleFacebook mSimpleFacebook;
you haven't initialized that variable so you got NPE
So initialized it on onCreateView() method.
mSimpleFacebook = SimpleFacebook.getInstance(getActivity());
And yet you get error then you need to finally change
mSimpleFacebook = SimpleFacebook.getInstance();
Add this line to manifest file..
<activity android:name="com.facebook.LoginActivity" android:screenOrientation="portrait" android:configChanges="keyboardHidden|orientation">
</activity>
which would be finally works for you.!!

how to show profile pictures of friends in a list view?

i want to add profile pictures of friends in a list view along with their names. i am using the code which gives me friends name in list view. but i don't know how to show their profile pictures.i have used a login button and on its click event friends list will open. can anybody please tell.? here is the code that i have used
public class LoginActivity extends Activity{
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;
public byte[] picture;
public Bitmap pictureBitmap;
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() {
mAsyncRunner.request("me/friends", new FriendsRequestListener());
}
});
}
private void saveCredentials(Facebook facebook) {
}
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) {
}
public class getAlbumsData {
public void execute() {
} }
private class FriendsRequestListener implements RequestListener {
String friendData;
//Method runs when request is complete
public void onComplete(String response, Object state) {
Log.v("", "FriendListRequestONComplete");
friendData = response;
Log.v("friendData--", ""+friendData);
LoginActivity.this.runOnUiThread(new Runnable() {
public void run() {
try {
//Parse JSON Data
JSONObject json;
json = Util.parseJson(friendData);
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"));
}
Intent ide = new Intent(LoginActivity.this,FrndActivity.class);
ide.putStringArrayListExtra("friends", friends);
startActivity(ide);
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FacebookError e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
}
You have to show your friend's profile picture with URL only.
You have to use only URL for showing your frnds profile picture.(This facility is given by Facebook)
you can show your friend's profile picture with Lazy Loading ..
Code::::
package com.facebook.me;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.FacebookError;
import com.facebook.lazylist.Friend_List_Lazy_Loading;
public class Friend_list extends Activity
{
public static final String DATA = "data";
public static final String NAME = "name";
public static final String FB_ID = "id";
public static final String PICTURE = "picture";
public static final String URL = "url";
Friend_List_Bean friendBean;
ArrayList<Friend_List_Bean> aryFriendList;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.friend_list);
aryFriendList = new ArrayList<Friend_List_Bean>();
getFriendList();
}
private void getFriendList()
{
Bundle param = new Bundle();
param.putString("fields", "name, picture");
AsyncFacebookRunner async = new AsyncFacebookRunner(MainActivity.facebook);
async.request("me/friends", param, new RequestListener()
{
#Override
public void onMalformedURLException(MalformedURLException e, Object state) {
}
#Override
public void onIOException(IOException e, Object state) {
}
#Override
public void onFileNotFoundException(FileNotFoundException e, Object state) {
}
#Override
public void onFacebookError(FacebookError e, Object state) {
}
#Override
public void onComplete(String response, Object state)
{
Log.d("response : ", ""+response);
parseContact(response);
}
},null);
}
public void parseContact(String response)
{
try
{
JSONObject objResponse = new JSONObject(response);
JSONArray contact = objResponse.getJSONArray(DATA);
Log.d("Total Friends", " : "+contact.length());
for(int i=0;i<contact.length();i++)
{
friendBean = new Friend_List_Bean();
JSONObject objData = contact.getJSONObject(i);
Log.d("", ""+objData.getString(FB_ID));
Log.d("", ""+objData.getString(NAME));
Log.d("", ""+objData.getString(PICTURE));
JSONObject objJsonPicture = objData.getJSONObject(PICTURE);
JSONObject objJsonPictureData = objJsonPicture.getJSONObject(DATA);
Log.d("", ""+objJsonPictureData.getString(URL));
friendBean.setFbId(objData.getString(FB_ID));
friendBean.setName(objData.getString(NAME));
friendBean.setPictureUrl(objJsonPictureData.getString(URL));
aryFriendList.add(friendBean);
}
Intent i = new Intent(Friend_list.this, Friend_List_Lazy_Loading.class);
i.putExtra("aryFriendList", aryFriendList);
startActivity(i);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
BEAN:::::
package com.facebook.me;
import java.io.Serializable;
public class Friend_List_Bean implements Serializable
{
public String fbId;
public String name;
public String pictureUrl;
public String getFbId()
{
return fbId;
}
public void setFbId(String fbId)
{
this.fbId = fbId;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getPictureUrl()
{
return pictureUrl;
}
public void setPictureUrl(String pictureUrl)
{
this.pictureUrl = pictureUrl;
}
}
Friend_List_Lazy_Loading.class:::
package com.facebook.lazylist;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.Toast;
import com.facebook.me.Friend_List_Bean;
import com.facebook.me.Post_on_Friend;
import com.facebook.me.R;
public class Friend_List_Lazy_Loading extends Activity implements OnItemClickListener {
ListView list;
GridView gv;
LazyAdapter adapter;
GridViewLazyAdapter gridViewLazyAdapter;
ArrayList<Friend_List_Bean> aryFriendList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// aryFriendList = new ArrayList<Friend_List_Bean>();
list=(ListView)findViewById(R.id.list);
Intent intent=getIntent();
aryFriendList=(ArrayList<Friend_List_Bean>)intent.getSerializableExtra("aryFriendList");
adapter=new LazyAdapter(this, aryFriendList);
gridViewLazyAdapter=new GridViewLazyAdapter(this, aryFriendList);
list.setAdapter(adapter);
list.setOnItemClickListener(this);
gv = (GridView) findViewById(R.id.grid_id);
gv.setAdapter(gridViewLazyAdapter);
gv.setOnItemClickListener(this);
Button b=(Button)findViewById(R.id.button1);
b.setOnClickListener(listener);
Button btnViewGalary=(Button)findViewById(R.id.btnViewGalary);
btnViewGalary.setOnClickListener(listenerBtnViewGalary);
Button btnThumbnail=(Button)findViewById(R.id.btnThumbnail);
btnThumbnail.setOnClickListener(listenerBtnThumbnail);
list.setVisibility(View.VISIBLE);
}
#Override
public void onDestroy()
{
list.setAdapter(null);
super.onDestroy();
}
public OnClickListener listener=new OnClickListener(){
#Override
public void onClick(View arg0)
{
adapter.imageLoader.clearCache();
adapter.notifyDataSetChanged();
}
};
public OnClickListener listenerBtnViewGalary=new OnClickListener(){
#Override
public void onClick(View arg0)
{
list.setVisibility(View.GONE);
gv.setVisibility(View.VISIBLE);
}
};
public OnClickListener listenerBtnThumbnail=new OnClickListener(){
#Override
public void onClick(View arg0)
{
gv.setVisibility(View.GONE);
list.setVisibility(View.VISIBLE);
}
};
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
if(arg1 == list)
{
Toast.makeText(this, aryFriendList.get(arg2).getFbId(), Toast.LENGTH_SHORT).show();
Intent i = new Intent(Friend_List_Lazy_Loading.this, Post_on_Friend.class);
i.putExtra("id", ""+aryFriendList.get(arg2).getFbId());
startActivity(i);
}
else
{
Toast.makeText(this, ""+aryFriendList.get(arg2).getFbId(), Toast.LENGTH_SHORT).show();
Intent i = new Intent(Friend_List_Lazy_Loading.this, Post_on_Friend.class);
i.putExtra("id", aryFriendList.get(arg2).getFbId());
startActivity(i);
}
}
}

Android Facebook integration does not log out

I am developing a Facebook Android integration using the below code, but once I log-in through this app then it does not logout from facebook even if I logout from Facebook app or browser both from my device. So this android app can still post on my Facebook wall. How do I logout from this app if I logout from my facebook app or facebook on browser.
package com.facebook.androidhive;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
public class AndroidFacebookConnectActivity extends Activity {
// Your Facebook APP ID
private static String APP_ID = "APP_ID"; // Replace with your App ID
// 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.main);
mAsyncRunner = new AsyncFacebookRunner(facebook);
loginToFacebook();
postToWall();
}
/**
* Function to login into facebook
* */
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
}
#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
}
});
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
/**
* Function to post to facebook wall
* */
public void postToWall() {
// post on user's wall.
facebook.dialog(this, "feed", new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onComplete(Bundle values) {
}
#Override
public void onCancel() {
}
});
}
/**
* Function to Logout user 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) {
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
}
}
#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) {
}
});
}
}
You can't force a logout from your app if you logout of the Facebook app, at least no API that we support with our SDK.
In theory, you could find a way to attach some sort of uninstall intent or to parse logs for any messages regarding facebook logout, but it generally is not recommended as best practice to force a logout of another app when another app logs out (its not intuitive to the user that this is going to happen).
try remove this code
if (access_token != null) {
facebook.setAccessToken(access_token);
Log.d("FB Sessions", "" + facebook.isSessionValid());
}

Facebook SSO not working in android

I used the following code to Login through Facebook in my app. I need to do this with Facebook SSO. I have the correct app_id.
package com.fb.sso;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
public class FBSSOActivity extends Activity {
/** Called when the activity is first created. */
public static final String APP_ID = "my_app_id";
private static final String[] PERMISSIONS = new String[] {
"publish_stream", "read_stream", "offline_access" };
private TextView mText;
private Handler mHandler = new Handler();
private Facebook mFacebook;
private AsyncFacebookRunner mAsyncRunner;
byte[] raw;
private SharedPreferences mPrefs;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (APP_ID == null) {
Util.showAlert(this, "Warning",
"Facebook Applicaton ID must be set...");
}
// Initialize the content view
setContentView(R.layout.main);
// Initialize the Facebook session
mFacebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(mFacebook);
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
mFacebook.setAccessToken(access_token);
}
if (expires != 0) {
mFacebook.setAccessExpires(expires);
}
}
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);
}
private class LogoutRequestListener implements RequestListener {
#Override
public void onComplete(String response, Object state) {
// TODO Auto-generated method stub
Log.v("comes here>>.","sucess");
// Only the original owner thread can touch its views
FBSSOActivity.this.runOnUiThread(new Runnable() {
public void run() {
mText.setText("Thanks for using FB Sample App. Bye bye...");
}
});
// Dispatch on its own thread
mHandler.post(new Runnable() {
public void run() {
}
});
}
#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
Log.v("facebook error","fb error");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem loginItem = menu.findItem(R.id.login);
if (mFacebook.isSessionValid()) {
loginItem.setTitle("Logout");
} else {
loginItem.setTitle("Login");
}
loginItem.setEnabled(true);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Login/logout toggle
case R.id.login:
if (!mFacebook.isSessionValid()) {
mFacebook.authorize(this, new DialogListener() {
#Override
public void onComplete(Bundle values) {
// TODO Auto-generated method stub
Log.v("Entered ", "No ERRRRRRRRRRRR");
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
mFacebook.getAccessToken());
editor.putLong("access_expires",
mFacebook.getAccessExpires());
editor.commit();
Intent i=new Intent(FBSSOActivity.this,second.class);
startActivity(i);
}
#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 onCancel() {
// TODO Auto-generated method stub
}
});
}else{
mFacebook.setAccessToken(null);
mFacebook.setAccessExpires(0);
AsyncFacebookRunner asyncRunner = new AsyncFacebookRunner(mFacebook);
asyncRunner.logout(this.getBaseContext(), new LogoutRequestListener());
}
break;
default:
return false;
}
return true;
}
}
I logged in to preinstalled Facebook app in my device. And I got this screen only.
And in my Logcat this line appears.
09-28 15:18:24.652: E/ActivityThread(1201): Failed to find provider info for com.facebook.katana.provider.AttributionIdProvider
If I logged out from my preinstalled Facebook app, my application prompts me to login, asking the credentials. That time also, the empty screen appears.But in the preinstalled Facebook app, I can see my updates.( I get Logged in).
Update:
Right now I'm checking the app only. I have not published it to market. I got the key by referring this site http://sean.lyn.ch/2011/07/android-the-facebook-sdk-sso-and-you/. And I added it to the app, like this.
Update 2:
Now I got these lines in logcat:
09-29 12:00:12.552: I/ActivityManager(73): Starting activity: Intent { cmp=com.facebook.katana/.ProxyAuth (has extras) }
09-29 12:00:13.022: I/ActivityManager(73): Displayed activity com.facebook.katana/.ProxyAuth: 436 ms (total 436 ms)
09-29 12:00:15.032: W/InputManagerService(73): Starting input on non-focused client com.android.internal.view.IInputMethodClient$Stub$Proxy#434b2e88 (uid=10031 pid=2233)
09-29 12:00:15.032: W/IInputConnectionWrapper(2233): showStatusIcon on inactive InputConnection

Categories

Resources