--

Showing posts with label Fragment. Show all posts
Showing posts with label Fragment. Show all posts

Wednesday, 13 June 2018

Kotlin - Chapter 5 - Model View Presenter (MVP) pattern

The Model View Presenter pattern is an architectural pattern based on the Model View Controller (MVC) pattern that increases the separation of concerns and facilitates unit testing.
It creates three layers, Model, View, and Presenter, each with a well defined responsibility. The MVP pattern separates the data model, from a view through a presenter.

The Model
Accommodating models (POJO class), data from various sources (database, server results, cache, Android file system, etc.).

The View
View is responsible for visual display of applications, along with data input by users. This part should NOT under any circumstances process the data. Its function is only to detect the input (e.g. touch or swipe) and visualization.

The Presenter
Presenter is responsible for passing of data between two layers, and thus the analysis and interaction. Such division allows substitution of code parts, proper testing and connects layers as interfaces.

Android MVP Guidelines
  1. Activity, Fragment and a CustomView act as the View part of the application.
  2. The Presenter is responsible for listening to user interactions (on the View) and model updates (database, APIs) as well as updating the Model and the View.
  3. Generally, a View and Presenter are in a one to one relationship. One Presenter class manages one View at a time.
  4. Interfaces need to be defined and implemented to communicate between View-Presenter and Presenter-Model.
  5. The Presenter is responsible for handling all the background tasks. Android SDK classes must be avoided in the presenter classes.
  6. The View and Model classes can’t have a reference of one another.
Having covered the theory of MVP architecture, let’s build an android MVP app now. I have developed a very simple application to demonstrate MVP. When user click ‘Tap me’ button, I am showing “Hello, Kotlinzers!!!”  popup message,

We have to create 3 packages such as model, presenter, view.

When to follow MVP design pattern ?
MVP makes it easier to test your presenter logic and to replace dependencies. But using MVP also comes with a cost, it makes your application code longer. Also as the standard Android templates at the moment do not use this approach, not every Android developer will find this code structure easy to understand.
Model Layer
The Model layer is responsible for handling the business logic. It holds an popup message shown to the user, and a reference to the Presenter.

      We have to create IBaseView.kt & IBasePresenter.kt interfaces to implement to communicate between View-Presenter and Presenter-Model.

interface IBasePresenter {
fun clickMe()
}


interface IBaseView {
fun clickSuccess(text: String)
}

Let us implement IBaseView interface in Activity,

        Because Android doesn't permit the instantiation of an Activity, the View layer will be instantiated for us. We are responsible for instantiating the Presenter and Model layers. Unfortunately, instantiating those layers outside the Activity can be problematic.
       It is recommended to use a form of dependency injection to accomplish this. Since our goal is to concentrate on the MVP implementation, we will take an easier approach. This isn't the best approach available, but it is the easiest to understand.
I have shared this source code on GitHub

Happy Coding!!!

Thursday, 24 May 2018

Kotlin - Chapter 4 - Room DataBase framework

Saving data in local DB using Room

Room persistence library introduced at Google I/O 2017 basically is not a database it just acts as middle man between SQLite and Application layer. By caching required pieces of data from web services.
If the device cannot access the network, the user can still access that content while they are offline. Any user-initiated content changes are then synced to the server after the device is back online.
Room provides enhanced security, easy access, easy to setup and quick to get started with new database. All the DML (Data Manipulation Language) commands are now annotated except SELECT command which works with @Query.

Components of Room


We have 3 components they are
Entity : a model class annotated with @Entity where all the variable will become column name for the table and name of the model class becomes name of the table.
Database: This is an abstract class where you define all the entities that means all the tables that you want to create for that database.
Dao (Data Access Objects): This is an interface which acts is an intermediary between the user and the database. All the operation to be performed on a table has to be defined here.
Apply the kotlin-kapt plugin in the app.gradle file,
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
Add the kapt dependency in the app.gradle file,
dependencies {
   implementation fileTree(include: ['*.jar'], dir: 'libs')
   implementation "android.arch.persistence.room:runtime:$room_version"
   annotationProcessor "android.arch.persistence.room:compiler:$room_version"
   kapt "android.arch.persistence.room:compiler:$room_version"
...
}
       First of all let’s create our model class where all it’s variable name will become the column name and name of model class will become the table name.

      Now let’s create our Dao interface which contains the list of operation that we would like to perform on table.
