简体   繁体   中英

How can I post my status on facebook using Graph API in android

I want to use Graph API in my android app to post text status using my android app but don't know how to use API perfectly... (I am using latest API)

This is my login Activity

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.appevents.AppEventsLogger;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;

import java.util.Arrays;


public class LoginToFacebook extends AppCompatActivity {

    public LoginButton loginButton;
    private CallbackManager callbackManager;
    public static final String LOGGED_IN_PREFFERENCE = "loggedInPrefference" ;
    private AccessToken accessToken;
    LoginResult loginResultOfClass;
    static SharedPreferences mPrefs;

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        if(mPrefs.getBoolean("loggedIn",false)==true);
        {
            Intent i = new Intent(LoginToFacebook.this,PostToWall.class);
            startActivity(i);


        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        FacebookSdk.sdkInitialize(getApplicationContext());
        mPrefs = getSharedPreferences(LOGGED_IN_PREFFERENCE, Context.MODE_PRIVATE);
        callbackManager = CallbackManager.Factory.create();
        accessToken = AccessToken.getCurrentAccessToken();

        setContentView(R.layout.activity_login_to_facebook);
        loginButton = (LoginButton) findViewById(R.id.login_button);
        loginButton.setReadPermissions(Arrays.asList("user_friends"));


        // Other app specific specialization




        // Callback registration
        loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                // App code

                loginResultOfClass = loginResult;

                SharedPreferences.Editor editor = mPrefs.edit();
                editor.putBoolean("loggedIn",true);
                editor.commit();


                Intent i = new Intent(LoginToFacebook.this,PostToWall.class);
                i.putExtra("UserName", loginResult.getAccessToken().getUserId());
                i.putExtra("AuthToken", loginResult.getAccessToken().getToken());
                startActivity(i);
            }

            @Override
            public void onCancel() {
                // App code

                Toast.makeText(LoginToFacebook.this, "login Cancelled", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(FacebookException exception) {
                // App code
                Toast.makeText(LoginToFacebook.this, "login exception"+exception.toString(), Toast.LENGTH_SHORT).show();

            }
        });




    }





    @Override
    protected void onResume() {
        super.onResume();
        // Logs 'install' and 'app activate' App Events.
        AppEventsLogger.activateApp(this);
    }


    @Override
    protected void onPause() {
        super.onPause();
        // Logs 'app deactivate' App Event.
        AppEventsLogger.deactivateApp(this);
    }

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


}

and this is my activity from where I want to POST my status

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.AccessToken;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.HttpMethod;
import com.facebook.login.widget.LoginButton;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Arrays;

public class PostToWall extends AppCompatActivity {
    TextView info;
    private LoginButton loginButton;
    private EditText post_text;
    Button post_button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FacebookSdk.sdkInitialize(getApplicationContext());
        setContentView(R.layout.activity_post_to_wall);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        post_text = (EditText)findViewById(R.id.post_text);
        post_button = (Button) findViewById(R.id.post_button);

        loginButton = (LoginButton) findViewById(R.id.login_button);
        loginButton.setPublishPermissions(Arrays.asList("publish_actions"));


        setSupportActionBar(toolbar);
        info = (TextView) findViewById(R.id.info);
        Intent i = getIntent();
        info.setText(i.getStringExtra("UserName") + i.getStringExtra("AuthToken"));

post_button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {


        Bundle params = new Bundle();
        params.putString("message", "hello post");
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("value", "SELF");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        params.putString("privacy", jsonObject.toString());

/* make the API call */

        GraphRequest request = new GraphRequest();
        request.setAccessToken(AccessToken.getCurrentAccessToken());
        request.setHttpMethod(HttpMethod.POST);

        request.setParameters(params);

        request.setGraphPath("/me/feed");
        request.setCallback(new GraphRequest.Callback() {
            @Override
            public void onCompleted(GraphResponse response) {

                Toast.makeText(PostToWall.this, "Post Success", Toast.LENGTH_SHORT).show();


            }
        });

        request.executeAsync();



    }
});

    }


}

I dont know why GraphRequest is not working for me... Help me to find my mistakes...

Please try the following code:

Bundle postContents = new Bundle();
            String selectedImageURL = galleryObj.getImageURL(mImageSelected);
            mImageStory = mTextBox.getText().toString();

            /*postContents.putString("attachment", "{\"name\":\""+mImageStory+"\","
            +"\"media\":[{\"type\":\"image\",\"src\":\""+selectedImageURL+"\",\"href\":\""+selectedImageURL+"\"}]"
            +"}");*/

//Below code is for posting text only
postContents.putString("attachment", "{\"name\":\""+mImageStory+"\""
            +"}");

            // OLD REST API stream.publish used to publish data onto the wall
            mFacebook.dialog(mContext, "stream.publish", postContents, new AndroidDialogListener());

The following is the listner for post the Image with Text on Wall:

public class AndroidDialogListener extends BaseDialogListener {

    public void onComplete(Bundle values) {
        final String postId = values.getString("post_id");
        if (postId != null) {
            Log.d("Facebook-Example", "Dialog Success! post_id=" + postId);

            // get the post id and send a request to get it posted on wall
            // once posted/failure then call back invoked
            mAsyncRunner.request(postId, new WallPostRequestListener());

        } else {
            Log.d("Facebook-Example", "No wall post made");
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM