Tuesday 5 March 2013

Facebook Android SDK 3.0 - getting a user's profile picture

Here's another Facebook operation which you'd think should not only be easy to do but also be easy to find in the documentation. It certainly was easy to do, but once again wasn't so easy to find in the documentation. Oh and, strictly speaking, you don't need the Facebook SDK for this. You just need to make a HTTP GET call to the Facebook user's picture connection. (You'll need the Facebook SDK to get the user's Facebook id beforehand.)

final String userFacebookId = ...

new AsyncTask<Void, Void, Bitmap>()
{
  @Override
  protected Bitmap doInBackground(Void... params)
  {
    // safety check
    if (userFacebookId == null)
      return null;

    String url = String.format(
        "https://graph.facebook.com/%s/picture",
        userFacebookId);

    // you'll need to wrap the two method calls
    // which follow in try-catch-finally blocks
    // and remember to close your input stream

    InputStream inputStream = new URL(url).openStream();
    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

    return bitmap;
  }

  @Override
  protected void onPostExecute(Bitmap bitmap)
  {
    // safety check
    if (bitmap != null
        && !isChangingConfigurations()
        && !isFinishing())
      // do what you need to do with the bitmap :)
  }
}.execute();

Saturday 2 March 2013

When methods and functions do too much

It's like asking a robot to get you some milk and it comes back to you with flavoured milk. You might want flavoured milk, but you might not! Your methods should only do as much as they are contracted to do. No more.

Here's another example: you create an Android AlertDialog with the AlertDialog.Builder class. Now every time you click one of the buttons of your AlertDialog, the AlertDialog is automically dismissed, as well as notifying you that a button was clicked. But you don't want the AlertDialog to be dismissed, you only want to be notified that a button was clicked!

Sometimes doing more is less helpful.

Friday 1 March 2013

Android - load and show html from a file into a TextView

There's a known bug in the Android WebView such that a WebView set with a transparent background colour does not appear with a transparent background on all devices. None of the workarounds are definitive and work for all devices. An alternative to loading html in a WebView is to load it in a TextView. There are limitations as to what HTML tags can be used (see here) but if you're only doing basic HTML tagging, this will work:

try
{
  InputStream inputStream = getResources().getAssets().open("myFile.html");

  String html = IOUtils.toString(inputStream);

  myTextView.setText(Html.fromHtml(html));
}
catch (IOException exception)
{
  myTextView.setText("Failed loading html.");
}