2

I tried this: when isSessionValid getDetails directly else facebook.authorize and then getDetails in onActivityResult

public class MainActivity extends Activity {

    Facebook facebook = new Facebook("xxxxxxxxxxxxxxxx");
    AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
    private SharedPreferences mPrefs;

    @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 String[] {}, new DialogListener() {
                @Override
                public void onComplete(Bundle values) {
                    SharedPreferences.Editor editor = mPrefs.edit();
                    editor.putString("access_token", facebook.getAccessToken());
                    editor.putLong("access_expires",
                            facebook.getAccessExpires());
                    editor.commit();
                }

                @Override
                public void onFacebookError(FacebookError error) {
                }

                @Override
                public void onError(DialogError e) {
                }

                @Override
                public void onCancel() {
                }
            });
        }else{

            try {
                JSONObject json = Util.parseJson(facebook.request("me"));
                String facebookID = json.getString("id");
                String firstName = json.getString("first_name");
                String lastName = json.getString("last_name");
                String email = json.getString("email");
                String gender = json.getString("gender");
            } catch (Exception e) {

            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        facebook.authorizeCallback(requestCode, resultCode, data);
        try {
            JSONObject json = Util.parseJson(facebook.request("me"));
            String facebookID = json.getString("id");
            String firstName = json.getString("first_name");
            String lastName = json.getString("last_name");
            String email = json.getString("email");
            String gender = json.getString("gender");

        } catch (Exception e) {

        }
    }

    public void onResume() {
        super.onResume();
        facebook.extendAccessTokenIfNeeded(this, null);
    }
}

This works fine when I have facebook app installed on my system. But If not installed i get a Web View to enter facebook credentials and in logcat shows login-success, but none of the getDetails block is called.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Archie.bpgc
  • 23,812
  • 38
  • 150
  • 226
  • how to you sets the `access_token` in the `Facebook.java` ? Can you help me http://stackoverflow.com/questions/39994002/how-to-get-users-information-after-logging-in-facebook-app-and-authorized-your – natsumiyu Oct 12 '16 at 19:25
  • @mori Use `facebook.authorize` and get the access token inside `onComplete ` callback. But this is old code. May be it is changed now. – Archie.bpgc Oct 13 '16 at 04:05

1 Answers1

6

Here in initFacebook() function through you can login and perform you functionality, here i am fetching user's friends information.

private void initFacebook() 
{
    try
    {
        if (APP_ID == null) 
        {
            Util.showAlert(this,"Warning","Facebook Applicaton ID must be "+ "specified before running this example: see Example.java");
        }

        mFacebook = new Facebook();
        mAsyncRunner = new AsyncFacebookRunner(mFacebook);
        mFacebook.authorize(FacebookList.this, APP_ID, new String[] {"email", "read_stream", "user_hometown", "user_location","friends_about_me", "friends_hometown", "friends_location","user_relationships", "friends_relationship_details","friends_birthday", "friends_education_history","friends_website" }, new DialogListener()
        {
            public void onComplete(Bundle values) 
            {
                getHTTPConnection();
            }

            public void onFacebookError(FacebookError error) 
            {
                Log.i("public void onFacebookError(FacebookError error)....","....");
            }

            public void onError(DialogError e) 
            {
                Log.i("public void onError(DialogError e)....", "....");
                CustomConfirmOkDialog dialog = new CustomConfirmOkDialog(FacebookList.this, R.style.CustomDialogTheme, Utils.FACEBOOK_CONNECTION_ERROR);
                dialog.show();
            }

            public void onCancel() 
            {
                Log.i("public void onCancel()....", "....");
            }
        });

        SessionStore.restore(mFacebook, this);
        SessionEvents.addAuthListener(new SampleAuthListener());
        SessionEvents.addLogoutListener(new SampleLogoutListener());
    }
    catch (Exception e) 
    {
        e.printStackTrace();
    }
}

Here in getHTTPConnection(), proceeding for connection and sending fields, that we require about user's friends as here we can see that passing fields are fields=id,first_name,last_name,location,picture of friends. here you can change this fields according to application's requirements.

private void getHTTPConnection() 
{
    try
    {
        mAccessToken = mFacebook.getAccessToken();
        HttpClient httpclient = new DefaultHttpClient();
        String result = null;
        HttpGet httpget = new HttpGet("https://graph.facebook.com/me/friends?access_token="+ mAccessToken + "&fields=id,first_name,last_name,location,picture");
        HttpResponse response;
        response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        if (entity != null) 
        {
            result = EntityUtils.toString(entity);
            parseJSON(result);
        }
    }
    catch (Exception e) 
    {
        e.printStackTrace();
    }
}

Now after successfully connecting with facebook , we are getting JSON data and further to parse it .

private void parseJSON(String data1) throws Exception,NullPointerException, JSONException 
{
    try 
    {
        JSONObject jObj = new JSONObject(data1);
        JSONArray jObjArr = jObj.optJSONArray("data");
        int lon = jObjArr.length();


        for (int i = 0; i < lon; i++) 
        {
            JSONObject tmp = jObjArr.optJSONObject(i);

            String temp_image =  tmp.getString("picture");                          String temp_fname = tmp.getString("first_name");

            String temp_lname = tmp.getString("last_name");

            String temp_loc = null;

            JSONObject loc = tmp.getJSONObject("location");
            temp_loc = loc.getString("name");


        }
    } 
    catch (Exception e) 
    {
        Log.i("Exception1 is Here>> ", e.toString());
        e.printStackTrace();
    }
}

It is assumed that you have already added a facebook jar in to your application and for proceeding this code you can call initFacebook() in to onCreate() of your activity

Miral Dhokiya
  • 1,720
  • 13
  • 26
  • I only want to know where to call the method to getDetails?? i mean which method is called for sure, what ever might be the case: fb app installed or not, user has session or not?? Is it the onComplete method?? – Archie.bpgc Oct 25 '12 at 13:05
  • Please explain in brief what your codes does, and also try to give compact and complete code. BTW, +1 goes to you. – Mohammed Azharuddin Shaikh Oct 26 '12 at 06:19