Android:在Facebook上发布图片时获取NullPointerException

时间:2012-09-05 06:29:57

标签: java android facebook

我正在尝试使用以下代码在Facebook上发布图像。我在此行收到NullPointerException错误:bi.compress(Bitmap.CompressFormat.JPEG, 100, baos);

这是我的代码。怎么了?

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;

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

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.method.BaseKeyListener;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Toast;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;

/**
 * The Class PublishOnFacebook posts the events on facebook profile using
 * Facebook SDK
 */
public class PublishOnFacebook extends Activity {

    /** The Constant APP_ID. */
    private static final String APP_ID = "369797849756493";

    /** The Constant PERMISSIONS. */
    private static final String[] PERMISSIONS = new String[] { "publish_stream" };

    /** The Constant TOKEN. */
    private static final String TOKEN = "access_token";

    /** The Constant EXPIRES. */
    private static final String EXPIRES = "expires_in";

    /** The Constant KEY. */
    private static final String KEY = "facebook-credentials";

    /** The facebook. */
    private Facebook facebook;

    /** The msg to post. */
    private String msgToPost;

    /** The post image. */
    private String postImage;

    /*
     * (non-Javadoc)
     * 
     * @see android.app.Activity#onCreate(android.os.Bundle)
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.fb_layout);

        facebook = new Facebook(APP_ID);
        restoreCrediential(facebook);
        String facebookMessage = getIntent().getStringExtra("facebookMessage");
        String imageToUpload = getIntent().getStringExtra("uploadphoto");
        Log.d("ImageURL=: ", imageToUpload);
        if (facebookMessage == null) {
            facebookMessage = "Hello friends... Enjoy the rainy season.";
        }
        msgToPost = facebookMessage;
        postImage = imageToUpload;

    }

    /**
     * Do not share.
     * 
     * @param button
     *            the button
     */
    public void doNotShare(View button) {
        finish();
    }

    /**
     * Share the event on facebook .
     * 
     * @param button
     *            the button
     * @throws MalformedURLException
     *             the malformed url exception
     * @throws IOException
     *             Signals that an I/O exception has occurred.
     */
    public void share(final View button) throws MalformedURLException,
            IOException {

        if (!facebook.isSessionValid()) {
            loginAndPostToWall();
        } else {
            postToWall(msgToPost);
            postImageToWall(postImage);
        }
    }

    /**
     * Post image to wall.
     * 
     * @param imageUrl
     *            the image url
     */
    private void postImageToWall(String imageUrl) {
        byte[] data = null;

        Bitmap bi = BitmapFactory.decodeFile(imageUrl);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bi.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        data = baos.toByteArray();

        Bundle params = new Bundle();
        params.putString(Facebook.TOKEN, facebook.getAccessToken());
        params.putString("method", "photos.upload");
        params.putByteArray("picture", data);

        AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
        mAsyncRunner.request(null, params, "POST", new SampleUploadListener(),
                null);

    }

    /**
     * Login and post to wall.
     */
    private void loginAndPostToWall() {
        facebook.authorize(this, PERMISSIONS, Facebook.FORCE_DIALOG_AUTH,
                new LoginDialogListener());

    }

    /**
     * Post to wall.
     * 
     * @param message
     *            the message
     */
    private void postToWall(String message) {
        Bundle parameters = new Bundle();
        parameters.putString("message", message);
        parameters.putString("description", "topic to share");
        try {
            facebook.request("me");
            String response = facebook.request("me/feed", parameters, "POST");
            Log.d("response: ", response);
            if (response == null || response.equals("")) {
                response.equals("");
                showToast("No Response.");

            } else {
                showToast("Message has been posted to your walll!.");
            }
            finish();
        } catch (Exception e) {
            showToast("Message failed to posdt on wall.");
            e.printStackTrace();
            finish();
        }

    }

    /**
     * Show toast.
     * 
     * @param message
     *            the message
     */
    private void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    /**
     * Restore crediential.
     * 
     * @param facebook
     *            the facebook
     * @return true, if successful
     */
    public boolean restoreCrediential(Facebook facebook) {
        SharedPreferences sPreferences = getApplicationContext()
                .getSharedPreferences(KEY, Context.MODE_PRIVATE);
        facebook.setAccessToken(sPreferences.getString(TOKEN, null));
        facebook.setAccessExpires(sPreferences.getLong(EXPIRES, 0));

        return facebook.isSessionValid();

    }

    /**
     * Save credientails.
     * 
     * @param facebook
     *            the facebook
     * @return true, if successful
     */
    public boolean saveCredientails(Facebook facebook) {
        Editor editor = getApplicationContext().getSharedPreferences(KEY,
                Context.MODE_PRIVATE).edit();
        editor.putString(TOKEN, facebook.getAccessToken());
        editor.putLong(EXPIRES, facebook.getAccessExpires());

        return editor.commit();
    }

    /**
     * The listener interface for receiving loginDialog events. The class that
     * is interested in processing a loginDialog event implements this
     * interface, and the object created with that class is registered with a
     * component using the component's
     * <code>addLoginDialogListener<code> method. When
     * the loginDialog event occurs, that object's appropriate
     * method is invoked.
     * 
     * @see LoginDialogEvent
     */
    public class LoginDialogListener implements DialogListener {

        /*
         * (non-Javadoc)
         * 
         * @see
         * com.facebook.android.Facebook.DialogListener#onComplete(android.os
         * .Bundle)
         */
        public void onComplete(Bundle values) {
            saveCredientails(facebook);
            if (msgToPost != null) {
                postToWall(msgToPost);
            }
            postImageToWall(values.getString(Facebook.TOKEN));
        }

        /*
         * (non-Javadoc)
         * 
         * @see
         * com.facebook.android.Facebook.DialogListener#onFacebookError(com.
         * facebook.android.FacebookError)
         */
        public void onFacebookError(FacebookError e) {
            showToast("Auntication with facebook failed");
            finish();

        }

        /*
         * (non-Javadoc)
         * 
         * @see
         * com.facebook.android.Facebook.DialogListener#onError(com.facebook
         * .android.DialogError)
         */
        public void onError(DialogError e) {
            showToast("Auntication with facebbok failed");
            finish();
        }

        /*
         * (non-Javadoc)
         * 
         * @see com.facebook.android.Facebook.DialogListener#onCancel()
         */
        public void onCancel() {
            showToast("Aunticaton with facebbok failed");
            finish();
        }

    }

    /**
     * The listener interface for receiving sampleUpload events. The class that
     * is interested in processing a sampleUpload event implements this
     * interface, and the object created with that class is registered with a
     * component using the component's
     * <code>addSampleUploadListener<code> method. When
     * the sampleUpload event occurs, that object's appropriate
     * method is invoked.
     * 
     * @see SampleUploadEvent
     */
    public class SampleUploadListener extends BaseKeyListener implements
            RequestListener {

        /*
         * (non-Javadoc)
         * 
         * @see
         * com.facebook.android.AsyncFacebookRunner.RequestListener#onComplete
         * (java.lang.String, java.lang.Object)
         */
        public void onComplete(final String response, final Object state) {
            try {
                // process the response here: (executed in background thread)
                Log.d("Facebook-Example", "Response: " + response.toString());
                JSONObject json = Util.parseJson(response);
                final String src = json.getString("src");

                // then post the processed result back to the UI thread
                // if we do not do this, an runtime exception will be generated
                // e.g. "CalledFromWrongThreadException: Only the original
                // thread that created a view hierarchy can touch its views."

            } catch (JSONException e) {
                Log.w("Facebook-Example", "JSON Error in response");
            } catch (FacebookError e) {
                Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
            }
        }

        /*
         * (non-Javadoc)
         * 
         * @see
         * com.facebook.android.AsyncFacebookRunner.RequestListener#onFacebookError
         * (com.facebook.android.FacebookError, java.lang.Object)
         */
        public void onFacebookError(FacebookError e, Object state) {

        }

        /**
         * Gets the input type.
         * 
         * @param img
         *            the img
         * @return the input type
         */
        public Bitmap getInputType(Bitmap img) {
            return img;
        }

        /*
         * (non-Javadoc)
         * 
         * @see android.text.method.KeyListener#getInputType()
         */
        public int getInputType() {
            return 0;
        }

        /*
         * (non-Javadoc)
         * 
         * @see
         * com.facebook.android.AsyncFacebookRunner.RequestListener#onIOException
         * (java.io.IOException, java.lang.Object)
         */
        public void onIOException(IOException e, Object state) {

        }

        /*
         * (non-Javadoc)
         * 
         * @see com.facebook.android.AsyncFacebookRunner.RequestListener#
         * onFileNotFoundException(java.io.FileNotFoundException,
         * java.lang.Object)
         */
        public void onFileNotFoundException(FileNotFoundException e,
                Object state) {

        }

        /*
         * (non-Javadoc)
         * 
         * @see com.facebook.android.AsyncFacebookRunner.RequestListener#
         * onMalformedURLException(java.net.MalformedURLException,
         * java.lang.Object)
         */
        public void onMalformedURLException(MalformedURLException e,
                Object state) {

        }

    }
}

1 个答案:

答案 0 :(得分:1)

如果您查看BitmapFactory.decodeFile(String pathName)的文档,您会看到:

  

将文件路径解码为位图。如果指定的文件名为null,   或者无法解码为位图,该函数返回null。

我建议您查看尝试从中获取位图的网址。

/ toffer