--

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 !!!

Tuesday 10 April 2018

Kotlin - Chapter 2 - Developing Android Apps using Kotlin

Calling REST API in Kotlin


       I have implemented REST API call using HttpURLConnection & Retrofit API. We will create a connection between Android App and server at certain period then receive the data request from Android App to server.

Rest API and JsonObject Model :

      REST APIs is often used in mobile applications, social networking Web sites, mashup tools, and automated business processes. The REST style emphasizes that interactions between clients and services is enhanced by having a limited number of operations.

Using HttpURLConnection :

A URLConnection with support for HTTP-specific features.

Uses of this class follow a pattern:

  • Obtain a new HttpURLConnection by calling URL.openConnection() and casting the result to HttpURLConnection.
  • Prepare the request. The primary property of a request is its URI. Request headers may also include metadata such as credentials, preferred content types, and session cookies.
  • Optionally upload a request body. Instances must be configured with setDoOutput(true) if they include a request body. Transmit data by writing to the stream returned by URLConnection.getOutputStream().
  • Read the response. Response headers typically include metadata such as the response body's content type and length, modified dates and session cookies. The response body may be read from the stream returned by URLConnection.getInputStream(). If the response has no body, that method returns an empty stream.
  • Disconnect. Once the response body has been read, the HttpURLConnection should be closed by calling disconnect(). Disconnecting releases the resources held by a connection so they may be closed or reused.

Response Handling :

       HttpURLConnection will follow up to five HTTP redirects. It will follow redirects from one origin server to another. This implementation doesn't follow redirects from HTTPS to HTTP or vice versa.
If the HTTP response indicates that an error occurred, URLConnection.getInputStream() will throw an IOException. Use getErrorStream() to read the error response.



var - something that will vary with time. (Mutable )

val - for a value that won’t change. (Immutable - i.e. read-only)

Calling getUsers() function in doInBackground of inner class AsyncTask.



Note :
If you have to send GET/POST requests over HTTPS protocol, then all you need is to use javax.net.ssl.HttpsURLConnection instead of java.net.HttpURLConnection. Rest all the steps will be same as above, HttpsURLConnection will take care of SSL handshake and encryption.

Using Retrofit API

     Retrofit is type-safe HTTP client for Android and Java by Square, Inc. It is an open source library which simplifies HTTP communication by turning remote APIs into declarative, type-safe interfaces. It makes it relatively easy to retrieve and upload JSON (or other structured data) via a REST based web service. It automatically serializes the JSON response using a POJO which must be defined in advanced for the JSON Structure. 

     REST Client in our case is the Retrofit library that is used on the client side (Android) to make HTTP request to REST API, in our case, The USER API and also process the response. A REST API defines a set of functions which developers can perform requests and receive responses via HTTP protocol such as GET and POST. 

     We can also simply say that a RESTful API is an application program interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data. We have to initialize Retrofit client by setting up baseUrl, addConverterFactory. 

By Query parameters can also be added to a method. creating interface for fetching list of users using gson library,

interface IUser{
@GET ("users")
fun getAllUsers() : Call<RetroUser>
}

You can use replacement blocks and query parameters to adjust the URL. A replacement block is added to the relative URL with {}. With the help of the @Path annotation on the method parameter, the value of that parameter is bound to the specific replacement block.




       A Retrofit class which generates an implementation of the UserService interface. The above sample code would be inside the Retrofit class and this is how it creates an instance of Retrofit and implements the getAllUsers() method that’s in the IUser Interface. By calling loadUsers() function in onCreate() override method.


Using simple service URL to fetch user details.
URL : https://reqres.in/api/users
The output would be,

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

Happy Coding !!!