Scala on Android: best strategy for avoiding global data? - android

Suppose you have multiple activities in an app and need to share data. A pretty common pattern for Android developers it seems is to have some sort of singleton object (optionally attached to the Application singleton), and share data globally using that. That's bad enough in Java, but looks really ugly in Scala.
For message passing you can use Intents if your data consists of primitives. But what about your main domain model? I'd like to be able pass very complex objects. It seems I might be able to do that using Parcelable serialization, but I'm not sure how fast that is (my objects are data-heavy) and if it works well with Scala? Has anybody tried this?
Another idea would be to use the "HashMap of WeakReferences to Objects" strategy where the passed messages are references -- you've still got global data but access is guarded. Maybe I can get some opinions on that too, not just from Android folk but also some Scala folk.

The way I solved this was to include the Akka library in my app, and turn the global objects into messages that are passed between activities.
It seems to work OK, but not a lot of people are using Akka on Android so far and it's difficult to find best practices. If people have any comments about this strategy, let me know.

Related

Are there exceptions to no code in view model?

The general rule of thumb is that there should be no android specific code in view models to allow for easy testing.
I need to pass a bundle with lots of metadata to the view model to filter and then return to the view. The logic is pretty dense, it would best for the view model to handle this.
Are there any exceptions to this rule, such as using Bundle or other non-Activity or Fragment android classes? Or is there a suggestion work around?
This will probably get flagged, because it's very opinion based. There is no ultimate authority, as such, decreeing these things.
I personally have worked on some massive MVVM projects, both WPF and Xamarin, containing hundreds of thousands of lines of source code without a single line of code-behind anywhere. I can also honestly say that in the 10+ years I've been working with WPF I've never seen a single case where a problem wasn't solved elegantly by strict adherence to the paradigm. That's not to say some solutions weren't more verbose or convoluted...many most definitely were...but they were all elegant and, above all, robust.
Not everybody is as much an MVVM purist as I am. Josh Smith, one of the most respected authorities on WPF/MVVM, jokingly wrote in his book Advanced MVVM: "Others insist that there should never be a single line of code in the code-behind, based on the strange notion that code does not belong in the code-behind. What an odd bunch!"
The problem with any technology such as WPF is that the distinction between application layers is blurred at the best of times. We've all seen inexperienced WPF developers who, when faced with the power of XAML, start trying to cram as much logic into the view layer as possible. And then there are people who solve the code-behind problem by simply moving it into converters and behaviors, not realizing that these are really just a slightly more abstracted form of code-behind. (Not that I'm saying they shouldn't be used, I use them myself all the time, just keep in mind they are still view logic!)
So yeah, it's complicated. At the end of the day it's up to you, as the developer, to make the best and most sensible decisions based on the requirements of your project.

Creating a Serializable ArrayMap

I'm a newbie to Android, however I'm not entirely new to Java. From what I can tell, the ArrayMap should be used over the HashMap due to less memory used/performance increase. I'm not entirely sure when I should use one over the other beyond that, however while attempting to send an ArrayMap over a Bundle/Intent, I noticed that I was unable to do so, yet I could with a HashMap.
So, I thought, instead of just succumbing to using HashMap, especially when it's not necessary to, I'll create my own Serializable ArrayMap, however I'm unsure as to how to go about it.
All I know is that I implement three methods, readObject, writeObject, and readObjectNoData, all which have a Stream as an argument. I'm assuming I have to go through each item in the ArrayMap, then write it to the output stream and read from the input stream to recreate the ArrayMap. What I want to know is... how I should go about doing so.
I'm sorry if there is a duplicate question, but I can't really find any at all. So I'll start off with an example to fend off any "YAGNI" (You Aren't Gonna Need It). For one of my projects, I maintained a nested ArrayMap of objects, with said objects being in the thousands, with nested key-values to reduce collision greatly. I can't go too far into it, as it was for a recent school project. I wanted to be able to preserve the data structure over the life cycle of the application, including onDestroy of MainActivity, without having to parse everything all over again.
My solution ended up being to create a constant (static final) ArrayMap and access that, which worked, but it feels like I'm going against the philosophy of Android Development. Also I'm assuming that when MainActivity is destroyed the constant is also destroyed as well, yet with a saved bundle, it will be preserved, which is what I want.
I'm getting off topic... anyway, I want to create a Serializable ArrayMap, but I have a lot of questions regarding it. For one, what would be the best format to represent the objects nested inside of an ArrayMap? JSON would be my guess, although I've never actually done anything with it before. Then, how do I get the information from the objects nested inside? Do I enforce that only certain objects that implement an interface I declare may be added to the map? Then HashMap doesn't have this requirement. Do I use reflection to obtain each field and value, but then isn't that super slow?
I cannot use any third-party libraries, however I would love to do this from scratch regardless as it feels like a good way to learn more, does anyone have any tips/ideas on how to properly approach this? Thank you in advance!

