将图片上传到脸书

时间:2013-04-29 16:35:38

标签: android facebook image-uploading

嘿那里 我知道很多人都问过这个问题,但没有一个人可以帮助我,这就是我想要的是如何制作一个按钮onclick必须启动一个照片选择器并将所选图片上传到Facebook?

我真的卡住了,没有一个答案可以帮助我。我有一个代码,它发送文本,它的工作正常。但现在我也要上传图片了,所以我怎么能做到呢?有人可以帮帮我吗?

最好的问候

更新 - >这就是我要发布的内容

public class TestPost extends Activity{
private Facebook mFacebook;
private CheckBox mFacebookCb;
private ProgressDialog mProgress;

private Handler mRunOnUi = new Handler();

private static final String APP_ID = "app id here";

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

    setContentView(R.layout.post);

    final EditText reviewEdit = (EditText) findViewById(R.id.revieew);
    mFacebookCb               = (CheckBox) findViewById(R.id.cb_facebook);

    mProgress   = new ProgressDialog(this);

    mFacebook   = new Facebook(APP_ID);

    SessionStore.restore(mFacebook, this);

    if (mFacebook.isSessionValid()) {
        mFacebookCb.setChecked(true);

        String name = SessionStore.getName(this);
        name        = (name.equals("")) ? "Unknown" : name;

        mFacebookCb.setText("  Facebook  (" + name + ")");
    }

    ((Button) findViewById(R.id.button1)).setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            String review = reviewEdit.getText().toString();

            if (review.equals("")) return;

            if (mFacebookCb.isChecked()) postToFacebook(review);
        }
    });
  private void postToFacebook(String review) {  
    mProgress.setMessage("Posting ...");
    mProgress.show();

    AsyncFacebookRunner mAsyncFbRunner = new AsyncFacebookRunner(mFacebook);

    Bundle params = new Bundle();

    params.putString("message", review);
    params.putString("name", "Dexter");
    params.putString("caption", "londatiga.net");
    params.putString("link", "http://www.londatiga.net");
    params.putString("description", "Dexter, seven years old dachshund who loves to catch cats, eat carrot and krupuk");
    params.putString("picture", "http://twitpic.com/show/thumb/6hqd44");

    mAsyncFbRunner.request("me/feed", params, "POST", new WallPostListener());
}

private final class WallPostListener extends BaseRequestListener {
    public void onComplete(final String response) {
        mRunOnUi.post(new Runnable() {
            @Override
            public void run() {
                mProgress.cancel();

                Toast.makeText(TestPost.this, "Posted to Facebook", Toast.LENGTH_SHORT).show();
            }
        });
    }

} }

更新2 - > logcat和错误apper

    04-30 12:45:02.471: W/Bundle(29461): Key method expected byte[] but value was a java.lang.String.  The default value <null> was returned.
    04-30 12:45:02.476: W/Bundle(29461): Attempt to cast generated internal exception:
    04-30 12:45:02.476: W/Bundle(29461): java.lang.ClassCastException: java.lang.String
    04-30 12:45:02.476: W/Bundle(29461):    at android.os.Bundle.getByteArray(Bundle.java:1305)
    04-30 12:45:02.476: W/Bundle(29461):    at com.facebook.android.Util.openUrl(Util.java:155)
    04-30 12:45:02.476: W/Bundle(29461):    at com.facebook.android.Facebook.request(Facebook.java:559)
    04-30 12:45:02.476: W/Bundle(29461):    at com.facebook.android.AsyncFacebookRunner$2.run(AsyncFacebookRunner.java:208)
    04-30 12:45:02.476: W/Bundle(29461): Key format expected byte[] but value was a java.lang.String.  The default value <null> was returned.
    04-30 12:45:02.476: W/Bundle(29461): Attempt to cast generated internal exception:
    04-30 12:45:02.476: W/Bundle(29461): java.lang.ClassCastException: java.lang.String
    04-30 12:45:02.476: W/Bundle(29461):    at android.os.Bundle.getByteArray(Bundle.java:1305)
    04-30 12:45:02.476: W/Bundle(29461):    at com.facebook.android.Util.openUrl(Util.java:155)
    04-30 12:45:02.476: W/Bundle(29461):    at com.facebook.android.Facebook.request(Facebook.java:559)
    04-30 12:45:02.476: W/Bundle(29461):    at com.facebook.android.AsyncFacebookRunner$2.run(AsyncFacebookRunner.java:208)
    04-30 12:45:02.476: W/dalvikvm(29461): threadid=10: thread exiting with uncaught exception (group=0x4001e578)
    04-30 12:45:02.476: E/AndroidRuntime(29461): FATAL EXCEPTION: Thread-11
    04-30 12:45:02.476: E/AndroidRuntime(29461): java.lang.NullPointerException
    04-30 12:45:02.476: E/AndroidRuntime(29461):    at java.net.URLDecoder.decode(URLDecoder.java:104)
    04-30 12:45:02.476: E/AndroidRuntime(29461):    at java.net.URLDecoder.decode(URLDecoder.java:48)
    04-30 12:45:02.476: E/AndroidRuntime(29461):    at com.facebook.android.Util.openUrl(Util.java:167)
    04-30 12:45:02.476: E/AndroidRuntime(29461):    at com.facebook.android.Facebook.request(Facebook.java:559)
    04-30 12:45:02.476: E/AndroidRuntime(29461):    at com.facebook.android.AsyncFacebookRunner$2.run(AsyncFacebookRunner.java:208)

