Facebook SSO not working in android - 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

Related

ClassCastException while integrating google plus api inside a fragment

I followed all steps mentioned in developer.google.com to implement the googleplus api in my application.
I'm integrating the googleplus api in the fragment and i'm getting an ClassCastException when i run the code.
My Fragment Class:
import com.digiapes.apeonomy.animation.Positions;
import com.example.apeonomy.R;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.plus.Plus;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
public class Login extends Fragment implements OnGlobalLayoutListener,
OnClickListener, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
EditText UN, Pass;
View loginimage, loginusing, loginlayout;
ImageButton flogin, Glogin;
Button login1;
float f;
Positions pos = new Positions();
String name = "Harsha";
String pass = "hahaha";
private static final int RC_SIGNIN = 0;
private static boolean mSignInClicked;
private GoogleApiClient mGoogleApiClient;
private boolean mIntentInProgress;
private boolean mSignedIn;
private ConnectionResult mConnectionResult;
private Activity c;
private boolean mSignedInClicked;
// Login_Register Lg=new Login_Register();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View login = inflater.inflate(R.layout.login, container, false);
// TODO Auto-generated method stub
UN = (EditText) login.findViewById(R.id.UsernameL);
Pass = (EditText) login.findViewById(R.id.PassswordL);
loginimage = login.findViewById(R.id.LoginImage);
login1 = (Button) login.findViewById(R.id.Login);
loginusing = login.findViewById(R.id.loginusing);
loginlayout = login.findViewById(R.id.LoginLayout);
f = ((Login_Register) getActivity()).pos.getLIpos();
loginimage.getViewTreeObserver().addOnGlobalLayoutListener(this);
UN.getBackground().setAlpha(50);
Pass.getBackground().setAlpha(50);
ObjectAnimator.ofFloat(loginusing, View.ALPHA, 0, 1).setDuration(1000)
.start();
ObjectAnimator.ofFloat(loginlayout, View.ALPHA, 0, 1).setDuration(1000)
.start();
login.findViewById(R.id.googlepluslog).setOnClickListener(this);
login.findViewById(R.id.facebooklog).setOnClickListener(this);
return login;
}
#Override
public void onGlobalLayout() {
pos.setLIpos(loginimage.getY());
// TODO Auto-generated method stub
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
ObjectAnimator
.ofFloat(loginimage, View.TRANSLATION_Y,
f - loginimage.getY() - 130, 0).setDuration(300)
.start();
login1.setOnClickListener(this);
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks((ConnectionCallbacks) getActivity().getApplicationContext())
.addOnConnectionFailedListener(this).addApi(Plus.API, null)
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.Login:
if (UN.getText().length() == 0 || Pass.getText().length() == 0) {
Toast.makeText(getActivity(),
"Please enter valid Username and Password",
Toast.LENGTH_SHORT).show();
} else if (UN.getText().toString().equals(name)
&& Pass.getText().toString().equals(pass)) {
Intent intent = new Intent(getActivity()
.getApplicationContext(), Main.class);
startActivity(intent);
}
break;
case R.id.facebooklog:
break;
case R.id.googlepluslog:
signInWithGplus();
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (requestCode == RC_SIGNIN) {
mIntentInProgress = false;
if (!mGoogleApiClient.isConnecting()) {
mGoogleApiClient.connect();
}
}
}
private void signInWithGplus() {
// TODO Auto-generated method stub
if (!mGoogleApiClient.isConnecting()) {
mSignedIn = true;
resolveSignInerror();
}
}
private void resolveSignInerror() {
// TODO Auto-generated method stub
if (mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
mConnectionResult.startResolutionForResult(c, RC_SIGNIN);
} catch (SendIntentException e) {
mIntentInProgress = false;
mGoogleApiClient.connect();
}
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// TODO Auto-generated method stub
if (!result.hasResolution()) {
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), c, 0)
.show();
return;
}
if(!mIntentInProgress){
mConnectionResult=result;
if(mSignedInClicked)
resolveSignInerror();
}
}
#Override
public void onConnected(Bundle arg0) {
mSignedInClicked=false;
Toast.makeText(c, "Connected", Toast.LENGTH_SHORT).show();
// TODO Auto-generated method stub
}
#Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
mGoogleApiClient.connect();
}
#Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
mGoogleApiClient.connect();
}
#Override
public void onStop() {
// TODO Auto-generated method stub
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
}
Getting error at this line:
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks((ConnectionCallbacks) getActivity().getApplicationContext())
.addOnConnectionFailedListener(this).addApi(Plus.API, null)
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
Logcat:
Solution given in Error implementing GoogleApiClient Builder for Android development didn't workout for me...
.addConnectionCallbacks((ConnectionCallbacks) getActivity().getApplicationContext())
That's wrong, the method accepts a class that implements GoogleApiClient.ConnectionCallbacks, use your Fragment instead of getActivity().getApplicationContext().

