Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

android - Facebook sdk 3.0.1 is not working properly

I am trying to login into the Facebook using Facebook sdk .But it not logging in .Its opening the dialog box but after getting the credentials its not working . If i install the Facebook app it opens the Facebook app but login is not completed i cant get the token and user id . I cant post the message to the wall also . But it displays the toast that "message successfully displayed" but it is not posted in the Facebook wall. Code:

public boolean isSession() {
    access_token = sp.getString(TOKEN, "x");
    expires = sp.getLong(EXPIRES, -1);
    Log.d("TAG", access_token);

    if (access_token != null && expires != -1) {
        facebook.setAccessToken(access_token);
        facebook.setAccessExpires(expires);
    }
    return facebook.isSessionValid();
}

private class LoginDialogListener implements DialogListener {
    @Override
    public void onComplete(Bundle values) {
        Log.d("TAG", "LoginONComplete");
        token =facebook.getAccessToken();
        token_expires = facebook.getAccessExpires();
        Log.d("TAG", "AccessToken: " + token);
        Log.d("TAG", "AccessExpires: " + token_expires);

        savePrefs3(EXPIRES,token_expires);
        savePrefs(TOKEN,token);
        mAsyncRunner.request("me", new IDRequestListener());
    }

    @Override
    public void onFacebookError(FacebookError e) {
        Log.d("TAG", "FacebookError: " + e.getMessage());
    }

    @Override
    public void onError(DialogError e) {
        Log.d("TAG", "Error: " + e.getMessage());
    }

    @Override
    public void onCancel() {
        Log.d("TAG", "OnCancel");
    }
}

private class IDRequestListener implements RequestListener {
    @Override
    public void onComplete(String response, Object state) {
        try {
            Log.d("TAG", "IDRequestONComplete");
            Log.d("TAG", "Response: " + response.toString());
            JSONObject json = Util.parseJson(response);

            Uid = json.getString("id");
            savePrefs("UID", Uid);
            final String name = json.getString("name");
        } catch (JSONException e) {
            Log.d("TAG", "JSONException: " + e.getMessage());
        } catch (FacebookError e) {
            Log.d("TAG", "FacebookError: " + e.getMessage());
        }
    }

    @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
    } 
}

public void postToWall(String message){
    Bundle parameters = new Bundle();
    parameters.putString("message", message);
    parameters.putString("description", "topic share");
    try {
        facebook.request("me");
        String response = facebook.request("me/feed", parameters, "POST");
        Log.d("Tests", "got response: " + response);
        if (response == null || response.equals("") ||
            response.equals("false")) {
            showToast("Blank response.");
        } else {
        showToast("Message posted to your facebook wall!");
        }
        finish();
    } catch (Exception e) {
        howToast("Failed to post to wall!");
        e.printStackTrace();
        finish();
    } 
}

private void showToast(String message) {
    Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}

please tell me where i am going wrong . after displaying a toast app gets closed. while loading the fb dialog if i touch the screen it either reloads or switching back to the app window. Please give immediate reply

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The Facebook object is depreciated.You can use the following code in your activity oncreate() method.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);



    requestWindowFeature(Window.FEATURE_NO_TITLE);

//  setContentView(R.layout.facebook_dialog);
    Session.openActiveSession(this, true, new Session.StatusCallback() {

        // callback when session changes state
        @Override
        public void call(Session session, SessionState state, Exception      exception) {
            if (session.isOpened()) {
                // make request to the /me API
                Request.executeMeRequestAsync(session, new   Request.GraphUserCallback() {

                    // callback after Graph API response with user object
                    @Override
                    public void onCompleted(GraphUser user, Response response) {
                        if (user == null) {



         Toast.makeText(LoginFacebook.this.getApplicationContext(), 
                                    "Facebook Error",

Toast.LENGTH_LONG).show();

 finish();
                        }
                        else
                        {

         Toast.makeText(LoginFacebook.this.getApplicationContext(), 
                                    user.getName()+" Logged in Successfully.",
                                    T    
   Toast.LENGTH_LONG).show();
                            finish();
                        }
                        //login_fb.setEnabled(true);
                        //progress.setVisibility(View.INVISIBLE);
                    }

                });


            }
        }
    });


}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
  finish();
}

And use the following code in the Manifest.xml file under the application tag.

    <meta-data
        android:name="com.facebook.sdk.ApplicationId"
        android:value="@string/app_id" />

    <activity
        android:name="com.facebook.LoginActivity"
        android:label="@string/app_name" >
    </activity>

After Loging in to post to wall you have to call this method...

       private void publishStory(String user) {
    try {
        Session session = Session.getActiveSession();

        if (session != null){

            // Check for publish permissions    
            List<String> permissions = session.getPermissions();
            if (!isSubsetOf(PERMISSIONS, permissions)) {
                pendingPublishReauthorization = true;
                Session.NewPermissionsRequest newPermissionsRequest = new Session
                        .NewPermissionsRequest(this, PERMISSIONS);
                session.requestNewPublishPermissions(newPermissionsRequest);
                return;
            }

            Bundle postParams = new Bundle();
            postParams.putString("message", messageToPost);

            Request.Callback callback= new Request.Callback() {
                public void onCompleted(Response response) {
                    JSONObject graphResponse = response
                            .getGraphObject()
                            .getInnerJSONObject();
                    String postId = null;
                    try {
                        postId = graphResponse.getString("id");
                    } catch (Exception e) {
                        Log.i("Test",
                                "JSON error "+ e.getMessage());
                    }
                    FacebookRequestError error = response.getError();
                    if (error != null) {
                        Toast.makeText(ShareOnFacebook.this
                                .getApplicationContext(),
                                error.getErrorMessage(),
                                Toast.LENGTH_SHORT).show();
                    } else {

                        progress.setVisibility(View.INVISIBLE);
                        toastmessage="Posted Successfully";
                        Toast.makeText(ShareOnFacebook.this
                                .getApplicationContext(),
                                toastmessage,
                                Toast.LENGTH_SHORT).show();

                    }
                }
            };

            Request request = new Request(session, user+"/feed", postParams, 
                    HttpMethod.POST, callback);

            RequestAsyncTask task = new RequestAsyncTask(request);
            task.execute();
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        Toast.makeText(ShareOnFacebook.this
                .getApplicationContext(),
                "Facebook Error",
                Toast.LENGTH_SHORT).show();
    }

}
private boolean isSubsetOf(Collection<String> subset, Collection<String> superset) {
    for (String string : subset) {
        if (!superset.contains(string)) {
            return false;
        }
    }
    return true;
}

and declare the variables as..

private static final List<String> PERMISSIONS =    Arrays.asList("publish_actions","manage_pages","publish_stream");
private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
private boolean pendingPublishReauthorization = false;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...