I am fooling around with some basic programming in Android using Eclipse. I’m currently looking through a book and playing with some sample code that is written in the book.
I have noticed that in this particular book, all of the examples so far take pace in Main-Activity. I don’t believe this to be very good Object Oriented programming practice as I am from a traditional Java background.
Is this the common practice for mobile platforms? Shouldn’t classes all be contained in their own files?
Not necessarily as an Android
Activityis a ‘special case’ class. If you haven’t done already, I’d recommend you read Application Fundamentals and in particular the section on ‘Activities’ under Application components…Note the section of text that I’ve highlighted in bold. The point is that an
Activityin itself is not the complete app and if allowed, any third-party app can potentially invoke anActivityin one of your apps. As such, it is common to make anActivityas self-contained as possible. One particular example is the use of something like an AsyncTask which provides methods to execute a background thread as well as manipulate the UI – nesting a private class which extendsAsyncTaskis quite common and simplifies code. Nesting classes which extend BroadcastReceiver is also common for the same reason.That said, there is nothing wrong with using separate Java class files for POJO helper classes, for example, it just comes down to how complex your app is but it can mean taking special consideration of how certain Android classes work – the
AsyncTaskclass being one in particular if defined in a separate class file, try it and you’ll see what I mean. 🙂