Finally let’s create our database with version number.
@Database(entities = arrayOf(User::class), version = 1)
abstract class UserDatabase : RoomDatabase() {
abstract fun userDAOAccess(): IUserDao
}
We can insert test user to Room DB by calling insert() function,

       One great feature that Room supports is LiveData that means you can observe the changes and as soon as any data gets changed in the database you get the response. One more advantage is that LiveData observable are lifecycle aware component which gives response only when your activity or fragment is either in onStart or onResume state.
Now save and run the App. You can download the full source code for this project on GitHub
Happy coding !!!

Monday, 30 April 2018

Kotlin - Chapter 3 - Showcasing Viewpager using Kotlin


ViewPager in Android allows the user to flip left and right through pages of data. Screen slides are transitions between one entire screen to another and are common with UIs like setup wizards or slideshows.
This post shows you how to do screen slides with a ViewPager provided by the support library in Kotlin. ViewPagers can animate screen slides automatically.
You’ll divide the ViewPager implementation into three parts:
  1. Adding the ViewPager
  2. Creating an Adapter for the ViewPager
  3. Wiring up the ViewPager and the Adapter
We have to add android.support.design.widget.TabLayout & android.support.v4.view.ViewPager in layout file same as Java.


ViewPager is only available through the Android Support Library. The Android Support Library is actually a set of libraries that provide backward compatible implementations of widgets and other standard Android functionality.
These libraries provide a common API that often allow the use of newer Android SDK features on devices that only support lower API levels. You should familiarize yourself with the Support Library and Support Library Packages.
We need to create our PageAdapter. This is a class that inherits from the FragmentPageAdapater class. In creating this class, we have two goals in mind:
  1. Make sure the Adapter has our fragment list
  2. Make sure it gives the Activity the correct fragment
By extending FragmentPagerAdapter, we can add multiple fragments to the ViewPager. We need to implement setupViewPager method in the ViewPagerActivity.

supportFragmentManager is equivalent to the getSupportFragmentManager() method you would use in Java and viewPager.adapter = pagerAdapter is the same as viewPager.setAdapter(pagerAdapter).
Note : The FragmentPagerAdapter is the more general PageAdapter to use. This version does not destroy Fragments it has as long as the user can potentially go back to that Fragment. The idea is that this PageAdapter is used for mainly "static" or unchanging Fragments. If you have Fragments that are more dynamic and change frequently, you may want to look into the FragmentStatePagerAdapter. This Adapter is a bit more friendly to dynamic Fragments and doesn't consume nearly as much memory as the FragmentPagerAdapter.
The output must be,

FragmentPagerAdapter or FragmentStatePagerAdapter?
There are two types of standard PagerAdapters that manage the lifecycle of each fragment: FragmentPagerAdapter and FragmentStatePagerAdapter. Both of them work well with fragments, but they are better suited for different scenarios:
  1. The FragmentPagerAdapter stores the fragments in memory as long as the user can navigate between them. When a fragment is not visible, the PagerAdapter will detach it, but not destroy it, so the fragment instance remains alive in the FragmentManager. It will release it from memory only when the Activity shuts down. This can make the transition between pages fast and smooth, but it could cause memory issues in your app if you need many fragments.
  2. The FragmentStatePagerAdapter makes sure to destroy all the fragments the user does not see and only keep their saved states in the FragmentManager, hence the name. When the user navigates back to a fragment, it will restore it using the saved state. This PagerAdapter requires much less memory, but the process of switching between pages can be slower.

Now save and run the App. You can download the full source code for this project on GitHub

Happy Coding !!!