Scala

Scala: Abstract classes, Traits, and Self-types

Abstract classes in Scala are very similar to abstract classes in Java. They represent a protocol or contract that is guaranteed to be in place for any subclass of that abstract class. The main difference between abstract classes in Scala and abstract classes in Java is that in Scala, an abstract class can declare fields that must be defined by it’s subclasses. So, for example:

abstract class Thing {
  val someValue: Int // not defined 
}
The following does not compile: The compiler will complain that ‘class SubThing needs to be abstract, since value someValue in class Thing of type Int is not defined’. In other words, SubThing claimed to be a concrete implementation of Thing, but did not define someValue. Just like you are required to provide the implementation of abstract methods, in Scala you must provide the values of members that are not defined in the abstract class. To get it to compile, you’d need: Traits Similar to interfaces in Java, traits are used to define object types by defining method signatures. Unlike Java, however, traits may define the default implementation for some methods. This sounds very much like an abstract class, so why use one over the other? Well, in Java the difference between using an abstract class and an interface is that a Java interface method may not contain any implementation. So abstract classes are useful in Java when you would like to provide the implementation details for some methods, while having the subclass provide the rest. Also, classes can implement as many interfaces as they’d like, but you can only extend one class. So, in Java there are two reasons to prefer one over the other. In Scala, however, since traits may provide the implementation details of whichever methods it chooses to, the usefulness of traits in Scala is the advantage of being able to compose classes with as many traits as you’d like. This crucial distinction between Java interfaces and Scala traits (in the former you cannot provide method bodies, whereas in the latter you can) is probably the reason why Martin Odersky has said that when you’re in doubt as to which to use, you should probably opt for using a trait. It’s more flexible in that it can be mixed in along with other traits and if you later decide it should be an abstract class, it’s very easy to convert it. The syntax for mixing in a trait in Scala: Self-types Typically, traits can be mixed into any class. However, it can sometimes be incredibly useful to define a trait whose operations depend on some of the methods or fields inside of the class it’s being mixed in to. Enter self-types. Self-types allow you to restrict the clases that are allowed to mix in a particular trait. For example: If, for example, you had a Person class like: You could mix in the Angry trait like this: Note that here you don’t need to use ‘with’ since person has no other superclass, but if it did, it’d be: If you created a new Person, like Person(“Bob”).growl, it would print “I’m pissed!!” Here’s a more powerful use of traits, from an exercise problem in the book “Scala for the Impatient”: The java.awt.Rectangle class has useful methods translate and grow that are unfortunately absent from classes such as java.awt.geom.Ellipse2D. In Scala, you can fix this problem. Define a trait RectangleLike with concrete methods translate and grow. Provide any abstract methods that you need for the implementation, so that you can mix in the trait like this: Horstmann, Cay S. (2012-03-08). Scala for the Impatient. Pearson Education (US). Let’s just concentrate on the grow() problem. In the java.awt.Rectangle class, grow is defined as public void grow(int h, int v) // Resizes the Rectangle both horizontally and vertically. But a java.awt.geom.Ellipse2D does not have a grow method. Using traits and self-types, we can fix this. Turns out that an Ellipse2D is a subclass of java.awt.geom.RectangularShape which defines an abstract method setFrame(double x, double y, double w, double h), which “Sets the location and size of the framing rectangle of this Shape to the specified rectangular values.” RectangularShape also defines getX(), getY(), getWidth() and getHeight(). We can use the RectangularShape as our self-type to monkey patch our Ellipse2D to have a grow() method. With this, we can do: Since our self-type was the abstract base class RectangularShape, we can also use this trait for a java.awt.geom.Rectangle2D.Double since it also extends from RectangularShape. There’s a lot more to know about traits and this only stratches the surface, but hopefully this provided a nice introduction.

Standard
Scala

An illustrative solution in Scala

I’ve been messing around with Scala a lot recently and I think the language hits such a sweet spot. Scala is a multi-paradigm language which means if you want to use an exclusively procedural/imperative/functional style or a mix of the three then you can. As Martin Odersky (the creator of the language) mentions in his fantastic book Programming in Scala, Scala doesn’t force you to do anything, but it definitely encourages   you to use a functional style where it makes sense. So, in this respect Scala is very welcoming to beginners; you can use it initially just to write more concise Java, but you are also lead to discover the beauty of functional programming.