Android - App crashing without any definite interval of time

I am using Facebook SDK in my app but my app crashes after i click on the login button.
But the time is not fixed.
Sometimes it crashes after i have logged in, sometimes at the instant i click on login button, sometimes in between when i am filling out the details for login.
Also can anybody tell me why the shared preferences are not working.
MainActivity.this
import com.facebook.android.FacebookError;
import com.facebook.android.Facebook.DialogListener;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
Facebook fb;
ImageView login;
SharedPreferences sp;
String APP_ID = "123456";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fb = new Facebook(APP_ID);
sp = getPreferences(MODE_PRIVATE);
String access_token = sp.getString("access_token", null);
long expires = sp.getLong("expires", 0);
if (access_token != null) {
fb.setAccessToken(access_token);
}
if (expires != 0) {
fb.setAccessExpires(expires);
}
login = (ImageView) findViewById(R.id.imageView1);
login.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.imageView1) {
fbLogin();
}
}
private void fbLogin() {
if (fb.isSessionValid()) {
Intent i = new Intent(MainActivity.this, com.example.test.Register.class);
startActivity(i);
} else {
fb.authorize(MainActivity.this, new String[] { "email" },
new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
e.printStackTrace();
Toast.makeText(MainActivity.this, "fbError",Toast.LENGTH_SHORT).show();
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
e.printStackTrace();
Toast.makeText(MainActivity.this, "onError",Toast.LENGTH_SHORT).show();
}
#Override
public void onComplete(Bundle values) {
// TODO Auto-generated method stub
Editor editor = sp.edit();
editor.putString("access_token",fb.getAccessToken());
editor.putLong("access_expires",fb.getAccessExpires());
editor.commit();
Intent i = new Intent(MainActivity.this, com.example.test.Register.class);
startActivityForResult(i, RESULT_OK);
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "onCancel",Toast.LENGTH_SHORT).show();
}
});
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
fb.authorizeCallback(requestCode, resultCode, data);
}
}
So please can anybody help me to identify :
Why the app is crashing at any time after i click on the the login button.
Why the shared preferences is not working.
Logcat
03-31 00:31:47.459: E/AndroidRuntime(5121): FATAL EXCEPTION: Timer-0
03-31 00:31:47.459: E/AndroidRuntime(5121): java.lang.NoClassDefFoundError: android.support.v4.content.LocalBroadcastManager
03-31 00:31:47.459: E/AndroidRuntime(5121): at com.facebook.AppEventsLogger.flushAndWait(AppEventsLogger.java:760)
03-31 00:31:47.459: E/AndroidRuntime(5121): at com.facebook.AppEventsLogger.access$1(AppEventsLogger.java:732)
03-31 00:31:47.459: E/AndroidRuntime(5121): at com.facebook.AppEventsLogger$2.run(AppEventsLogger.java:605)
03-31 00:31:47.459: E/AndroidRuntime(5121): at java.util.Timer$TimerImpl.run(Timer.java:284)
03-31 00:31:47.589: D/OpenGLRenderer(5121): Flushing caches (mode 0)
03-31 00:31:50.319: I/Process(5121): Sending signal. PID: 5121 SIG: 9
About the problem with your shared preferences:
It looks like you look up the wrong key here:
long expires = sp.getLong("expires", 0);
you should change it to:
long expires = sp.getLong("access_expires", 0);
because later you do actually save this in the shared preferences:
editor.putLong("access_expires",fb.getAccessExpires());
editor.commit();
Note: The other problem with the NoClassDefFoundError was solved with this related answer

