简体   繁体   中英

FaceBook: posting same status to user wall getting error

my code work fine but i have issue . when i click again to post in the same list item getting force close . if i click in another list item will post successfully . basicly can't post same text1 again Without posting another text and back to post text1 .

private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
private boolean pendingPublishReauthorization = false;
private static final String TAG = "FaceBook";
private Boolean isShared;

private UiLifecycleHelper uiHelper;


@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_view);
    uiHelper = new UiLifecycleHelper(this, callback);
    uiHelper.onCreate(savedInstanceState);

       if (savedInstanceState != null) {
        pendingPublishReauthorization = savedInstanceState.getBoolean(
                PENDING_PUBLISH_KEY, false);
    }
    ls = (ListView) findViewById(android.R.id.list);
    ls.setAdapter(new MyAdapter(this, android.R.layout.simple_list_item_1,
            0, ITEMS));


}

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

    uiHelper.onActivityResult(requestCode, resultCode, data, new FacebookDialog.Callback() {
        @Override
        public void onError(FacebookDialog.PendingCall pendingCall, Exception error, Bundle data) {
            Log.e("Activity", String.format("Error: %s", error.toString()));
        }

        @Override
        public void onComplete(FacebookDialog.PendingCall pendingCall, Bundle data) {
            Log.i("Activity", "Success!");
        }
    });
}

     private class MyAdapter extends ArrayAdapter<String> {
    LayoutInflater inflater = (LayoutInflater)  getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    public MyAdapter(Context context, int resource, int textViewResourceId,
            ArrayList<String> iTEMS) {
        super(context, resource, textViewResourceId, iTEMS);
        // TODO Auto-generated constructor stub
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.view_item, parent,
                    false);

        }
        tv_content_item = (TextView) convertView
                .findViewById(R.id.tv_content);

        tv_content_item.setText(ITEMS.get(position));
        tv_content_item.setTag(position);
        tv_content_item.setTypeface(Typeface.createFromAsset(getAssets(),
                "fonts/Hayah.otf"));

        TextView tv_counter = (TextView) convertView
                .findViewById(R.id.text_counter);
        tv_counter.setText(String.valueOf(position + 1));

        Button facebook = (Button) convertView
                .findViewById(R.id.btn_share_face);

        facebook.setOnClickListener(ViewActivity.this);
        return convertView;
    }

    @Override
    public String getItem(int position) {
        // TODO Auto-generated method stub
        return super.getItem(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return super.getItemId(position);
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return ITEMS.size();
    }

}



@Override
public void onClick(View v) {
    // TODO Auto-generated method stub

    final TextView tv = (TextView) ls.findViewWithTag(ls
            .getPositionForView(v));

    switch (v.getId()) {

        case R.id.btn_share_face:


            if(!isShared){

        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()) {
                    isShared=true;
                       publishStory(tv.getText().toString());

                }
            }
        });

        }else{
            Session session = Session.getActiveSession();

            if (session.isOpened()) {
                   publishStory(tv.getText().toString());


        }
        }
        break;
    }
}

@Override
protected void onResume() {
    super.onResume();
    uiHelper.onResume();

}



@Override
public void onPause() {
    super.onPause();
    uiHelper.onPause();

}

@Override
public void onDestroy() {
    super.onDestroy();
    uiHelper.onDestroy();

}

private Session.StatusCallback callback = new Session.StatusCallback() {
    @Override
    public void call(Session session, SessionState state, Exception exception) {
        onSessionStateChange(session, state, exception);
    }
};
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
    if (state.isOpened()) {
        Log.i(TAG, "Logged in...");
    } else if (state.isClosed()) {
        Log.i(TAG, "Logged out...");
    }
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putBoolean(PENDING_PUBLISH_KEY, pendingPublishReauthorization);
    uiHelper.onSaveInstanceState(outState);
}

private void publishStory(String txt) {
    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", txt);

        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 (JSONException e) {
                    Log.i(TAG,
                        "JSON error "+ e.getMessage());
                }
                FacebookRequestError error = response.getError();
                if (error != null) {
                    Toast.makeText(ViewActivity.this
                         .getApplicationContext(),
                         error.getErrorMessage(),
                         Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(ViewActivity.this
                             .getApplicationContext(), 
                             postId,
                             Toast.LENGTH_LONG).show();
                }
            }
        };

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

        RequestAsyncTask task = new RequestAsyncTask(request);
        task.execute();
    }

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

my logcat

01-15 07:10:29.771: W/dalvikvm(4584): threadid=1: thread exiting with uncaught exception (group=0x41e8c898)
01-15 07:10:29.771: E/AndroidRuntime(4584): FATAL EXCEPTION: main
01-15 07:10:29.771: E/AndroidRuntime(4584): java.lang.NullPointerException
01-15 07:10:29.771: E/AndroidRuntime(4584):     at com.droidibuilders.aqual_alolma.ViewActivity$4.onCompleted(ViewActivity.java:352)
01-15 07:10:29.771: E/AndroidRuntime(4584):     at com.facebook.Request$4.run(Request.java:1669)
01-15 07:10:29.771: E/AndroidRuntime(4584):     at android.os.Handler.handleCallback(Handler.java:730)
01-15 07:10:29.771: E/AndroidRuntime(4584):     at android.os.Handler.dispatchMessage(Handler.java:92)
01-15 07:10:29.771: E/AndroidRuntime(4584):     at android.os.Looper.loop(Looper.java:137)
01-15 07:10:29.771: E/AndroidRuntime(4584):     at android.app.ActivityThread.main(ActivityThread.java:5450)
01-15 07:10:29.771: E/AndroidRuntime(4584):     at java.lang.reflect.Method.invokeNative(Native Method)
01-15 07:10:29.771: E/AndroidRuntime(4584):     at java.lang.reflect.Method.invoke(Method.java:525)
01-15 07:10:29.771: E/AndroidRuntime(4584):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1187)
01-15 07:10:29.771: E/AndroidRuntime(4584):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
01-15 07:10:29.771: E/AndroidRuntime(4584):     at dalvik.system.NativeStart.main(Native Method)

Your code is fine don't have any issue with the code. The only thing is facebook SDK does not allow to post multiple status with the same text . and there is timeline of i think one minute. You can post the same status more than once after 1minute . If you change the text lets say try to append the current time with your post text so that the two status is never same. And you can post now many times the same status but the time would be different.

thank you .. i edited my onComplete and work fine .

 public void onCompleted(Response response) {
                FacebookRequestError error = response.getError();
                if (error != null) {
                    Toast.makeText(ViewActivity.this
                         .getApplicationContext(),
                        getString(R.string.post_faild),
                         Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(ViewActivity.this
                             .getApplicationContext(), 
                             getString(R.string.post_succeed),
                             Toast.LENGTH_LONG).show();
                }
            }
        };

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