Functional programming takes some getting used to when you’re coming from an imperative language like Java. You have to learn to think functionally. The essence of functional programming is the application of functions  to some input which produces a well-defined output. Functional programming, therefore, in contrast to imperative programming, shuns changing state and mutating data. As such, whereas in imperative languages it is common to use iteration/loops to continuously update the value of some variable to solve a given problem, in functional programming there is only f(x) – the function applied to x always yields a particular, well-defined value. As a consequence, in functional programming, many problems can be solved using recursive approaches. Scala supports tail recursion which makes recursive solutions practicable (in Java, the lack of tail call optimization frequently results in a stack overflows).

I just wanted to share a small bit of code that I thought showcases a lot of the neat things about Scala (and other functional languages as well).

The problem is a simple one: for any number, calculate the sum of its digits. For example,   the sum of the digits of 123 is 6, the sum of the digits of 375 = 15. It’s easy to see that this problem lends itself to a recursive solution, since the sum of the digits of the number 123 can be defined as the sum of 3 + the sum of the digits of 12. Here’s a solution in scala:

The basis for the solution is the fact that when dealing with ints, n/10 will always drop the last digit of a number and n%10 will always yield the rightmost digit. So, for example 45/10 will give you 4 and 45%10 yields 5. In our solution, once we arrive at a single digit number, we can simply add that number to our accumulated value. The accumulated value is also needed in order to allow the scala compiler to optimize the tail call here. Why? Because a solution is only tail recursive if the final statement in the function is a call to the functional itself. Without the ability to pass the stored up sum into our nested function, we wouldn’t be able to do this and we wouldn’t have tail call optimization. The beauty of being able to have nested functions is that since we know our accumulator must start at 0, we can avoid leaking the fact that we use an accumulator into our public API. Instead, we simply require an Int to be passed and we then define the solution as our nested function. Another awesome thing is that Scala has an annotation @tailrec which will raise a compiler error if the function cannot be optimized into a loop.

There are a lot of points here, but I thought this small example was actually pretty informative. It demonstrates the use of recursion, the ability to have nested functions, the bonus @tailrec annotation and how nicely this all comes together in the language.

I’m pretty new to Scala and functional programming so if I’m wrong about something, I’d love feedback.

EDIT -

As Nicolas B. kindly pointed out in the comments, I had a mistake in the above code. for case 0, I was returned n + acc when there’s no need to add n since I’m going from n to 0. Nicolas also pointed out that I can clean things up a bit more by using default arguments. Scala lets you specify default values for function parameters. The argument for such a parameter can optionally be omitted from a function call, in which case the corresponding argument will be filled in with the default. For us, this means we don’t need to supply the initial value of our accumulator when we call sumOfDigitsAcc. Combining Nicolas’s two points results in the following:

Standard
Uncategorized

Using textured/repeating patterns as backgrounds

In order to use textured pattern images as backgrounds for Layouts and Views in Android, it’s not enough to simply crop out a part of the image and run it through the Draw 9-Patch tool. Similarly, if you simply set the background resource/drawable to your image, you’ll find that it won’t look right. You’ll get the image repeating many times over in a way that doesn’t fill the background with the pattern you’re expecting.

Here’s how you should do it: define a Bitmap resource in your res/drawable and set the android:tileMode to “repeat” (it works similarly in html) which will repeat the bitmap in both directions.

res/drawable/mybackground.xml

then you’re free to use that as your backgroundResource in any View or Layout.

Head on over to subtlepatterns.com for some great, free textured patterns.

 

 

Standard
Uncategorized

Loopers, Handlers, RuntimeExceptions explained…

What’s a Looper, what’s a Handler and what’s up with “Can’t create handler inside thread that has not called Looper.prepare()?!”

NOTE: as always, consider everything I say as prefaced with “my understanding is that…”

A Looper is a simple message loop for a thread. Once loop() is called, an unending loop (literally while (true)) waits for messages to appear in a MessageQueue and then processes it once one shows up.

Some basic facts: a Looper is associated with a particular thread. When Looper.prepare() is called, it simply checks to see if the calling Thread already has a Looper associated with it. If it does, it throws a RuntimeException because you can only have one Looper per thread.