How to Get friend list from Facebook SDK 3.0 in my Activity

I am new in Facebook integration with android. I've logged in to Facebook in my android application.
So I am creating an app which needs to get the Facebook friends list (the names and the pictures). I Googled but not getting. How can I get the list of friends?
XML file, when button is clicked i want my all list of Facebook friends
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="#+id/login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/login_button"/>
<ImageView
android:id="#+id/picturepic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible"/>
<Button
android:id="#+id/btn_get_friend_list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Friends"
android:layout_marginTop="30dip"
android:layout_gravity="center_horizontal"
android:visibility="gone"/>
<Button
android:id="#+id/btn_show_access_tokens"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Access Tokens"
android:layout_marginTop="30dip"
android:layout_gravity="center_horizontal"
android:visibility="gone"/>
package com.example.simplelogin1;
import java.io.IOException;
import java.net.MalformedURLException;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.Facebook.DialogListener;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener
{
ImageView pic,button;
Facebook fb;
Button btnShowAccessTokens,btnGetFriendList;
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String APP_ID="";
fb=new Facebook(APP_ID);
btnGetFriendList=(Button) findViewById(R.id.btn_get_friend_list);
btnShowAccessTokens = (Button) findViewById(R.id.btn_show_access_tokens);
button=(ImageView) findViewById(R.id.login);
pic=(ImageView) findViewById(R.id.picturepic);
mAsyncRunner = new AsyncFacebookRunner(fb);
button.setOnClickListener(this);
btnGetFriendList.setOnClickListener(this);
btnShowAccessTokens.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
showAccessTokens();
}
});
updateButtonImage();
}
private void updateButtonImage()
{
// TODO Auto-generated method stub
if(fb.isSessionValid())
{
button.setImageResource(R.drawable.logout_button);
}
else
{
button.setImageResource(R.drawable.login_button);
}
}
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
if(fb.isSessionValid())
{
try
{
fb.logout(getApplicationContext());
updateButtonImage();
btnShowAccessTokens.setVisibility(View.INVISIBLE);
btnGetFriendList.setVisibility(View.INVISIBLE);
}
catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
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);
// Making show access tokens button visible
btnShowAccessTokens.setVisibility(View.VISIBLE);
btnGetFriendList.setVisibility(View.VISIBLE);
Log.d("FB Sessions", "" + fb.isSessionValid());
}
if (expires != 0)
{
fb.setAccessExpires(expires);
}
{
fb.authorize(this,new String[] {"email","publish_stream"} , new DialogListener()
{
#Override
public void onFacebookError(FacebookError e)
{
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "fbError", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(DialogError e)
{
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "onError", Toast.LENGTH_SHORT).show();
}
#Override
public void onComplete(Bundle values)
{
// TODO Auto-generated method stub
updateButtonImage();
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",fb.getAccessToken());
editor.putLong("access_expires",fb.getAccessExpires());
editor.commit();
btnShowAccessTokens.setVisibility(View.VISIBLE);
btnGetFriendList.setVisibility(View.VISIBLE);
}
#Override
public void onCancel()
{
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "onCancel", Toast.LENGTH_SHORT).show();
}
});
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
fb.authorizeCallback(requestCode, resultCode, data);
}
public void showAccessTokens()
{
String access_token = fb.getAccessToken();
Toast.makeText(getApplicationContext(),"Access Token: " + access_token, Toast.LENGTH_LONG).show();
}
}
My main activity ,,where should i implement getting a friends from Facebook when i clicked button.
after success full login
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(mFacebook);
String query="SELECT uid, name, pic_square FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me())";
Bundle bundal=new Bundle();
bundal.putString("method", "fql.query");
bundal.putString("query", query);
return bundal;
mAsyncRunner.request(bundal, new RequestListener() {
#Override
public void onComplete(final String response, Object state) {
// TODO Auto-generated method stub
//parse json and get all friends
}
});

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());
}

