I have a RelativeLayout that I need to send to Facebook. So I figure the process involves
- Inflate the RelativeLayout
- Add content to each subview
- Convert the RelativeLayout to a Bitmap
- Compress the Bitmap
- Send the Bitmap to Facebook
In the following code, I have followed that process. But I am already getting a Null Pointer Exception at the line map = Bitmap.createBitmap(v.getDrawingCache(true));
. So instead of asking for help for each error I find along the way. I am posting my entire code for help. Perhaps some more experienced eyes can find some bugs with me.
Note: do not be distracted by the fact that the RelativeLayout only contains one ImageView; this is a test run.
public static void sendRelativeLayoutToFacebook(Activity activity, Bitmap testImg) {
Log.i(TAG, "inside sendRelativeLayoutToFacebook");
View v = prepareViewForFacebook(activity, testImg);
Bitmap photo = getBitmapFromView(v);
File filename = createCompressedImageFromBitmap(getContext(), photo);
Request request;
try {
request = Request.newUploadPhotoRequest(Session.getActiveSession(), filename, new Request.Callback() {
@Override
public void onCompleted(Response response) {
// some logging goes here maybe }
});
request.executeAsync();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
static View prepareViewForFacebook(Activity activity, Bitmap testImg) {
Log.i(TAG, "inside prepareViewForFacebook");
RelativeLayout view = (RelativeLayout) activity.getLayoutInflater().inflate(R.layout.facebook_photo, null, false);
ImageView imgView = (ImageView) view.findViewById(R.id.test_image);
imgView.setImageBitmap(testImg);
return view;
}
static Bitmap getBitmapFromView(View v) {
Log.i(TAG, "inside getBitmapFromView");
Bitmap map;
v.setDrawingCacheEnabled(true);
v.buildDrawingCache(true);
map = Bitmap.createBitmap(v.getDrawingCache(true));
v.setDrawingCacheEnabled(false);
return map;
}
static File createCompressedImageFromBitmap(Context context, Bitmap bitmap) {
Log.i(TAG, "inside createCompressedImageFromBitmap");
String fileName = "fb_img";// no .png or .jpg needed
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
FileOutputStream fo = context.openFileOutput(fileName, Context.MODE_PRIVATE);
fo.write(bytes.toByteArray());
// remember close file output
fo.close();
} catch (Exception e) {
e.printStackTrace();
fileName = null;
}
return new File(fileName);
}
Aucun commentaire:
Enregistrer un commentaire