Android, как обмениваться данными с Facebook Open Graph в новом SDK 3.0?

Прямо сейчас я настроил свое приложение Open Graph на Facebook. Это было одобрено. Я пытаюсь отправить свои «объекты» через параметры пакета, но мне любопытно, как настроить объект параметра пакета, как показано ниже.

РЕДАКТИРОВАТЬ:

Я создаю объект и действие, подобное этому

Objects и action это код для обмена

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

            try {                   
                RequestBatch requestBatch = new RequestBatch();                     
                Log.i("session requestBatch ==>", "requestBatch");

                JSONObject tropy = new JSONObject();

                tropy.put("type", "thebigtoss:tropy");
                tropy.put("title", "A Game of Thrones");
                tropy.put("url","http://www.thebigtoss.com/assets/app-icon.png");
                tropy.put("description", "supernatural forces are mustering.");

                // Set up object request parameters
                Bundle objectParams = new Bundle();
                objectParams.putString("object", tropy.toString());
                // Set up the object request callback
                Request.Callback objectCallback = new Request.Callback() {
                    @Override
                    public void onCompleted(Response response) {
                        Log.i("objectParams onCompleted ==>", "onCompleted");
                        // Log any response error
                        FacebookRequestError error = response.getError();
                        if (error != null) {                     
                            Log.i(TAG, "objectParams =>" +error.getErrorMessage());
                        }
                    }
                };                            
                // Create the request for object creation
                Request objectRequest = new Request(session, 
                        "me/objects/thebigtoss:trophy", objectParams, HttpMethod.POST, objectCallback);

                // Set the batch name so you can refer to the result
                // in the follow-on publish action request
            //  objectRequest.setBatchEntryName("objectCreate");      

                // Add the request to the batch
                requestBatch.add(objectRequest);

                Bundle actionParams = new Bundle();
                // Refer to the "id" in the result from the previous batch request
                actionParams.putString("trophy", "Action parametery");
                // Turn on the explicit share flag
                actionParams.putString("fb:explicitly_shared", "true");

                // Set up the action request callback
                Request.Callback actionCallback = new Request.Callback() {
                    @Override
                    public void onCompleted(Response response) {
                        // dismissProgressDialog();
                        FacebookRequestError error = response.getError();
                        if (error != null) {
                            Toast.makeText(MainActivity.this.getApplicationContext(),error.getErrorMessage(),Toast.LENGTH_LONG).show();
                        } else {
                            String actionId = null;
                            try {
                                JSONObject graphResponse = response.getGraphObject().getInnerJSONObject();
                                actionId = graphResponse.getString("id");
                            } catch (JSONException e) {
                                Log.i(TAG, "JSON error "+ e.getMessage());
                            }
                            Toast.makeText(MainActivity.this.getApplicationContext(),actionId, Toast.LENGTH_LONG).show();
                        }
                    }
                };                                
                // Create the publish action request
                Request actionRequest = new Request(session,
                        "me/thebigtoss:win", actionParams, HttpMethod.POST, actionCallback);                                
                // Add the request to the batch
                requestBatch.add(actionRequest);                                
                // Execute the batch request
                requestBatch.executeAsync();

            } catch (JSONException e) {
                //Auto-generated catch block
                e.printStackTrace();
            }               
        }               
    }        

Но я не получаю обмен данными в моем facebook

эта ошибка я получаю 12-10 15:26:25.710: I/MainActivity(27667): objectParams =>(#100) conflicting og:type found in path (thebigtoss:trophy) and 'properties' (thebigtoss:tropy)

в этой строке кода if (error != null) {
Log.i(TAG, "objectParams =>" +error.getErrorMessage());
}

Request.Callback objectCallback = new Request.Callback() {
                    @Override
                    public void onCompleted(Response response) {
                        Log.i("objectParams onCompleted ==>", "onCompleted");
                        // Log any response error
                        FacebookRequestError error = response.getError();
                        if (error != null) {                     
                            Log.i(TAG, "objectParams =>" +error.getErrorMessage());
                        }
                    }
                }; 

У кого-нибудь есть идея, как поделиться этим кодом в facebook opengraph.


person NagarjunaReddy    schedule 09.12.2013    source источник


Ответы (3)


Вы не можете просто поместить объект/действие открытого графа в Bundle.

Сначала вам нужно создать OpenGraphObject:

OpenGraphObject object = OpenGraphObject.Factory.createForPost("yournamespace:objectname");
object.setTitle("Sample Trophy");
object.setDescription("...");
//... set more properties as necessary

Затем создайте OpenGraphAction и добавьте к нему свой объект:

OpenGraphAction action = OpenGraphAction.Factory.createForPost("thebigtoss:win");
action.setProperty("trophy", object);

Наконец, опубликуйте его с помощью метода newPostOpenGraphActionRequest:

Request request = Request.newPostOpenGraphActionRequest(session, action, new Callback() {...});
person Ming Li    schedule 09.12.2013
comment
Опять же, вы помещаете действие открытого графа непосредственно в пакет, что не приведет к правильной сериализации. Почему OpenGraphObject не импортирует? Пожалуйста, попробуйте код, который я вставил выше напрямую. - person Ming Li; 10.12.2013
comment
Если класс не импортируется, то это другая проблема. Проверьте настройки своего проекта (и то, как вы используете Facebook SDK). OpenGraphObject является частью SDK. - person Ming Li; 11.12.2013

Это то, что я использую в своем приложении. Попытайся..

protected void postFacebook(final SherlockFragmentActivity activity) {
        Session session = Session.getActiveSession();
        if (!session.isOpened()) {
            AppMsg.makeText(getSherlockActivity(), "Please login to Facebook first.", AppMsg.STYLE_ALERT).show();
            return;
        }
        Bundle params = new Bundle();
        params.putString("name", "App Name");
        params.putString("caption", "Check out my mind-blowing app");
        params.putString("description", "Here goes my long description of the app.");
        params.putString("link", "http://play.google.com/store/apps/details?id=com.my.app");
        params.putString("picture", "http://.../ic_launcher.PNG");

        WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(activity, Session.getActiveSession(), params))
                .setOnCompleteListener(new OnCompleteListener() {

                    @Override
                    public void onComplete(Bundle values, FacebookException error) {
                        if (error == null) {
                            // When the story is posted, echo the success
                            // and the post Id.
                            final String postId = values.getString("post_id");
                            if (postId != null) {
                                AppMsg.makeText(activity, "Posted sucessfully.", AppMsg.STYLE_INFO).show();
                            } else {
                                // User clicked the Cancel button
                                Toast.makeText(activity.getApplicationContext(), "Publish cancelled",
                                        Toast.LENGTH_SHORT).show();
                            }
                        } else if (error instanceof FacebookOperationCanceledException) {
                            // User clicked the "x" button
                            Toast.makeText(activity.getApplicationContext(), "Publish cancelled", Toast.LENGTH_SHORT)
                                    .show();
                        } else {
                            // Generic, ex: network error
                            Toast.makeText(activity.getApplicationContext(), "Error posting story", Toast.LENGTH_SHORT)
                                    .show();
                        }
                    }

                }).build();
        feedDialog.show();
    }