Implementing Leadbolt in Android app

I am making my first Android app and I am trying to implement Leadbolt unlocker, I have done everything like Leadbolt documentation, but when I launch app it is always crashing. When I remove implement AdListener from public class FullActivity extends Activity implements AdListener then everything is working. App is crashing when Intent full = new Intent(GridActivity.this, FullActivity.class); and it is not even go to super.onCreate(savedInstanceState); breakpoint.
This is FullActivity.java:
import java.io.IOException;
import android.app.Activity;
import android.app.WallpaperManager;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import com.Leadbolt.AdController;
import com.Leadbolt.AdListener;
public class FullActivity extends Activity implements AdListener{
private AdController myController;
private String MY_LB_SECTION_ID="1111111";
private Integer[] mThumbIds = {
R.drawable.p1,
R.drawable.p2,
R.drawable.p3,
R.drawable.p4,
R.drawable.p5,
R.drawable.p6,
R.drawable.p7,
R.drawable.p8,
R.drawable.p9,
R.drawable.p10,
R.drawable.p11,
R.drawable.p12,
R.drawable.p13,
R.drawable.p14,
R.drawable.p15,
R.drawable.p16,
R.drawable.p17,
R.drawable.p18,
R.drawable.p19,
R.drawable.p20,
R.drawable.p21,
R.drawable.p22,
R.drawable.p23,
R.drawable.p24,
R.drawable.p25,
R.drawable.p26,
R.drawable.p27,
R.drawable.p28,
R.drawable.p29,
R.drawable.p30,
R.drawable.p31,
R.drawable.p32,
R.drawable.p33,
R.drawable.p34,
R.drawable.p35,
R.drawable.p36,
R.drawable.p37,
R.drawable.p38,
R.drawable.p39,
R.drawable.p40,
R.drawable.p41,
R.drawable.p42,
R.drawable.p43,
R.drawable.p44,
R.drawable.p45,
R.drawable.p46,
R.drawable.p47,
R.drawable.p48,
R.drawable.p49,
R.drawable.p50
};
Integer imageId;
TouchImageView touch;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
final Activity act = FullActivity.this;
final AdListener listener = FullActivity.this;
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
if (extras != null) {
imageId = extras.getInt("image");
touch = new TouchImageView(this);
Bitmap snoop = BitmapFactory.decodeResource(getResources(), mThumbIds[imageId]);
touch.setImageBitmap(snoop);
touch.setMaxZoom(4f); //change the max level of zoom, default is 3f
setContentView(touch);
}
final String PREFS_NAME = "AppPrefs";
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
int ad = settings.getInt("ad", 0);
if((imageId > 25)&&(ad < 1)){
touch.post(new Runnable() {
public void run(){
myController = new AdController(act, MY_LB_SECTION_ID,
listener);
myController.loadAd();
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.set_back:
setBack();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void setBack() {
WallpaperManager myWallpaperManager
= WallpaperManager.getInstance(getApplicationContext());
try {
myWallpaperManager.setResource(mThumbIds[imageId]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(FullActivity.this.getApplicationContext(), "Wallapers set!", Toast.LENGTH_SHORT).show();
}
public void onDestroy(){
myController.destroyAd();
super.onDestroy();
}
public void onAdClicked() {}
public void onAdClosed() {}
public void onAdCompleted() {
// TODO Auto-generated method stub
SharedPreferences settings = getSharedPreferences("AppPrefs", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("ad", 1);
// Commit the edits!
editor.commit();
}
public void onAdFailed() {
this.runOnUiThread(new Runnable() {
public void run() {
if(myController != null){
myController.destroyAd();
}
}
});
}
public void onAdLoaded() {}
public void onAdProgress() {}
}
We have made some adjustments to the code which should resolve this for you.
package com.mkstudio.hdwallpapers;
import java.io.IOException;
import android.app.Activity;
import android.app.WallpaperManager;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import com.Leadbolt.AdController;
import com.Leadbolt.AdListener;
public class FullActivity extends Activity{
private AdController myController;
private String MY_LB_SECTION_ID="729926945";
// references to our images
private Integer[] mThumbIds = {
R.drawable.p1,
R.drawable.p2,
R.drawable.p3,
R.drawable.p4,
R.drawable.p5,
R.drawable.p6,
R.drawable.p7,
R.drawable.p8,
R.drawable.p9,
R.drawable.p10,
R.drawable.p11,
R.drawable.p12,
R.drawable.p13,
R.drawable.p14,
R.drawable.p15,
R.drawable.p16,
R.drawable.p17,
R.drawable.p18,
R.drawable.p19,
R.drawable.p20,
R.drawable.p21,
R.drawable.p22,
R.drawable.p23,
R.drawable.p24,
R.drawable.p25,
R.drawable.p26,
R.drawable.p27,
R.drawable.p28,
R.drawable.p29,
R.drawable.p30,
R.drawable.p31,
R.drawable.p32,
R.drawable.p33,
R.drawable.p34,
R.drawable.p35,
R.drawable.p36,
R.drawable.p37,
R.drawable.p38,
R.drawable.p39,
R.drawable.p40,
R.drawable.p41,
R.drawable.p42,
R.drawable.p43,
R.drawable.p44,
R.drawable.p45,
R.drawable.p46,
R.drawable.p47,
R.drawable.p48,
R.drawable.p49,
R.drawable.p50
};
Integer imageId;
TouchImageView touch;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.full);
Bundle extras = getIntent().getExtras();
if (extras != null) {
imageId = extras.getInt("image");
touch = new TouchImageView(this);
Bitmap snoop = BitmapFactory.decodeResource(getResources(), mThumbIds[imageId]);
touch.setImageBitmap(snoop);
touch.setMaxZoom(4f); //change the max level of zoom, default is 3f
setContentView(touch);
}
final String PREFS_NAME = "SexyRec";
final Activity act = this;
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
int ad = settings.getInt("ad", 0);
if((imageId > 25)&&(ad < 1)){
touch.post(new Runnable() {
public void run(){
myController = new AdController(act, MY_LB_SECTION_ID, new AdListener() {
public void onAdProgress() {
// TODO Auto-generated method stub
}
public void onAdLoaded() {
// TODO Auto-generated method stub
}
public void onAdFailed() {
// TODO Auto-generated method stub
}
public void onAdCompleted() {
// TODO Auto-generated method stub
SharedPreferences settings = getSharedPreferences("SexyRec", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("ad", 1);
// Commit the edits!
editor.commit();
}
public void onAdClosed() {
// TODO Auto-generated method stub
}
public void onAdClicked() {
// TODO Auto-generated method stub
}
});
myController.loadAd();
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.set_back:
setBack();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void setBack() {
//chuckNorris.setResourceAsWallpaper(mThumbIds[imageId]);
WallpaperManager myWallpaperManager
= WallpaperManager.getInstance(getApplicationContext());
try {
myWallpaperManager.setResource(mThumbIds[imageId]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(FullActivity.this.getApplicationContext(), "Wallapers set!", Toast.LENGTH_SHORT).show();
}
public void onDestroy(){
myController.destroyAd();
super.onDestroy();
}
}

Categories

Resources