Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I'm new to Android, but I've done quite a bit of server side Java.
I was reading about Intents, and in particular about the difference between sending extra data (classes) via Serializable vs Parcelable. There seems to be a consensus that Serializeable has bad performance, and Parcelable is to be preferred. In some places I've seen it stated that Serializeable is bad because it uses reflection.
That leads to a couple of questions for me:
Is reflection in general considered bad? Should I avoid any library that relies heavily on reflection? For example, if I need JSON deserialization (from some web service) should I not be using Jackson or Gson? Is that org.json garbage really "best practice" in Android-land?
If I really should avoid reflection (and thus Serializable), is there any alternative to the ugly, boilerplate-heavy Parcelable? The Intents are all explicit, and I'm not broadcasting them outside the app. I guess I don't understand why in-process messaging can't just pass a reference to the object inside the Intent.
RE question #2:
I guess I don't understand why in-process messaging can't just pass a reference to the object inside the Intent.
Parcelizing (or serializing) the object allows Android to re-create it when the containing activity is re-created itself. Android controls the lifecycle of activities - and can at anytime destroy your activity, even if it is active/visible (e.g screen rotation, to reclaim memory to handle an incoming phone call, ...). When Android re-creates your activity, it passes you an object called a Bundle that includes all your parcelized objects. This allows you to restore the state of your activity, but note that these are not the original objects - they have been re-constitued from their parceled representations.
is there any alternative...?
If you want to be able to properly re-create your activity, then parcelization and serialization are your choices. I would not be so fast to rule out serialization however. While in general it is less performant, in many cases, this will probably not be user-detectable. Keep in mind that Android was designed at a time when mobile devices has significantly less processing power than they do today. Thus performance optimizations like parcelability were likely more of a concern.
One alternative worth mentioning, which is probably even less performant would be to write the object to disk yourself. Then in the intent, pass a pointer to the file (or the database record). A variation on this would be to use Android SharePreferences to save the data. I only mention this because passing large amounts of data in an Intent can sometimes fail. There is no hard limit on the max object size, but many people, including me, have seen this failure.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I have two questions:
How to handle events, like user logged in etc.
Let's say I have repository and I am calling a Repo.function in my viewModel, and that ViewModel.method is called in my activity, when user presses the button. So, in some time my Repo.method completes and returns 200, and says my user is logged in. The question is, how my android view ( activity / fragment ) should now that it has to navigate? Currently I use EventBus to post and subscribe to such events.
How to handle network loading states: default/loading/completed
Currently I have a separate singleton that has ObservableFields for loaders like val isTokenLoading = ObservableField(false)
In my viewModel I hold ref to that singleton.isTokenLoading
My view binds to that viewModel's field
And in this way I handle UI changes during loading progress
What is the best way to do such things?
For your first question, I would say that the Observer pattern is the way to go (and the one people usually choose). For instance, RxJava fits perfectly in your use case, and you can even use it with LiveData nowadays. You would launch the request on your ViewModel, create an Observable from the response, perform all the operations you need, and do one of the following: subscribe to the final Observable on your view, or subscribe to a LiveData on your view, while updating it through the observable subscription on your ViewModel (I prefer the latter since it keeps the RxJava dependencies out of the view). You have tons of examples online with implementation details on this.
As for your second question, you're already using the Observer pattern (which, again, is the way most people do it), but keeping all loading fields in the same class seems to me like a code smell. It would probably be better to store them on the class that has to deal with them.
Edit: I just came across an article on AndroidPub exploring exactly what you want: https://android.jlelse.eu/android-architecture-communication-between-viewmodel-and-view-ce14805d72bf
you should use observer pattern. your repository can return a flow (in kotlin coroutine package) and you can observe this flow in you viewmodel. then you can expose this flow to a live data and observe this live data in your fragment or activity. using live data will help you to avoid memory leak.
for handling network states you can have another live data and post state of network to that. and of course observe it in view if you want.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Increasingly in our spring (or equivalent) wired world of services, the Java code I see seems more & more procedural, with not much emphasis on modelling the problem in OO.
For example, a service that has stuff to do may well inline that in the service method in the singleton service class – maybe over several hundred lines. Alternatively, local methods may be created, but because the service is stateless, these are invariably called with a stack (no pun intended) of needed args. It’s noisy.
Guess this maybe my original OO background in Smalltalk to the fore here, but modelling the problem in OO has always seemed to me to be the way to go. That is, modelling with objects which have state as well as behaviour.
An alternative approach might be to create a stateful prototype delegate invoked from the service, which is either wired or loaded with the necessary (entities, singleton DAO/services etc) In addition some other decorators might be created to wrap entities (esp collections) to provide some model list behaviour (I have a list af accounts, I have some list based behaviour – this must be a class holding the list, it must not be just the technical List class and its usage behaviour inlined in the service (but usually is))
But.
Creating some objects of this kind uses memory, and in a high throughput environment, this might result in the creation of thousands of small strategy/decorator instances.
So what is the real world impact of that? Will the extra GC screw the performance or, assuming a JVM instance around a couple of GB, can Java cope?
Has anyone delivered a Java SOA based on these principles? Are there any papers on the subject?
Thanks for reading this far.
Real-world problems usually are a mix of object-based and procedural logic, especially in the business world where transactions involve needing to manipulate a number of distinct objects simultaneously. Certainly most real code could use improvement and refactoring, especially after a few years of moving-target requirements, and better understanding and use of AspectJ could clean up a lot of the procedural boilerplate, but it doesn't make sense to force all logic into a strong OOP pattern if it doesn't match the way that a real-world instructor would describe it to a trainee.
What you're describing is basically the Command pattern, and while there are situations where it is useful (it's essentially the role of Runnable), it's usually not worth using unless there are time-based considerations (serial execution, parallelism) or the transaction itself needs to be persistent (such as for banking).
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I've been using Sonar code quality management platform for some time, and for the most cases I find it very helpful in revealing hidden design flaws of my code base.
However, there's one rule that gives me more annoyance than help and that is its check for 'cyclic package reference' violations.
I guess I fully understand where such a dependency between packages is a bad thing. For example, in a typical 3-tier presentation/service/persistence layered design, it's almost always a bad idea to let the database handling code have a reference back to UI related classes. I have no problem with calling it a 'violation'.
But let's consider other cases, i.e. like designing an IDE-like application. Say, we have a main package which contains an Application interface, which defines List<View> Application.getViews() method to reference application's views.
However, when the View interface has an Application getApplication() method to refer back to its parent application, which I believe is a quite common design, it will introduce a cyclic reference, provided each of the interfaces are separated in com.myapp.ui, and com.myapp.ui.view respectively.
Of course, you can just put the View interface into the com.myapp.ui to break the cycle. But when you have various other view related APIs in com.myapp.ui.view, many of them another abstract APIs like AbstractView, ContentView, AbstractContentView, etc. I wonder if it's more advisable to keep them in separate packages for a management purpose.
And consider the said application has many other similar cases like com.myapp.ui.action, com.myapp.ui.perspective, etc. which would really make com.myapp.ui package crowded if we are to put them all in there.
So, what approach do you suggest to handle such a situation? Are really every cyclic package references a bad thing? Or if I have to live with them, how do you configure Sonar to check only real, problematic cycles?
Every absolute -- except this one ;) -- is going to be wrong some of the time. So, is every cyclic reference bad? No. You have to use your judgement.
But if you do introduce a cyclic dependency, it's worth asking if you really need it, and why. The tl;dr is that more often than not, you may find that breaking the cycle can improve your modularity, and in particular your ability to test components separately.
To use your example, does a view really need a getApplication(), which presumably returns a relatively "heavy" object (ie, one that itself needs a database, network, etc etc)? Maybe... but maybe not. If what you really need from that getApplication is something with a few callbacks (such as when a user initiates some action), then it could be useful to create an interface in some common package for that callback. So, rather than:
com.foo.app.Application
com.foo.view.View
Application getApplication()
You'd have:
com.foo.common.Callback // maybe just a Callable, Runnable, etc?
com.foo.app.Application
provides a Callback for some action foo
com.foo.view.View
Callback getFooCallback()
The question you should be asking is: what does that give me? It could be that you have to stub out so much that it doesn't give you much -- though that may suggest you can break apart your classes some. But it could be that it actually makes it easier to test your view, because now your unit test can (1) test the view without spinning up a whole application, and (b) provide a "dummy" callback that does something like saving a string that describes the action, and then your unit test asserts that it saved the right string.
And indeed there is an open JIRA ticket to prevent considering a cycle between father/child packages as a quality flaw : http://jira.codehaus.org/browse/SONAR-3452
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
In my project I am developing at the moment, I have many configuration settings. Things such as
Alarm times
Amount of items to retrieve from the server
LocationManager integers such as minium location
These are all static final and are all in a class that corresponds to the value.
My question is, are there any problems with moving all of these values to a single static class?
My thinking is that when it comes to testing and tweeking the app, it will be easier to manage.
Building on #Snicolas's answer...
You should indeed persist your CONFIGURATION settings outside of code (file or database). BUT you should not "read" that configuration each time a value is required, that would be inefficient.
Using a class to manage configuration (ie. AppSettings) is a good idea. Making it static is one way to provide singleton-like access. In C# and ASP.NET a web app will guarantee one and only one instance of a static class and therefore multiple un-related requests from different users will share the exact same static values.
But in your case (I see the tag 'android') using Java your best bet may be a Singleton approach. I don't know how garbage collection works in Java but I'd say you should use a singleton to ensure one-and-only-one instance of your settings. The singleton Ensures an instance exists (or creates one if not) and then provides it to the caller.
This may also make it easier to support the ability to change configuration values while the app is running -- you can "watch" for setting changes on a regular basis.
I'm not a Java man but I'd be surprised (well no not really) if there wasn't already a library for handling this very problem.
I am pretty sure you are not talking about constants as you mentionned alarm times.
The problem with using only static fields inside a dedicated class is that your class can be garbage collected if the device is under memory pressure. In that case, they would simply be lost and reset when you would use them again.
So you should really consider persisting them in a file or in a database depending on the amount of data you wanna store. SharedPreferences can be usefull for a small amount of data, otherwise, consider using a database. That's a much more scalable solution and access times are better for larger data sets.
In the Rails world, it's good practice to implement a configuration model class that lazily loads and caches configuration information, which is persistently stored in serialized form in a simple two-column (key and serial data value) table or (less often) a flat file. A configuration editor is then just a View for this model.
This ought to be a good solution in Android as well.
Another idea will be to store these constants in a properties file. And load the constants when you need them. http://viralpatel.net/blogs/loading-java-properties-files/
If you find it convenient, it's a good practice.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
i'm experienced with Java and want to learn objective-c to write apps for the iPhone. What are some fundamental differences? (other than syntax)
Conceptually, the biggest difference is that Objective-C is dynamically typed and you don't call methods, you send messages. This means that the Objective-C runtime does not care what type your object is, only whether it will respond to the messages you send it. This in turn means that you could (for example) create a class with an objectForIndex: method and use it in place of an NSArray as long as the code that uses it only calls objectForIndex:
This allows you to do all sorts of funky things, like have one object pose as an object of a different class and you can add methods at run time or add collections of methods (called categories) to prebuilt classes like NSString at compile time. Most of the time you'll never bother with any of those tricks, except the categories.
On a more practical level you'll notice:
the syntax is different
Memory management is more manual. On the iPhone, you have to use retain/release (OS X has garbage collection). This is not actually as bad as it sounds. If you follow the rules, and wrap your instance variables in getters and setters you'll find yourself rarely having to write retain or release. Update: some time after I wrote this, Apple introduced automatic reference counting (ARC). ARC grew out of the observation that the clang static analyser was capable of spotting just about every single missing (or extra) retain or release. So they extended the principle by having the compiler put in the retains and releases automatically. Apart from some simple rules about strong and weak relationships (i.e. whether an object claims to own another object or not), you can more or less forget about memory management. Also, ARC is available on iOS.
All methods are public. This is a direct consequence of the message sending paradigm, but you can't define private or protected methods.
The library is much smaller. In particular, you will notice that there are only three collection classes NSArray, NSDictionary and NSSet (plus their mutable versions). The philosophy is that you program to the interface. The runtime worries about what the implementation should be.
ETA: I forgot one important thing, you'll miss from Java. Objective-C does not support name spaces. This is why you'll see OBjective-C classes with two (or more) letter prefixes and it's the feature I really wish they would add.
First, Objective-C doesn't provide a garbage collector for iPhone. On the Mac, a garbage collector is present.
But, Possibly the biggest difference for me is that there are 2 files for each class. A header file (.h) where you have to declare instance variables, properties, and methods. Then is the implementation (.m) file where you write your methods. Properties in Objective-C have to be "synthesized" with the #synthesize keyword to create the getter and setter methods.
The transition isn't too bad. Both languages follow similar rules in terms of object models and even some of the syntax. I actually made the opposite transition. I started with Objective-C for iPhone, then picked up Java to do Android development.
On an unrelated note, building your UI is much easier using Apple's tools. Interface builder is drop-dead simple. Hooking up UI objects in the nib files to their declarations in code is so easy. Instruments provides an easy way to check CPU usage, memory leaks, allocations, and so on. Plus, just in terms of features, overall polish, and ease of use, I'll take XCode and Apple's tools to Eclipse any day.
If you're "fluent" in Java, the move to Objective-C won't be too hard. Just get your [] keys ready and practice typing "release"!
The biggest difference that will affect you immediately, besides an entirely different set of libraries[1], is that Objective-C doesn't provide garbage collector. The Apple libraries provide some garbage collection related routines and objects, I believe using reference counting, but you don't have the garbage collection you're used to in Java.
Other than that, many things will be similar: single inheritance, late binding, etc. Objective C doesn't provide method overloading, but that's a somewhat trivial difference. Java and Objective-C aren't too far apart in terms of how their object model works. Obj. C has a few tricks up its sleeve, such as categories, but you don't need to worry about those at first.
See the related C# question suggested by Remus for more (and much more detailed) information (and thanks to Remus for reminding me of the library difference - I nearly forgot that important facet).
Any object declared in Objective C is a pointer of another