* 这是来电*

    ((Button) findViewById(R.id.upload)).setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            try{
            selectImage();
                    } 
            catch (Exception e) {
                    Toast toast = Toast.makeText(TestPost.this, "Unable to retrieve the selected image.", Toast.LENGTH_LONG);
                    toast.show();
                } finally {   
                }
            }
    });
    }

这是// TODO:上传到Facebook专辑

private void uploadImageBytes(byte[] bytes) {
    // TODO: upload to Facebook albums

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

          AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(mFacebook);
          mAsyncRunner.request(null, params, "POST", new WallPostListener());
}

解决方案 感谢#vorrtex以及下面回答的问题,他向我解释了他的代码问题,我得到了它的工作。如果将来需要它们,这里是其他人的完整代码

按钮调用方法

   ((Button) findViewById(R.id.upload)).setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            try{
            selectImage();
                    } 
            catch (Exception e) {
                    Toast toast = Toast.makeText(TestPost.this, "Unable to retrieve the selected image.", Toast.LENGTH_LONG);
                    toast.show();
                } finally {   
                }
            }
    });

这里是方法和流代码。代码来自已回答的问题

    private void selectImage() {

    Intent i = new Intent(Intent.ACTION_GET_CONTENT);
    i.setType("image/*");
    this.startActivityForResult(i, REQUEST_CODE_GALLERY);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        switch (requestCode) {
            case REQUEST_CODE_GALLERY:

                Uri selectedImage = data.getData();
                String filePath = null;

                String[] columns = { MediaColumns.DATA };
                Cursor cursor = this.getContentResolver().query(selectedImage, columns, null, null, null);
                if (cursor != null) {
                    cursor.moveToFirst();

                    int columnIndex = cursor.getColumnIndex(columns[0]);
                    filePath = cursor.getString(columnIndex);

                    if (!cursor.isClosed()) {
                        cursor.close();
                    }
                } else {
                    filePath = selectedImage.getPath();
                }

                if (filePath != null) {
                    this.uploadImagePath(filePath);
                } else {
                    Toast toast = Toast.makeText(this, "Unable to retrieve the selected image.", Toast.LENGTH_LONG);
                    toast.show();
                }

                break;
        }
    }
}

private void uploadImagePath(String filePath) {
    FileInputStream fileStream = null;
    try {
        fileStream = new FileInputStream(new File(filePath));
        byte[] bytes = convertStreamToBytes(fileStream);
        this.uploadImageBytes(bytes);
        placering = filePath; 
    } catch (Exception e) {
        Toast toast = Toast.makeText(this, "Unable to retrieve the selected image.", Toast.LENGTH_LONG);
        toast.show();
    } finally {
        closeStream(fileStream);
    }
}

