I am new in Android, I have finished some Android app development courses and now I am trying to apply what I learned. I've chosen a news app for it. It will extract news' from 5-10 source and display them in recyclerview.
I recognized that the course materials I used is outdated. I've used AsynctaskLoader to handle internet connection issues but now in official Android documentation it says "Loaders have been deprecated as of Android P (API 28). The recommended option for dealing with loading data while handling the Activity and Fragment lifecycles is to use a combination of ViewModels and LiveData."
My question is should I convert my code to comply with ViewModels and LiveData or would Asynctask handle my task (or any other suggestion)? As I mentioned I only want to extract news data from a couple of source and display them in the app. It seems I don't need data storage feature. But, for now I have added two news source and the app seems to load news data a little bit late. Does this latency has something to do with using loaders? Would using viewmodels speed up news loading task (especially when there are lots of news source)?
If you've already written it with Loaders there's no reason to rush to change it. Deprecated doesn't mean gone. And no, Loaders don't add significant performance penalty- any perf issues would be elsewhere in your app.
Loaders are good because of its ability to handle life cycle, but it is not as efficient as LiveData and ViewModel. If you care about performance, speed and being latest, use Android Architecture Components (LiveData, ViewModel), also, you don't have to stick to the old system of doing things, you can write a simple AsyncTask and wrap it with ViewModel and LiveData. It works like a magic and better than Loaders. For information on how to wrap AsyncTask in LiveData and ViewModel, visit https://medium.com/androiddevelopers/lifecycle-aware-data-loading-with-android-architecture-components-f95484159de4
Loaders have been deprecated as of Android P (API 28). The recommended option for dealing with loading data while handling the Activity and Fragment lifecycles is to use a combination of ViewModels and LiveData. ViewModels survive configuration changes like Loaders but with less boilerplate. LiveData provides a lifecycle-aware way of loading data that you can reuse in multiple ViewModels. You can also combine LiveData using MediatorLiveData , and any observable queries, such as those from a Room database, can be used to observe changes to the data. ViewModels and LiveData are also available in situations where you do not have access to the LoaderManager, such as in a Service. Using the two in tandem provides an easy way to access the data your app needs without having to deal with the UI lifecycle.
Related
This is more of a question about designing applications, rather than fixing a specific issue.
So most Android tutorials I see use ViewModel as a layer between the data source and the views. Hence my first impression was that a ViewModel is supposed to handle data fetching and updating, but then I read about 'Use cases' which most Android samples don't even mention and I don't understand how all these parts fit together. What's the relationship between a ViewModel and a use case?
1) Clean Architecture this is approach how to design your application. This is not about specific realization like in case of ViewModel.
2) If you looked at the official Android documentation you will not find any mentions of Clean Architecture. Google not forcing this approach.
3) ViewModel this is part of MVVM design pattern. So if we looking info Clean Architecture MMVM can be part of Presentation layer (same as MVP commonly used in this layer). But you still need UseCase to make interactions between Data layer and Presentation layer.
I know that both Exposed and Anko can operate SQLite easily, could you tell me which one is more better when I develope an Android App?
Use the framework you are most comfortable with. I tried Exposed once and it was ok for what I've used it. jooq might also be a valid alternative instead.
Reading the documentation of both, Room and Anko, I would stick to either one of those.
Regarding which of those, I just found an issue asking the very same question (even though just as a second or third question):
https://github.com/Kotlin/anko/issues/484
Some other resources I found regarding Room and Anko:
Stress-free SQLite with Anko: the comment regarding Anko vs Room is also insightful:
Anko SQLite provides a nice API to manage your data persistence layer but you still have do the heavy lifting by yourself. While Room is more like a framework. Generates databases from annotated classes for you, provides observable queries and has a really nice testing support. Also works well with Android Architecture Components.
Ah... and don't get me wrong. Exposed is ok too, I am still using it ;-) But if you are familiar with both, you may also have your preferred choice already. If you don't know any, you can try both and choose the one where you grasp the documentation more quickly or you feel more comfortable sooner.
I've started using Architecture Components in my application and I'm still learning how to use it.
In my app I have an Activity showing different Fragments sequentially. In some of them I need to communicate with a background service in order to receive data from external BLE sensors. Since I need to interact with the service in more than one Fragment, I'm wondering if ViewModel is the right place where to make the binding. I've looked around but I didn't found an answer.
Are there any problems binding a service inside a ViewModel?
It is not advisable to use Android framework classes inside ViewModels.
Here is the link on Google Developers blog post with the detailed explanation: ViewModels and LiveData: Patterns + AntiPatterns
Ideally, ViewModels shouldn’t know anything about Android. This
improves testability, leak safety and modularity. A general rule of
thumb is to make sure there are no android.* imports in your
ViewModels (with exceptions like android.arch.*). The same applies to
presenters.
Don’t let ViewModels (and Presenters) know about Android framework
classes
I am looking into MVP architecture Implementation in android.
I found too many ways(mention end of the question) to implement it in the android studio, but Still, I am confused.
Can someone help me to find the right answer of below questions.
What would be directory structure of Application in MVP?
Activity should be a Presenter or View?
Way-1
Way-2
What would be directory structure of Application in MVP?
There is no predefined structure for that. What makes your code readable or what structure you are following, you can use same for MVP also.
Activity should be a Presenter or View?
View is the UI layer which displays the data and notifies the Presenter about user actions. So Activity will always be a view.
If you are looking for a good example of MVP implementation, there is one GitHub Repo for MVP developed by Android itself. Which you should look into.
Where
todo‑mvp
Demonstrates a basic Model‑View‑Presenter (MVP) architecture and provides a foundation on which the other samples are built. This sample also acts as a reference point for comparing and contrasting the other samples in this project.
todo‑mvp‑clean
Uses concepts from Clean Architecture.
todo‑mvp‑dagger
Uses Dagger 2 to add support for dependency injection.
todo‑mvp‑rxjava
Uses RxJava 2 to implement concurrency, and abstract the data layer.
todo‑mvvm‑databinding
Based on the todo-databinding sample, this version incorporates the Model‑View‑ViewModel pattern.
todo‑mvvm‑live
Uses ViewModels and LiveData from Architecture Components and the Data Binding library with an MVVM architecture.
Though there are lot of implementations for an MVP architecture, all of them share a basic idea (or they should at least), which is separating business logic from your views (activities, fragments, dialogs). Why is that? Well, for two reasons mainly:
separation of concerns
Testability: your business logic is able to be tested if there is no android components involved.
About your questions:
What would be directory structure of Application in MVP?
There is no rule about that except that your MVP components should be identified. Here you have an article where I started with a package structure but then I found other more convenient.
Activity should be a Presenter or View?
Your activity (or fragment or whatever components in charge of showing view components) should be the one that implements your view.
My advice is that you should check multiples examples and see their advantages and disadvantages of each one, and try to define your own architecture from those which you will feel more comfortable with.
You can use either Activity or Fragment for View layer. This is because showing UI elements in android needs Context.
For the Presenter layer, you must make sure not to pass the Context to the Presenter via constructor or setter. If you needed Context in your Presenter for tasks other than showing the UI, such as writing to SharedPreferences, you can get it from your View (which is either Activity or Fragment). In this way, if the View gets destroyed or becomes null, there would no standalone null Context in the Presenter to cause leak issues.
If you want to know more about the MVP structure, I have written a very handy MVP library for android and explained its use in a sample app here.
MVP android sample example application
MVP Android Example used to explain how to use this pattern in our Android apps.
The Problem: Really large and convoluted Activity classes. Hard to read/understand and modify. Hard to test.
The Possible Solution: Model-View-Presenter (perhaps with dependency injection).
And Mock Test Objects!
I'm planning on implementing Model-View-Presenter in my Android application.
This is basically a variant of the Model-View-Controller. In essence, make the Activity
a glorified layout manager and defer any business logic to the Presenter. Another way of looking at the Presenter is that its like an Helper class instantiated within an Activity to do the heavy lifting with the activity providing a interface/callback that the Presenter can use.
I would like to get some community thoughts on this. For example:
What interfaces are implied by this?
What responsibilities would the Model and View have vs. the Presenter.
For Presenter I suppose the Activity would implement the interfaces needed by the Presenter?
What kinds of things should go into the Presenter vs. Activity?
Would a presenter be one-to-one with an Activity? What about an Activity with multiple fragments displaying different widgets each with its own adapter? Do we now need multiple presenters or still just one?
What about Presenter vs. Adapter?
How should a presenter relate to say an Activity with a ListView and a ListViewAdapter?
What goes into the Presenter vs. Adapter?
Should the Presenter pick the Adapter to use? Or should the Activity make this decision?
Should the Presenter process Model Data or the Adapter? Is there a conflict between adapters and presenters? Are adapters presenters? or something less/more. Usually Adapters are just for widgets like ListViews within an Activity. They don't make the calls that get the data itself I think.
So in model-view-presenter the key thing is really to decides what goes in the presenter vs. other classes and what the communication should be between the presenter and activities, adapters and views/including fragments.
Is Model-View-Presenter just a really bad idea for Android? Or does it fit well with the Android Framework?
Keep in mind there are numerous examples outside Android of very mature SDK's that still needed a micro-architecture like MVP. In fact examples abound: eg. Flex was very mature SDK for Flash and yet it still needed MVP and MVC frameworks for almost any major app.
EJB needed Spring to simplify and organize it. MFC/Struts etc and the list goes on and on. Why should Android be any different? Why should we assume the SDK has everything needed in the case of Android without a design pattern like MVP?
Nice to know before I spend hundreds of hours on this, please feel free to comment/answer on any part of this question.
Android punishes poor MV(P|C) design more than any platform I've ever encountered. Forget the clumsy methods it provides for passing state up and down the activity stack. Get as much state and logic out of your activities as possible. Move it into Services, ContentProviders, and SharedPreferences as appropriate. Try to make your activities pure view. IMO, Services have never been given enough attention in Android tutorials. Even the O'Reilly Programming Android book only gives them a quarter page!
Be wary of extending Application. If you ever start a Service in its own process (e.g., to allow it to be shut down gracefully when an Activity crashes) then the Service will have its own copy of your Application.
Just to provide a reference for others who may be interested. I was thinking the same thing some years before. When we apply MVC/MVVM/Presentation Model to android app, what we really want is to have a clear structured project and more importantly easier for unit tests. At the moment, without an third party framework, you usually have lots of code(like addXXListener(), findViewById()...), which does not add any business value. What's more, you have to run android unit tests instead of normal JUnit tests, which take ages to run and make unit tests somewhat impractical. For these reasons, some years ago we started an open source project RoboBinding - A data-binding Presentation Model framework for the Android platform. RoboBinding helps you write UI code that is easier to read, test and maintain. RoboBinding removes the need of unneccessary code like addXXListener or so, and shifts UI logic to Presentation Model, which is a pojo and can be tested via normal JUnit tests. RoboBinding itself comes with more than 300 JUnit tests to ensure its quality. Other alternatives: Android-Binding, Bindroid and MvvmCross.