person Sunny    schedule 09.12.2013
comment
Привет, @NagarjunaReddy, ты читал это? developers.facebook.com/docs/android/share-using -the-object-api - person Sunny; 10.12.2013
comment
Как сказал Мингли, вы не можете просто поместить объект/действие с открытым графиком в Bundle. - person Sunny; 10.12.2013
comment
Вы указали правильный URL? Указанный вами URL-адрес должен быть доступен для Facebook, иначе вы получите эту ошибку. - person Sunny; 10.12.2013
comment
В приведенном выше URL-адресе проверьте предварительные условия. - person Sunny; 10.12.2013
comment
измените действительный URL-адрес, но все равно произойдет то же самое. - person NagarjunaReddy; 10.12.2013
comment
давайте продолжим это обсуждение в чате - person NagarjunaReddy; 10.12.2013

Наконец, с большим трудом я нашел ответ на чтение этой документации.

ЭТО и ЭТО

этот код работает для меня

    // Set up object request parameters

            RequestBatch requestBatch = new RequestBatch();                     

            Bundle objectParams = new Bundle();
            objectParams.putString("type", type);
            objectParams.putString("title", title);
            objectParams.putString("url", dataurl);                  
            objectParams.putString("description",  description);
            objectParams.putString("image",  imagepath);         

            // Set up the object request callback
            Request.Callback objectCallback = new Request.Callback() {
                @Override
                public void onCompleted(Response response) {
                    Log.i("objectParams onCompleted ==>", "onCompleted");
                    // Log any response error
                    FacebookRequestError error = response.getError();
                    if (error != null) {                     
                        Log.i(TAG, "objectParams =>" +error.getErrorMessage());
                    }
                }
            };                       
            Log.i(TAG, " "+  "me/objects/thebigtoss:trophy");
            // Create the request for object creation
            Request objectRequest = new Request(session, 
                    "me/objects/"objectadata"", objectParams, HttpMethod.POST, objectCallback);                            

            // Set the batch name so you can refer to the result
            // in the follow-on publish action request              
            Log.i(TAG, "objectRequest ==>"+ "objectRequest");
            //objectRequest.setBatchEntryName("objectCreate");                    
            // Add the request to the batch
            requestBatch.add(objectRequest);      


            Bundle actionParams = new Bundle();
            Log.i(TAG, "actionParams ==>"+ "actionParams");
            // Refer to the "id" in the result from the previous batch request               
            actionParams.putString("trophy", dataurl);       
            actionParams.putString("image",  imagepath);                 

            // Set up the action request callback
            Request.Callback actionCallback = new Request.Callback() {
                @Override
                public void onCompleted(Response response) {
                    Log.i(TAG, "actionParams onCompleted==>"+ "actionParams onCompleted");
                    // dismissProgressDialog();
                    FacebookRequestError error = response.getError();
                    if (error != null) {
                        Log.i(TAG, "actionParams onCompleted if==>"+ error.getErrorMessage());
                        Toast.makeText(TrophyDetailsActivity.this.getApplicationContext(),error.getErrorMessage(),Toast.LENGTH_LONG).show();
                    } else {
                        Log.i(TAG, "actionParams onCompleted else==>"+ "actionParams onCompleted else");

                        String actionId = null;
                        try {
                            JSONObject graphResponse = response.getGraphObject().getInnerJSONObject();
                            actionId = graphResponse.getString("id");
                        } catch (JSONException e) {
                            Log.i(TAG, "JSON error "+ e.getMessage());
                        }
                        Log.i("actionId ==>", actionId);
                    }
                }
            };                                
            // Create the publish action request
            Request actionRequest = new Request(session,
                    "me/action", actionParams, HttpMethod.POST, actionCallback);                                
            // Add the request to the batch
            requestBatch.add(actionRequest);                                
            // Execute the batch request
            requestBatch.executeAsync();
person NagarjunaReddy    schedule 13.12.2013