Closing streams like a boss

This is one of my favorite tips and I also consider it a good practice.
How to close any java input or output Stream.

/**
* Closes the specified stream.
*
* @param stream The stream to close.
*/
private static void closeStream(Closeable stream) {
if (stream != null) {
   try {
      stream.close();
   } catch (IOException e) {
   Log.e("IO", "Could not close stream", e);
}
} 
Share

How to sort RSS by date

So, if you’ve got one or more RSS feeds and you want to sort them according to the pubdate, do this:

Collections.sort(myFeedsList, new Comparator<RssItemModel>() {

            @Override
            public int compare(RssItemModel lhs, RssItemModel rhs) {
                SimpleDateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");
                try {
                    Date date1 = formatter.parse(rhs.getPubDate());
                    Date date2 = formatter.parse(lhs.getPubDate());
                    return date1.compareTo(date2);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                return 0;
            }
        });
Share

Check if device has Android Market

Although the majority of the Android powered devices have the Android Market installed, there are a lot of devices that are running Android but haven’t passed the Compatibility Test Suite (CTS) because they do not comply with the Android Compatibility Definition Document (CDD). (more info here). These device may have high quality hardware and software but they haven’t the Android Market installed.

In my personal experience, these devices may lead to a large number of problems.
The easiest way to determine if a device has the Android Market installed (and has passed the CTS) is via the following method:

public static boolean hasMarket(Context ctx) {
        Intent market = new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q=test"));
        PackageManager manager = ctx.getPackageManager();
        List<ResolveInfo> list = manager.queryIntentActivities(market, 0);
        for (ResolveInfo info : list)
        {
            if (info.activityInfo.packageName.startsWith("com.android."))
                return true;
        }

        return false;
    }

You may wonder why we check the package name. The answer is simple: There can be a lot of applications that can handle the “market://” view intent such as SlideMe.

Share

Styled text in TextView

The easiest way of having styled text in a TextView is to use HTML and it is very easy to do it:

mTextView.setText(Html.fromHtml("This is a < b >bold< /b > and < i >italics< /i > styled textview!"));

Share