Android programming style

I've been coding for my Android phone lately, and i've been wondering... is this Intent class supposed to outline a new programming style?
I've been suspecting the API design discourages MVC: Intents are the main way to interact with all user-related objects (Activities, Services, Other apps...).
Is my train of thought right? Should is stick to "contaminating" Activities with business logic?
I have been reading the android developers site and no particular coding style is encouraged though.
Your question isn't entirely clear, because you seem to be confusing coding style with program architecture.
In my mind, Android really changes nothing in terms of coding style. Your coding style from Java will still work fine, and most Android apps look very similar to other apps. In the abstract, there are some things that you might want to do in Android you don't do as much in other languages, see the Android guide for details. The basic idea is: memory is limited, don't use it if you don't have to.
As far as whole program architecture goes, yes, the Android style is highly based around the message passing (through Intent objects) style. The way you react to GUI events within an Activity is still largely the same: you use event handlers to react to events like button presses, etc... But the platform is strongly centered around designing apps using different components (Activities, Services, BroadcastReceivers, etc...) and Intents to communicate between them. While Intents provide a flexible way of exchanging data between components, you still shouldn't be passing massive amounts of data within Intents, instead you should put those kinds of things in a ContentProvider or something similar.
I took a lot of the following ideas I took from this OReilly book. This is just whats worked best for me.
As far as architecture goes, its helped me to think of Android's UI as a Page Controller pattern - I found it to be similar to .Net Web Forms actually. So yes, it does fit with MVC (at least the Page Controller flavor of it). An Activity is your controller, you typically store your view in XML, and you can build out your Model however you like.
You see a lot of web-ish ideas in Android. Intents are a lot like HTTP, or more generally REST. Intents have a 'noun' that says what they are concerned with (can be explicit class declaration ie: go to a specific Activity, or can be more implicit using Intent Filters), the Action is a lot like an HTTP verb (Get, Post, etc), a Bundle is a lot like a list of query string parameters or payload...etc.
And similar to a web page, you want an Activity to be able to take care of itself. What I mean is, you don't want to pass around some big serialized object from activity to activity, its a lot cleaner/resilient/reliable to just pass the id of the a given record to the next Activity and let that activity grab the record with that id from the db (ContentProvider, some other persistent source...). Activities are also meant to be loosely coupled, and you're supposed to be able to navigate to one from various paths, it also makes them more re-usable. Thus, allowing the callers of an Activity to simply provide a recordId is a lot easier then the Activity expecting its consumer to have provided a large serialized object.
Bottom line - no, you don't need to contaminate Activities with Business Logic, tuck that stuff away in an application layer, or a gateway or something like that. As for persistence, the ContentProvider interface is pretty well designed - I like it alot. It also continues the Android RESTful theme, accessing content via URLs and verbs (query, delete, update, insert).
Sending and receiving intends is much like sending and registering (similar to a publish-subscribe channel) for command messages (e.g. in a distributed enterprise application, and this is about architecture, not style). This pattern helps designing a loosely coupled system of interacting applications.
I cannot remember having seen a similar architecture before used for the interaction of components and applications on a single computer but it helps to design application using other applications to easily build an ecosystem of features/components.