Now, many have experienced issues when using the parameterless constructor to create a Handler. Let’s back up. What’s a Handler? Handler is an object that simply lets you send/process messages and runnables associated with a thread’s MessageQueue. Internally, the MessageQueue that a Handler uses in order to do this is the MessageQueue that the Thread’s Looper “waits” for messages in. In other words, a Handler is the interface to the MessageQueue that the Looper is constantly “scanning”. Now you can understand the RuntimeException of “Can’t create handler inside thread that has not called Looper.prepare()”. This happens because the Handler can’t find a Looper associated with the Thread in which you’re trying to create the Handler (and therefore has no queue for it to use). It’s like you’re telling the system that you want to start pumping messages into a non-existent Queue. Calling Looper.prepare is what initially associates a new Looper (and the MessageQueue) with the “current thread”.

So, you can of course use the Handler constructor that takes a Looper (new Handler(Looper looper) if you already have a reference to one. And, you can always get a Looper by calling the static method Looper.getMainLooper(), which “Returns the application’s main looper, which lives in the main thread of the application.”

How does this work? Seems like magic, but the reason it works is because theres a static method inside of Looper called prepareMainLooper which the system calls inside of main(). Yes, the main which developers never encounter. main() is in the class ActivityThread and, sure enough, it calls Looper.prepareMainLooper. This is how/why you can do something Handler handler = new Handler(Looper.getMainLooper()). It’s because the system already created a “main” looper for you.

Feedback I’m interested in:

  1. “You were wrong about X”
  2. “You could be clearer about Y”
  3. “Here are some other helpful resources for learning about Loopers/Threads/Handler internals”
Standard
Uncategorized

A piece of advice for newcomers to OOP

I’m really surprised by how often I see people who are basically proficient in some language (I mean syntax, etc), but are entirely unaware of how a little bit of object orientation will solve their basic problems.

Here’s a question that I recently answered on StackOverflow which is a perfect example:

“How can I return multiple values?”

I’m not picking on the OP at all. He could very well have just been starting out and he asked a legitimate question. But, I’ve seen others struggle with similar issues; they know how to call methods, instantiate objects, etc. They’ve exhausted the language specification itself and are trying to solve some relatively simple problem, but they run up against a wall.

To be an efficient programmer, you eventually have to learn to use libraries and other pre-fab stuff. Rolling your own solution every time just doesn’t make sense. But here’s my advice for newcomers: when you need to represent/model some thing, create your own abstract data type. Every time. I don’t care how simple the “thing” is that you’re trying to represent. Just create your own ADT. Sure, this will be somewhat inefficient. Newbies will likely be creating complex objects when all they need is some simple data structure from the Collections API, etc etc. But that’s the point: you can actually appreciate what those data structures are, once you accustom yourself to the idea of objects. There is no magic about it. There’s no difference between Java’s built in data types and yours. The built-in ones are just very well designed and basically bullet-proof.

The reason I recommend this is because there’s a tendency for newbies to OOP to view the libraries or framework they’re using as magic. And that doesn’t help them to learn programming. If you look at the Android source code, as an example, you’ll see that so many of the objects that you interact with all the time as the user of the API are really just custom data types. That’s all it is.

Standard
Android

Demystifying Context in Android

The topic of Context in Android seems to be confusing too many. People just know that Context is needed quite often to do basic things in Android. People sometimes panic because they try to do perform some operation that requires the Context and they don’t know how to “get” the right Context.

I’m going to try to demystify the idea of Context in Android. A full treatment of the issue is beyond the scope of this post, but I’ll try to give a general overview so that you have a sense of what Context is and how to use it.

To understand what Context is, let’s take a look at the source code:

http://androidxref.com/4.2.2_r1/xref/frameworks/base/core/java/android/content/Context.java

What exactly is Context? Well, the documentation itself provides a rather straightforward explanation: The Context class is an “Interface to global information about an application environment.” The Context class itself is declared as abstract class, whose implementation is provided by the Android OS. The documentation further provides that Context “…allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.” You can understand very well, now, why the name is Context. It’s because it’s just that. The Context provides the link or hook, if you will, for an Activity, Service, or any other component, thereby linking it to the system, enabling access to the global application environment. In other words: the Context provides the answer to the components question of “where the hell am I in relation to app generally and how do I access/communicate with the rest of the app?”

If this all seems a bit confusing, a quick look at the methods exposed by the Context class provides some further clues about its true nature. Here’s a random sampling of those methods:

  1. getAssets()
  2. getResources()
  3. getPackageManager()
  4. getString()
  5. getSharedPrefsFile()

What do all these methods have in common? They all enable whoever has access to the Context to be able to access application-wide resources. Context, in other words, hooks the component that has a reference to it to the rest of application environment. The assets (think ‘/assets’ folder in your project), for example, are available across the application, provided that an Activity, Service or whatever knows how to access those resources. Same goes for “getResources()” which allows to do things like “getResources().getColor()” which will hook you into the colors.xml resource (nevermind that aapt enables access to resources via java code, that’s a separate issue).

The upshot is that Context is what enables access to system resources and its what hooks components into the “greater app.”

Let’s look at the subclasses of Context, the classes that provide the implementation of the abstract Context class. The most obvious class is the Activity class. Activity inherits from ContextThemeWrapper, which inherits from ContextWrapper, which inherits from Context itself. Those classes are useful to look at to understand things at a deeper level, but for now it’s sufficient to know that ContextThemeWrapper and ContextWrapper are pretty much what they sound like. They implement the abstract elements of the Context class itself by “wrapping” a context (the actual context) and delegating those functions to that context. An example is helpful – in the ContextWrapper class, the abstract method “getAssets” from the Context class is implemented as follows:

@Override
    public AssetManager getAssets() {
        return mBase.getAssets();
    }

mBase is simply a field set by the constructor to a specific context. So a context is wrapped and the ContextWrapper delegates its implementation of the getAssets method to that context. Let’s get back to examining the Activity class which ultimately inherits from Context to see how this all works.

You probably know what an Activity is, but to review – it’s basically ‘a single thing the user can do. It takes care of providing a window in which to place the UI that the user interacts with.’ Developers familiar with other APIs and even non-developers might think of it vernacularly as a “screen.” That’s technically inaccurate, but it doesn’t matter for our purposes.

So how do Activity and Context interact and what exactly is going in their inheritance relationship?

Again, it’s helpful to look at specific examples. We all know how to launch Activities. Provided you have “the Context” from which you are you are starting the Activity, you simply call startActivity(intent), where the Intent describes the context from which you are starting an Activity and the Activity you’d like to start. This is the familiar startActivity(this, SomeOtherActivity.class). And what is “this”? “this” is your Activity because the Activity class inherits from Context. The full scoop is like this:

When you call startActivity, ultimately the Activity class executes something like this:

Instrumentation.ActivityResult ar =
                mInstrumentation.execStartActivity(
                    this, mMainThread.getApplicationThread(), mToken, this,
                    intent, requestCode);

Ok, so it utilizes the execStartActivity method from the Instrumentation class (actually from an inner class in Instrumentation called ActivityResult). At this point we are beginning to get a peek at the system internals. This is where OS actually handles everything. So how does Instrumentation start the Activity exactly? Well, the param “this” in the execStartActivity method above is the your Activity, i.e. the Context, and the execStartActivity makes use of this context. A 30,000 overview is this: the Instrumentation class keeps tracks of a list of Activities that it’s monitoring in order to do it’s work. This list is used to coordinate all of the activities and make sure everything runs smoothly in managing the flow of activities. There are some operations which I haven’t fully looked into which coordinate thread and process issues. Ultimately, the ActivityResult uses a native operation – ActivityManagerNative.getDefault().startActivity() which uses the Context that you passed in when you called startActivity. The context you passed in is used to assist in “intent resolution” if needed. Intent resolution is the process by which the system can determine the target of the intent if it is not supplied. (Check out the guide

here for more details.) And in order for Android to do this, it needs access to information that is supplied by Context. Specifically, the system needs to access to a ContentResolver so it can “determine the MIME type of the intent’s data.”

This whole bit about how startActivity makes use of context was a bit complicated and I don’t fully understand the internals myself. My main point was just to illustrate how application-wide resources need to be accessed in order to perform many of the operations that are essential to an app. Context is what provides access to these resources.

A simpler example might be Views. We all know what you create a custom View by extending RelativeLayout or some other View class, you must provide a constructor that takes a Context as an argument. When you instantiate your custom View you pass in the context. Why? Because the View needs to be able to have access to themes, resources, and other View configuration details. View configuration is actually a great example. Each Context has various parameters (fields in Context’s implementations) that are set by the OS itself for things like the dimension or density of the display. It’s easy to see why this information is important for setting up Views, etc.

One final word: for some reason people new to Android (and even people not so knew) seem to completely forget about object-oriented programming when it comes to Android. For some reason, people try to bend their Android development to pre-conceived paradigms or learned behaviors. Android has it’s own paradigm and a certain pattern that is actually quite consistent if let go of your pre-conceived notions and simply read the documentation and dev guide. My real point, however, while “getting the right context” can sometimes be tricky, people unjustifiably panic because they run into a situation where they need the context and think they don’t have it. Once again, Java is an object-oriented language with an inheritance design. You only “have” the context inside of your Activity because your activity itself inherits from Context. There’s no magic to it (except for the all the stuff the OS does by itself to set various parameters and to correctly “configure” your context). So, putting memory/performance issues aside (e.g. holding references to context when you don’t need to or doing it in a way that has negative consequences on memory, etc), Context is an object like any other and it can be passed around just like any POJO. Sometimes you need might need to do clever things to retrieve that context, but any regular Java class that extends from nothing other than Object itself can be written in a way that has access to context; simply expose a public method that takes a context and then use it in that class as needed.

This was not intended as an exhaustive treatment on Context or Android internals, but I hope it’s helpful in demystifying Context a little bit.

Feedback I’m interested in:

  1. “You were wrong about X”
  2. “You could be clearer about Y”
  3. “Here are some other helpful resources for learning about Context/Android internals”
Standard
Uncategorized

Reusable AsyncTask: simple example

Someone on IRC (#android-dev in FreeNode) asked me about how they could implement an AsyncTask in a reusable way, i.e. they didn’t want the AsyncTask as an inner class inside of the Activity.

This can be done very easily with a classic Observer pattern. Using this listener, any Activity can register as a listener and make use of the task.

A simple example can be found here: https://github.com/levinotik/ReusableAsyncTask

tl;dr

1. Define an interface that your Activity implements.
2. Set the listener on your AsyncTask.
3. Have the AsyncTask call the listeners method in onPostExecute.
4. Perform whatever operation you need to in the implemented method in your Activity.

Standard
Fonts, Memory, Typeface, Views

Custom fonts and memory issues: a quick fix

Android allows you to import custom fonts into your project (just copy a .ttf file into your assets folder and you’re good to go). Typically, you’ll grab the custom font, like this 

  Typeface myTypeface = Typeface.createFromAsset(getResources().getAssets(), "fonts/DroidSerif-Bold.ttf"); 

If you’re using custom fonts a lot (constantly grabbing the font inside of your Views or Activities), it can create a major strain on memory. In my app, I noticed that as I switched between activities, Logcat was spitting out something like the following: DEBUG/skia(1510): purging 197K from font cache [20 entries]. Ok, so apparently there’s some caching mechanism and it’s getting purged. Sounds good. The problem was that this was happening way too often. Eventually, the memory was so strained that Android started killing all processes on the device until, eventually, my app was killed as well.

Here’s how to fix this: if you need to grab a custom font often, use a Singleton which holds on to and returns the Typeface when you request. For good measure, you can even hold onto the Typeface as a static field inside of the classes in which you use it.

All you need is something like this:

public class TypefaceSingleton {

private static TypefaceSingleton instance = new TypefaceSingleton();

private TypefaceSingleton() {}

public static TypefaceSingleton getInstance() {
return instance;
}

public Typeface getDroidSerif() {
return Typeface.createFromAsset(ThinkNearApp.getContext().getResources().getAssets(), "fonts/DroidSerif-Bold.ttf");
}
}

Notice, I’m using “eager”, as opposed to “lazy” instantiation (where getInstance() checks if the instance is null), but either way should work. After I switched to using the Singleton implementation, the memory issues disappeared.

Hope this helps.

Standard
ListView

ListView selector – use NinePatch, not solid colors

Many people have posted examples  of how to implement your own own custom selector for a ListView. Essentially, you create a StateListDrawable with different states for pressed, selected, etc. The only issue you might run into is if you try using a solid color for one of your states. For example, if your selector has something like:

<item android:state_pressed=”true” android:drawable=”@drawable/blue”/> where “blue” is defined in your colors.xml like so <drawable name=”blueselector”>#037DF1</drawable>

The problem you’re likely to encounter is that when an item in the ListView is selected, the ENTIRE ListView will display the pressed state color.

The solution: use a draw 9, stretchable image as the drawable, instead of a solid color. That’s all there is to it.

(On a Mac, I’ll get the color from http://www.colorschemer.com/online.html, hit CTRL + SHIFT + 4 – this lets me grab a snapshot of an area – then I run it through the draw 9 tool and drop it in res/drawable.)

 

Standard