private void uploadImageBytes(byte[] bytes) {
    // TODO: upload to Facebook albums

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

    AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(mFacebook);
    mAsyncRunner.request(null, params, "POST", new WallPostListener());
}


public static byte[] convertStreamToBytes(InputStream stream) throws IOException {
    if (stream == null) {
        return null;
    }

    ByteArrayOutputStream output = new ByteArrayOutputStream();

    copyStream(stream, output);

    return output.toByteArray();
}

public static void copyStream(InputStream from, OutputStream to) throws IOException {
    byte data[] = new byte[8192];
    int count;

    while ((count = from.read(data)) != -1) {
        to.write(data, 0, count);
    }

    from.close();
}

public static void closeStream(Closeable stream) {
    try {
        if (stream != null) {
            stream.close();
        }
    } catch (Exception e) {

    }
}

1 个答案:

答案 0 :(得分:1)

以下是如何启动照片选择器的解答:How to pick an image from gallery (SD Card) for my app?

然后您应该将所选图像上传到Facebook相册(/me/photos)。您必须执行此操作,因为me/feed仅接受URL字符串,而不接受二进制图像,因此您上传图像以便有一个URL字符串。

以下是如何执行此操作的答案:Android - Upload photo to Facebook with Facebook Android SDK。你应该用从gallery。中选择的文件路径替换'/sdcard/viewitems.png'。

然后您可以将链接发布到上传的图片:

// the onComplete method from the previous link
final String src = json.getString("src");

// ... create params ...
params.putString("picture", src);

mAsyncFbRunner.request("me/feed", params, "POST", new WallPostListener());

修改 顺便说一句,来自第一个链接的答案不完整而且不好,所以这里是完整的代码如何从库中选择图像并将其转换为字节:

private void selectImage() {
    Intent i = new Intent(Intent.ACTION_GET_CONTENT);
    i.setType("image/*");
    this.startActivityForResult(i, Constants.REQUEST_CODE_GALLERY);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        switch (requestCode) {
            case Constants.REQUEST_CODE_GALLERY:

                Uri selectedImage = data.getData();
                String filePath = null;

                String[] columns = { MediaColumns.DATA };
                Cursor cursor = this.getContentResolver().query(selectedImage, columns, null, null, null);
                if (cursor != null) {
                    cursor.moveToFirst();

                    int columnIndex = cursor.getColumnIndex(columns[0]);
                    filePath = cursor.getString(columnIndex);

                    if (!cursor.isClosed()) {
                        cursor.close();
                    }
                } else {
                    filePath = selectedImage.getPath();
                }

                if (filePath != null) {
                    this.uploadImagePath(filePath);
                } else {
                    Toast toast = Toast.makeText(this, "Unable to retrieve the selected image.", Toast.LENGTH_LONG);
                    toast.show();
                }

                break;
        }
    }
}

private void uploadImagePath(String filePath) {
    FileInputStream fileStream = null;
    try {
        fileStream = new FileInputStream(new File(filePath));
        byte[] bytes = convertStreamToBytes(fileStream);
        this.uploadImageBytes(bytes);
    } catch (Exception e) {
        Toast toast = Toast.makeText(this, "Unable to retrieve the selected image.", Toast.LENGTH_LONG);
        toast.show();
    } finally {
        closeStream(fileStream);
    }
}

private void uploadImageBytes(byte[] bytes) {
    // TODO: upload to Facebook albums
}

public static byte[] convertStreamToBytes(InputStream stream) throws IOException {
    if (stream == null) {
        return null;
    }

    ByteArrayOutputStream output = new ByteArrayOutputStream();

    copyStream(stream, output);

    return output.toByteArray();
}

public static void copyStream(InputStream from, OutputStream to) throws IOException {
    byte data[] = new byte[8192];
    int count;

    while ((count = from.read(data)) != -1) {
        to.write(data, 0, count);
    }

    from.close();
}

public static void closeStream(Closeable stream) {
    try {
        if (stream != null) {
            stream.close();
        }
    } catch (Exception e) {
        Log.e(TAG, e);
    }
}