ContentProvider vs. using AIDL/Messenger

I want to develop an application that supports plugins and that provides data to these plugins. It seems to me that the correct way to implement this plugin-archtitecture on Android would be one apk for the main app and one apk per plugin.
But as the main app and every plugin are in different apks I can't easily pass (data) objects from the one to the other, the applications run in different processes and even if they run in one process (which can be achieved) they have different classloaders and this doesn't work. Currently I see two promising approaches for getting data from my main app to my plugins:
Declaring the main app as a ContentProvider. This seems to me to be the intended approach because it does exactly what I want to achieve: providing content/data to another process.
Making my data objects Parcelable and pushing them around with AIDL or - if I do not need multithreading - with the Messenger-approach. In my opinion, this approach seems to be easier because I can use an ORM-library which cares about the Database in the background. I never used ContentProviders before but at a first look at it I thought that using a ContentProvider is a bit like building SQL-Queries by hand (please tell me if I'm wrong), and I would like to avoid that work!
Now I would like to know if I missed any pros or cons and if there are notable performance differences between these two approaches. And which solution would you prefer and why would you do so?
Thanks in advance! Any replies are appreciated!
Content provider is just way to share data (that are stored in different ways [database, files and so on]) between applications. If you want just share data between application it is the best way to do this.
However, if you want services to perform some tasks with data (for instance, sum several values provided by you) it's better to have a remote service.
In general case, application - plugin interaction is more similar to a remote service. In this case the main application exposes a remote service (an API of this application) that can be used by plugins to perform some actions.

Persistance of complex Java objects (SQLite, Serialization, JSON) and client-server app architecture

I'm working on an Android application which is fetching data from internet among other things. Actually, the project was started by someone else which is not here anymore,
and now that I have to turn it into a light client application and implement the server side (in Java), I'm wondering what would be the best tools/patterns to use to fit my needs.
Let's say I have to deal with several models (class representing a category) of objects which all inherits from one class : they have common attributes (such as name, attache thumbnail...) but specific properties too.
Because of this,you can understand that I can't afford to manage one specific table to map each single class.
However, I still want to be able to cache my objects somewhere in the Android device to populate the views of the application when working in offline mode.
Currently, the solution used by the previous developer was to store data directly into a TEXT field in the SQLIite database, as serialized objets.
This should be ok on the server side but I've read that the usual Java serializaton was very slow on the Android platform, although it is not really noticeable now because I work with around ~50 objects, I was looking for more performant alternatives for the future.
I've came across the JSON solution which can easily handle complex structures and Jackson library seems very interesting with its simplified data binding to POJO objects and its well-known performance.
But then, how should I store my Json objects ?
Is it possible to keep a json string in a TEXT field of a SQlite table ?
Or should I rather store them as .json file for each object ?
Which one is the more efficient to retrieve later lot of data?
Plus, I was thinking that JSON would be a very good exchange format between the Android client application and my server whould is in charge of processing the information from internet third-parties apis and exposing this data with webservices. (rather than trying to implement some RMI-like solution)
Is using the usual Apache HTTPClient enough on Android to communicate with the server?
For those who successfully developped client-server application (which seems very common to me) is this a good approach for Android ?
It seems to me that with mobile platforms, you can't really use the approach that you've learned for more classic J2EE app and such...
Any advice would be greatly appreciated because I'm a student and Android beginner who really want to improve her mobile development skills !
Thanks :)
That's open to discussion, so SO is probably not the best place to ask. In general, before declaring something is too slow (or fast), measure, compare and pick the one that works best for you. Yes, you can save JSON in a DB, an it will generally be faster than having separate files on the FS. But, again, benchmark and compare.
BTW, most J2EE 'approaches' (patterns) are overkill for any platform, let alone mobile.

Categories

Resources