Wednesday, June 17, 2015

Exception handling in Android Application

Standard
Hello All:

During application development for any platform there are chances of missing some corner cases which in turn leads to exceptions which can lead to crashes. In terms of android applications development this leads to crash of the application with a pop-up saying
"XYZ has stopped working"

There are various frameworks/ libraries available which can help is tracing down these unhandled exceptions. Some of these are
  1. Crittercism
  2. Parse
  3. Crashlytics
My personal favorite is Crashlytics. Crashlytics is almost free. You can get your copy from here.

Crashlytics comes with its own plugin for Android Studio which will do all the heavy lifting of setting up the library in your project.

Once the library is setup in the project logging is as easy as calling

Crashlytics.getInstance().core.logException(e);

However I like to make it more general. Below is the Interface which I use to log the exceptions (handled)

public interface ILogger {
    void log(String message);
    void log(Exception exception);
}

then setting up it in a sub-class of Application.
    public ILogger getLogger() {
        if (logger == null) {
            logger = new ILogger() {
                @Override
                public void log(String message) {
                    Crashlytics.getInstance().core.log(message);
                }

                @Override
                public void log(Exception e) {
                    StringWriter errors = new StringWriter();
                    e.printStackTrace(new PrintWriter(errors));
                    log(errors.toString());
                    Crashlytics.getInstance().core.logException(e);
                }
            };
        }
        return logger;
    }


Use it like
SuperApplication.getInstance().getLogger().log(exception);

Here SuperApplication is sub-class of Application class.

Hope this helps. Happy coding.



Thanks for printing this post. Hope you liked it.
Keep visiting and sharing.
Thanks,
Ashwani.

0 comments :

Post a Comment