我正在尝试将来自 url 的照片发布到 facebook。因此,我有一种方法可以将位于提供的 url 中的图像转换为位图,之后我想将图像发布到用户的 facebook 照片。这是我的代码:
将位于 URL 中的图像转换为位图图像的方法:
public Bitmap downloadImage(String url) {
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e("Hub","Error getting the image from server : " + e.getMessage().toString());
}
return bm;
}
这是我尝试在 facebook 中发布图像的地方:
private void postToFacebook(byte[] data) {
Session session = Session.getActiveSession();
if (session != null) {
Bundle postParams = new Bundle();
postParams.putString("caption", "Teste caption");
postParams.putByteArray("picture", data);
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("", "JSON error "+ e.getMessage());
}
FacebookRequestError error = response.getError();
if (error != null) {
Toast.makeText(getContext(), error.getErrorMessage(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), postId, Toast.LENGTH_LONG).show();
}
}
};
Request request = new Request(session, "me/photos", postParams, HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
} else {
Toast.makeText(getContext(), "Not logged", Toast.LENGTH_SHORT).show();
}
但是在这一行:response.getGraphObject(),我得到了空指针异常。我试图在后台线程中执行,如下所示:
class ConvertImageTask extends AsyncTask<URL, Integer, byte[]> {
AsyncTask<Params,Progress,Result>
@Override
protected void onPreExecute() {
super.onPreExecute(); // do nothing here
}
@Override
protected byte[] doInBackground(URL... params) {
byte[] data;
Bitmap bi = downloadImage(getPhotoUrl());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bi.compress(Bitmap.CompressFormat.PNG, 100, baos);
data = baos.toByteArray();
return data;
}
@Override
protected void onPostExecute(byte[] result) {
postToFacebook(result);
}
但错误仍在继续。
我怎样才能解决这个问题?谢谢!