How to use DateTime datatype in SQLite Using Room

One of the most interesting and confusing data types that SQLite not supports is Date and Time. I see more questions in online public discussion forums about this type than any other. In this article, I shed light on some very confusing issues regarding select query using Date.

Date and Time Datatype in SQLite


SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values:

  • TEXT as ISO8601 strings (“YYYY-MM-DD HH:MM:SS.SSS”).
  • REAL as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 B.C. according to the proleptic Gregorian calendar.
  • INTEGER as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC.

Applications can chose to store dates and times in any of these formats and freely convert between formats using the built-in date and time functions.

Using type converters


Sometimes, your app needs to use a custom data type, like Datetime whose value you would like to store in a single database column. To add this kind of support for custom types, you provide a TypeConverter, which converts a custom class to and from a known type that Room can persist.

For example, if we want to persist instances of Date, we can write the following TypeConverter to store the equivalent Text in the database:

The preceding example defines 2 functions, one that converts a Date object to a String object and another that performs the inverse conversion, from String to Date. Since Room already knows how to persist String objects, it can use this converter to persist values of type Date.

Next, you add the @TypeConverters annotation to the Field of class class so that Room can use the converter that you’ve defined for each Row in entity.

Note:You can also limit the @TypeConverters to different scopes, including individual entities, DAOs, and DAO methods.

1.SQLite Query to select data between two date


I have a start_date and end_date.I want to get the list of dates in between these two dates. Put those two dates between single quotes like..

2.SQLite Query to compare date


3.SQLite Query to group by Year


4.SQLite Select data for a specific year


5.SQLite Query to get Last month Data


6.SQLite Query to Order by Date


7.SQLite Query to calculate age from birth date


 

Download this project from GitHub.

 

Related Post

Room Persistence Library

 

Cloud Firestore Database for Web Application

Cloud Firestore is hot new document database in the cloud for mobile and web app for saving our data to the cloud.I want to create a little web app where we can store an Inspirational quote.My web app here consists of a text field, where I can enter my inspirational quote.We’ve got a save button, where we’re going to save whatever inspiring message our user has entered to the cloud.Later on, we’ll load whatever data our user has saved to the cloud and display it at H1 tag, so we can see the latest inspirational quote that we’ve entered.

If you want to follow along, go ahead and create your own version of this app.It really is nothing more than these UI elements here.Just make sure you have some InputText for the text fields and the label and create a button.

Getting Started with Cloud Firestore on Web


Let’s take a closer look at what I’ve got set up.So here’s index.html page, where I’ve got all my elements created.I’m loading the Firebase library.

Then, over here is my app.js file, where I’m configuring my Firebase project with the values that I got from the Firebase Console.

I’ve already created IDs for my header, my text field, and my button.So first things  I’m going to jump into my app.js file and create a few variables to hold references to these elements.I’ll do that just by calling querySelector.

Next up, I’m going to create a click event listener for the save button.Now I’ll grab the text that I want to save from my inputTextField.value and let’s log it to confirm.Let’s log it to confirm we have some actual data.

Initialize Cloud Firestore


Initialize Cloud Firestore through Firebase.

Now, I just need to save it to the cloud and to do that, I need to specify in which document I want to put this data.We do that through something known as a document reference.

I’ll be using the same reference a few times throughout this project.So I’m actually going to define it top of the script.
Firestore Database Pathyou’re always going to be alternating between collections and documents.

Now, I’ve specified my document, let’s go back to my event listener, where I’m going to call set on this document reference. Now, this will take in a JavaScript object to represent the data that we want to save for this document inspirationalQuote as textToSave that’s all I really need.This will replace my current document if it exists, and it will create it if it doesn’t.It also conveniently creates the samples collection too.So I don’t need to worry about whether or not that exists.

Now, the set function, as with most Firestore functions, returns a promise, which means it’s pretty easy to note when this call is complete.so I’ll attach a then callback at the end here, and print out a little success message, and come to think of it, I’ll add a catch here to print out any errors.

Error: Missing or insufficient permissions.

Cloud Firestore implementation contains a set of security rules that determine whether or not a certain action is permitted.The proper solution would be to add some sign-in using Firebase Auth and then create some proper, well thought out security rules, base on what information. I’m willing to share to each individual user.So I’m going to do a bit of a hack here and make anything in my samples collection open to the public.

Cloud Firestore Security Rules

So let’s head on over to the Firebase Console, make sure you’ve got your project selected, and I’m in the database section and then here, I’ll make sure cloud Firestore is selected for my list of database options.And then, I will click on the rule tab.Next, I’m going to add this here to allow reading and writing that’s part of my samples collection.

Time to load up our page and give this a try.

Cloud Firestore For web

I can verify this by going back to the Firebase console.We’ll select the Data tab to view our data.We’ll select our samples collection and sure enough, looks like we’ve saved our thought.

Get Data with Cloud Firestore


It’s great that we can see this data in the Firebase Console, we need to show this important information to our users too.So next up, let’s learn how to grab this data from the cloud and put it into our H1 tag.

Now, like the Realtime Database, Cloud FIrestore lets me listen to changes in the database and update my app in real-time.However, I know that for some of you out there, the idea of creating a real-time listener for all your data is weird and strange.Sometimes, you just want a basic fetch call to get your data, right? So I’m going to show you how to do that first and then, we can talk about getting fancy with our real-time listeners.

Now, getting this function to work is actually quite easy.I’m going to take that same document reference we created earlier and, instead of calling set on it, I’m just going to call get instead.This returns a promise.So I can attach a then callback to it, which will run when this get call is complete.Note that, this takes in a documented snapshot that I’m just calling doc here.A document snapshot is basically an object that represents your document. You can find out its ID, read some metadata about it, make sure the underlying document it represents really exists, and more importantly, grab the data that it contains by calling data on it.So we’ll see if this snapshot exists and if it does, we will call data to extract the contents of that document as an object.Then, I can set the text of our big output header to my data.inspirationalQuote.And as long as we’re here, let’s add a catch at the end to catch any error that might come up.

So let’s run this.I can still save our latest quotes to the world. Now, I’ll click the Load button to load it and there it is on our page.
Cloud Firestore Web Get Data

Get Realtime Updates with Cloud Firestore


So this is great.We’ve got our data successfully saved and loaded from cloud Firestore.But what if you are interested in getting your data in real time? What if this explicit fetching seems quaint and old-fashioned to you? Well, let’s show you how to get your data in real-time as well.

Basically, the process is going to work nearly the same.Let’s create a function called getRealtimeUpdates and in there,I’m going to bring up my document reference.But then instead of calling get, I’m going to use the onSnapshot.This will fire the first time I call it.But then, it will also fire any time thereafter when my data changes.Now, this call takes in a callback function, which accepts the document snapshot as an argument, essentially just like my get call.So in fact, I’m just to copy the exact same code for my get call into here to update my label.Well, that’s it.We’ll call getRealtimeUpdates at the bottom of our script.That should be all we need.Here, let’s reload the page.

Now you can see that my text automatically gets updated with current save Quote the value that was in the cloud previously.I hit save and you can see that my label gets updated automatically without my having to even touch that load button, that was fast.In fact, maybe too fast, right? It looks like my label got updated before that data was even saved.How’d that happen?

Cloud Firestore for web real-time update

Well, what’s happening is that cloud Firestore is making my app run as speedy as possible, by notifying me of changes as if they had happened on the server.But in the meantime, It’s still going ahead and updating that data remotely in the background.

Download this project from GitHub

 

Related Post

Firestore Document Database Data Model.

 

ConstraintLayout 1.1.0: Circular Positioning

Android just published ConstraintLayout 1.1.0 beta 3 on the google maven repository.One of the more interesting additions in this release is Circular Positioning. Circular positioning allows you to constrain a widget center relative to another widget center, at an angle and a distance. This allows you to position a widget on a circle.

ConstraintLayout Circular constraints

Add ConstraintLayout to your project


To use ConstraintLayout in your project, proceed as follows:

1.Ensure you have the maven.google.com repository declared in your project-level build.gradle file:

2.Add the library as a dependency in the same build.gradle file:

Example Circular positioning


The following attributes can be used:

  • layout_constraintCircle : references another widget id.
  • layout_constraintCircleRadius: the distance to the other widget center
  • layout_constraintCircleAngle : which angle the widget should be at (in degrees, from 0 to 360).

 

Related Post

New features in Constraint Layout 1.1.0

 

Firestore Security With Firebase Authentication

Cloud Firestore Security Rules are used to determine who has read and write access to collections and documents stored in Cloud Firestore, as well as how documents are structured and what fields and values they contain.

In this tutorial, We will learn how to secure your data using Firebase Authentication and Cloud Firestore Security Rules to handle serverless authentication, authorization, and data validation.

To set up and deploy your first set of rules, open the Rules tab in the Cloud Firestore section of the Firebase console.

Cloud Firestore populates a default rule, denying read and write access to everyone on all data:

Working with Security Rule


Cloud Firestore stores its data in a hierarchy of collections, documents, and subcollections, and you’ll often be working to secure data that is several layers deep in the hierarchy. Therefore it’s important to understand how to best work with this hierarchical data.

All documents in Cloud Firestore are stored in a path that begins with /databases/database name/documents — this path is generally not visible to clients working with Cloud Firestore. A client might be writing data to the employees/stanley document, but from the perspective of the Cloud Firestore Security Rules, this write is occurring at databases/database name/documents/employees/stanley.

Match Path


Rules match paths representing a document or collection in Cloud Firestore. Rules may match one or more paths and more than one rule can match the document name in a given request.

The basic type of rule is the allow rule, which allows read and write operations if an optionally specified condition is met.

In most cases, you’ll want to write rules that apply to any document within a collection, not just a specific one. In these situations, you can use wildcards to specify any element within a path. A wildcard is created by adding curly brackets around a string.

Apply rules to multiple documents or collections with wildcards. Wildcards represent the document or collection ID in the match path as a string between curly brackets. Add =** to the end of your wildcard string to apply the wildcard to all documents and subcollections in the path.

The request variable


The request variable is a map that contains information about the request that’s coming in from the client. You can view the reference documentation for a full list of fields, but two fields you’ll frequently be working with are the auth field, which contains information from Firebase Authentication about the currently signed-in user, and the resource field, which contains information about the document being submitted.

Common use cases for the request object include:

  • Confirming that request.auth is not null to ensure that a user is signed in
  • Using the value of request.auth.uid to get the user’s ID, as verified by Firebase Authentication
  • Using request.resource.data. to ensure the value being submitted for a document write meets a particular format. This is most common way to perform data validation within your database.

For example

Resource  vs Request.resource variable


The resource variable is similar to the request.resource variable, but it refers to the document that already exists in the database. In the case of a read operation, this is the document that is about to be read, while in a write operation, this is the old document that is about to be updated or altered.

Both the resource and request.resource objects are maps. Each contains a __name__ property indicating the document name, and a data property where all user-defined properties are declared. By accessing keys within the data property of these maps, you can get the values of the various fields belonging to the document being referenced. For example, resource.data.kesselRun is mapped to the value of the kesselRun field within the document represented by the resource variable.

Examples using the resource object.

Get Document From Database


Using the resource variable will let you evaluate the current document that is about to be accessed, but sometimes you will want to evaluate other documents in other parts of the database.
You can do so by calling the get() function with the document path in the database. This will retrieve the current document, which will allow you to access custom fields through the data property, just like the resource object.
One very common use of this function is to evaluate an access control list and determine if the userID of the current user is part of that list.
The exists() function can also be used to determine if a document already exists.

When entering a path into the exists or get function, you do not include quotes. If you want to include a variable in the path name, you should enclose the variable in parenthesis and preface it with a dollar sign.

For example:

Add Firestore Security Rules with Android Example


In previous tutorial we build a ‘MyThought’ application using Firestore which use for saving thought in Firestore database.In this tutorial we use same project to add firebase security rule.

Add Firebase Authentication


In the Authentication tab of the Firebase console go to the Sign-in Method page and enable ‘Google’
Firebase Enable Login With Google

Add Dependency


Add following dependency in your app.gradle file.

Add FirebaseUI


FirebaseUI has separate modules for using Firebase Realtime Database, Cloud Firestore, Firebase Auth, and Cloud Storage. To get started, see the individual instructions for each module.

Security Rules


Add the following security rules to your project in the: rules tab:

  • Rule 1: Only authorized users can create, read them.
  • Rule 2: Only the user who Creates the Thought can delete it. Thought can never be updated.

 

Download this project from GitHub

 

Related Post

Firestore Document Database Data Model.
Firebase Firestore Database for Android Application.

 

Firestore Document Database Data Model

We’ve all done things in relational databases for many many years and we’ve become really good at doing that.When we come across the document databases we have to retrain our brain. We have to think slightly differently when we do this otherwise we may run into some challenges.

If you think in the world of relational data you always had a model first. You thought about your tables and thought about what went in and you built your schema.So just because we’re in a document database that doesn’t mean we don’t model .we’re still modeling as just as in a relational database. It’s a little bit different where the relational data engine typically enforcing your schema or in a document database engine typically it’s the developer that’s enforcing that schema.So you build your models it’s usually built from some use case that you’re working on and driven from your code on down to the database.

Set the context how fundamentally different the approaches are. I’m going to find a scenario quickly and then to two extreme scenarios one on either end of the spectrum but it should give a good idea of the difference between the two approaches.

Let’s say I’m building an application that deals with Motor Vehicles. I want to display a motor vehicle on the screen.I may use some kind of ORM or some kind of mapping tool or some kind of middleware that takes my app and changes the format and then store it in the database separately.In a relational database, you may actually take the motor vehicle and break it up into component parts and store each one of those component parts in their own kind of table.I may store all wheels together and all engine blocks together and you get the idea very extreme.You probably wouldn’t model a database quite as extreme as the picture but you know you get the idea and then when you want to display the vehicle again on the page you write a bunch of code either in the database or in this middle tier or in your application to take all of these parts reassemble it back to a motor vehicle and then present the motor vehicle on the page.

Document vs Relational database

The other side of the spectrum in a document database is, you have a motor vehicle and you send that over the wire as it is and you persist that whole motor vehicle as a motor vehicle object in the database and when you want to display that motor vehicle on the page you do a query for the motor vehicle you bring it down to the page over the wire and you display it on the page.Those are the two different kinds of extremes.

If we take a look at a more realistic data modelling example a person and a person has contact details a contact detail has a type and we split these up into separate tables, we use foreign keys to kind of you know to break this up and reassemble the object and that ‘s what it would look like in a relational world.

Relational database

A document world we take a document called the person and we have attributes and on that, we may actually go and embed in and address a contact detail or multiple contact details and this is what the same thing would look like in a JSON document.

Document Database

Why we need  Document Database?


The document database is expressive, efficient, and flexible. Create shallow queries to retrieve data at the document level without needing to retrieve the entire collection or any nested subcollections.

Firestore Document Database


Cloud Firestore is a flexible, scalable database for APP.It keeps your data in sync across client apps through realtime listeners and offers offline support for mobile and web so you can build responsive apps that work regardless of network latency or Internet connectivity. Cloud Firestore also offers seamless integration with other Firebase and Google Cloud Platform products, including Cloud Functions.

How does it work?


Cloud Firestore is a  NoSQL database that your apps can access directly via native SDKs.

Firestore Document Database Structure

Following Cloud Firestore’s NoSQL data model, you store data in documents that contain fields mapping to values. These documents are stored in collections, which are containers for your documents that you can use to organize your data and build queries. Documents support many different data types, from simple strings and numbers, to complex, nested objects. You can also create subcollections within documents and build hierarchical data structures that scale as your database grows.

Add, sorting, filtering, and limits to your queries or cursors to paginate your results. To keep data in your apps current, without retrieving your entire database each time an update happens, add realtime listeners. Adding realtime listeners to your app notifies you with a data snapshot whenever the data your client apps are listening to changes, retrieving only the new changes.

Firestore Data Model


Firestore is a document database that means it kind of stores your data in a big tree like structure kind of like the original real-time database but everything is placed into documents and collections.

Document Database Database

Documents


You can think of a document is something kind of like a map it’s got key-value pairs which is the Firestone folks like to refer to as fields and the values of these things can be any number of things from strings to numbers to binary values to little small maps that are kind of JSON looking objects.

Firestore Document

Collections


The collection is basically well collections of documents.

Firestore Collection

There are a few rules around the use of this thing.

Rule 1: Collections can only contain documents nothing else no collections of strings or binary or anything else.

Rule 2: Documents can’t contain other documents but they can point to sub collections so it’s very common to see a collection containing a bunch documents which then point to sub-collections that contain other documents and so on in a user workout app for instance.

Firestore Document Database Example

I might have a users collection and this collection would contain a document for each user and then each of those documents might point to a workout subcollection that in turn contains a document for each different type of workout that this user is performed and then maybe each one of these has a history sub-collection that keeps track of every time the user performed one of these workouts may be along with like some average heart rate data or some other stuff like that.

Rule 3: The root of your database can only consist of the collection now in a normal production app this is going to feel pretty natural.

Firestore Rule #3

Conclusion


If you’re coming from real-time database land this kind of deep nesting might be giving you heart palpitations but don’t worry this kind of data structure is completely normal in the cloud Firestore world where queries are shallow meaning that when you grab data from a document you’ll garb just that document not any of the documents contained in any of the sub-collections below which nice.

 

Related Post

Firebase Firestore Database for Android Application.
Cloud Firestore Database for Web Application.
Firestore Security With Firebase Authentication
 

Firebase Firestore Database for Android Application

No matter what kind of app you’re developing these days, there’s a good chance
you’ll want to store data in the cloud.Because your user wants to assess their data from more than one device.

Cloud Firestore lets you store your data in the cloud, so you can sync it across all your devices or share them with multiple users.It comes with all the conveniences you’d expect from a firebase product, like robust client libraries, full support for offline mode so your app will continue to work just fine whether you’re connected or not– even on the web– a comprehensive set of security rules to help you manage access and sleep at night and an easy-to-use data browsing tool.It also lets you structure your data in ways that make sense to you thanks to its powerful querying and fetching capabilities.

Cloud Firestore works in near real time, automatically fetching changes from your database as they happen, or you can request and fetch data manually.It’s completely up to you.

Firestore integrates with other Firebase products, including firebase Authentication for easy sign-in and Cloud Functions, which lets you run all sorts of server-side logic in response to changes in your database, all of which means you get a truly serverless development experience.That means you can spend less time on infrastructure issues and more time building your app.

Getting Started with Cloud Firestore on Android


So I’m working a little app here that lets me store a thought.

My App consists of an EditText view where I can enter my thought and then the second one here where I can enter the publisher’s name and  then I have Publish button where we’re gonna save whatever thought our user has entered into the cloud so later we’ll load whatever data our users saved to the cloud and display it with a big Listview or something

Enable Firestore in Firebase


In order access to Firestore you need to enable Firestore in Firebase Console.

Enable Firestore

Add Firebase to your Android project


Create a Firebase project in the firebase console and configure the Google services plug-in with JSON file.

Add Firebase to your Android project

 

Firestore is a Document Database


Let’s take a moment to understand how cloud Firestore generally works frankly this could be the subject of its own separate post and it probably will be one day but here is the executive summary.

Document Database Database
Firestore is a document database that means it kind of stores your data in a big tree like structure kind of like the original real-time database but everything is placed into documents and collections
Firestore Document
You can think of a document is something kind of like a map it’s got key-value pairs which is the Firestone folks like to refer to as fields and the values of these things can be any number of things from strings to numbers to binary values to little small maps that are kind of JSON looking objects.

Firestore Collection
The collection is basically well collections of documents so there are a few rules around the use of this thing.

Rule 1: Collections can only contain documents nothing else no collections of strings or binary or anything else.

Rule 2: Documents can’t contain other documents but they can point to sub collections so it’s very common to see a collection containing a bunch documents which then point to sub-collections that contain other documents and so on in a user workout app for instance.

Firestore Document Database Example

I might have a users collection and this collection would contain a document for each user and then each of those documents might point to a workout subcollection that in turn contains a document for each different type of workout that this user is performed and then maybe each one of these has a history sub-collection that keeps track of every time the user performed one of these workouts may be along with like some average heart rate data or some other stuff like that.

If you’re coming from real-time database land this kind of deep nesting might be giving you heart palpitations but don’t worry this kind of data structure is completely normal in the cloud Firestore world where queries are shallow meaning that when you grab data from a document you’ll garb just that document not any of the documents contained in any of the sub-collections below which nice.

Rule 3: The root of your database can only consist of the collection now in a normal production app this is going to feel pretty natural.
Firestore Rule #3

When you’re creating a little test app like ours and you just want to save like two string so looking at app at the top level I’m gonna starting with a collection that I’m calling “lifethought ” this will then contain one single document called “publicThought” this document will contain subcollections and this subcollection contain individual call “thought”  which is identified by unique id.

Add Firestore Dependency to your app


Let’s start building so first thing you need to make sure you have Firestore installed and so you’ll go into your app.gradle file and add Firestore to your project.

We’re good, so next in my main activity here I’m gonna head on down to my publishThought call.

Cloud Firestore also supports writing your own Java objects with custom classes. Cloud Firestore will internally convert the objects to supported data types.Each custom class must have a public constructor that takes no arguments. In addition, the class must include a public getter for each property.

Now you just need to save this to the cloud and to do that you need to specify in which document you want to put this data so you do that through an object known as a DocumentReference let’s initialized it up.

I pass along a slash-separated string as our path so in our case, the path would be “thought/lifeThought

Just remember that in your path you’re always going to be alternating between collections documents collection document and so on.Firestore Database Path

so now that I’ve specified my document. In my publishThought() method where I’m going to call set on the document reference and that will take in the data. I created above as the contents of my document this call will replace my current document if it exists and created if it doesn’t it also conveniently create the sample data collection too so I don’t need to worry about that not existing now I’m going to chain on an addOnSuccessListener like so where we can print a debug message. And then we can add an addOnFailureListener listener where we can print out any error messages.

For those of you who are all about fewer listener in your call, you could also handle this with a single OnCompleteListener like and then just check in here to see if your task is successful either way works and honestly it’s just really up to you which method you prefer.

Error on Document Writing com.google.firebase.firestore.FirebaseFirestoreException: PERMISSION_DENIED: Missing or insufficient permissions.

Just like the real-time database cloud, Firestore implementation contains a set of security rules that determine whether or not a certain action will be permitted.By default they’re set up that nobody can read or write to the database.I’m willing to share with each particular user.So I’m just going to do a bit a hack here and make my sample data documents open to the public.

Set Firestore rules

I’ll select my project go to database selection and then make sure I select cloud Firestore for my list of database options then I will click the rules tab and then I’m going to add these lines here to allows reading and writing to anything that’s part of my sample data collection now this a pretty terrible idea from a security perspective but at least I’ve contained the damage to just what’s in my sample data collection so I’ll publish that and we are done.

So I’m going to start up my app, and I am going to enter thought in the text field and I hit publish button.

Firestore Database on android

I can verify this by going back to the Firebase console we’ll select the data tab and then I can look at our data collection find our document and sure enough look likes we’ve saved our inspiring thought to the world.

Firebase Cloud Firestore Database

Get Data with Cloud Firestore


We need to show our users this inspirational thought by grabbing that data from the cloud and populating in some kind of list view with it now like the real-time database cloud Firestore lets me listen to changes in the database and update my app in real time.

So let’s create a Thought List  I’m  gonna add a Recyclerview in the middle of my screen that has a TextView where I can display the thought and publisher name.

I already have my document reference.

Perform Simple Query in Cloud Firestore


Cloud Firestore provides powerful query functionality for specifying which documents you want to retrieve from a collection. These queries can also be used with either get() or addSnapshotListener().

Get Realtime Updates with Cloud Firestore


You can listen to a document with the onSnapshot() method. An initial call using the callback you provide creates a document snapshot immediately with the current contents of the single document. Then, each time the contents change, another call updates the document snapshot.

When I publish thought now my callback is getting called twice once for the change in my local cache and then once on the server.This is because of an important feature called latency compensation.

Download this project from GitHub

 

Related Post

Firestore Document Database Data Model.
Firestore Security With Firebase Authentication

Rest API Pagination with Paging Library.

Almost every REST API your app call requires to handle pagination. When calling an REST API for some resource instead of delivering all of the results, which could be time-consuming and cumbersome to deal with, a REST API will typically make you paginate through the results.If you are trying to support pagination on a client you need to handle it gracefully.

Let’s say that there’s an API endpoint that returns a list of users. In the database of the API, there are 100,000+ users. It would be impractical to fetch all 100,000 users from the API all in one request. In fact, we would probably get an OutOfMemory exception. To avoid this, we want to paginate through our list of the user when making requests to our API.

Rest Api Pagination with Paging Library

Paging Library


The new paging library makes it easier for your app to gradually load information as needed from a REST API, without overloading the device or waiting too long for an all result.This library contains several classes to streamline the process of requesting data as you need it. These classes also work seamlessly with existing architecture components, like Room.

1.Adding Components to your Project


Architecture Components are available from Google’s Maven repository. To use them, follow these steps:

Open the build.gradle file for your project and add the line as shown below:

Add Architecture Components

In this tutorial, we are using LiveData, and ViewModel.

Open the build.gradle file for your app or module and add the artifacts that you need as dependencies:

2.Setting up Retrofit for Pagination


The code samples below for making the API calls are using Retrofit with GSON.We are working with the GitHub API and making a call to the GitHub User endpoint.

Now, let’s write our class that will generate our RetrofitService.

3.Create TiledDataSource


UseTiledDataSource class to define a data source.It uses for incremental data loading, used in list paging. You can load arbitrary pages based solely on the position information and can provide a fixed item count. TiledDataSource supports querying pages at arbitrary positions, so can provide data to PagedLists in arbitrary order.

To implement, extend TiledDataSourcesubclass.

4.Create ViewModel


In the ViewModel, we would extend from the Architecture Component ViewModel, and then we would keep a reference to that LiveData of our PagedList.

LivePagedListProvider: It is use for construct Database that return LiveData.
PagedList: A PagedList is a List which loads its data in chunks (pages) from a DataSource.All data in a PagedList is loaded from its DataSource. Creating a PagedList loads data from the DataSource immediately, and should, for this reason, be done on a background thread. The constructed PagedList may then be passed to and used on the UI thread. This is done to prevent passing a list with no loaded content to the UI thread, which should generally not be presented to the user.

5.Create Adapter


To tell the PagedListAdapter how to compute the difference between the two elements, you’ll need to implement a new class, DiffCallback.Here, you will define two things.

You will define how to compute whether the contents are the same, and how to define whether the items are the same.
Let’s look at the adapter.So our adapter would extend PagedListAdapter, and then it will connect the user, which is the information that’s being displayed, with the user ViewHolder.

We define the callback, the DIFF_CALLBACK, for our user objects and then in onBindViewHolder, all we need to do is bind the item to the ViewHolder.

6.Create RecyclerView


In the onCreate, we get the reference to our ViewModel and get the reference to the RecyclerView, and we create our adapter.

 

Download this project

 

Related Post

Architecture Components:Paging Library.

 

 

Architecture Components:Paging Library

Many Applications need to load a lot of information from the database.Database queries can take a long time to run and use a lot of memory.Android has a new paging library that can help you with all of this.

Main Components of Paging Library


The main components of the paging library are PagedListAdapter, that actually extends the RecyclerViewAdapter, PagedList, and DataSource.

Component Of Paging Library

DataSource: The DataSource is an interface for page source to provide the data gradually.But you’ll need to implement one of the two DataSource, either a Keyed DataSource or TiledDataSource, which will be used when you need to load item N based on the item N-1.

  • Use KeyedDataSource if you need to use data from item N to fetch item N+1. For example, if you’re fetching threaded comments for a discussion app, you might need to pass the ID of one comment to get the contents of the next comment.
  • Use TiledDataSource if you need to fetch pages of data from any location you choose in your data store. This class supports requesting a set of data items beginning from whatever location you select, like “Return the 20 data items beginning with location 1200”.
  • loadCount():You also need to implement another method,loadCount()This tells whether you have an infinite or finite amount of items that you need to display in your list.

If you use the Room persistence library to manage your data, it can create the DataSource class for you automatically. For example, here’s a query that returns a TiledDataSource:

PagedList: The PagedList is a component that loads the data automatically and can provide update signal, for example, to the RecyclerViewAdapter. The data is loaded automatically from a DataSource on the background thread.But then, it’s consumed on the main thread.It supports both an infinite scrolling list, but also countable lists.

You can configure several things.You can configure the initial load size, the page size, but also the prefetch distance.

PagedListAdapter:This class is an implementation of RecyclerView.Adapter that presents data from a PagedList. For example, when a new page is loaded, the PagedListAdapter signals the RecyclerView that the data has arrived; this lets the RecyclerView replace any placeholders with the actual items, performing the appropriate animation.

The PagedListAdapter also uses a background thread to compute changes from one PagedList to the next (for example, when a database change produces a new PagedList with updated data), and calls the notifyItem…()methods as needed to update the list’s contents. RecyclerView then performs the necessary changes. For example, if an item changes position between PagedList versions, the RecyclerView animates that item moving to the new location in the list.

DataFlow


Paging data flow

Let’s say that we have some data that we put on the DataSource on the background thread.The DataSource invalidates the PagedList and updates its value.Then on the main thread, the PagedList notifies its observers of the new value.So now the PagedListAdapter knows about the new value.So on the background thread, the PageListAdapter needs to compute what’s changed, whats’ the difference.Then, back on the UI thread, the View is updated in the onBinderViewHolder.So all of this happens automatically.You just insert an item in that database, and then you see it animated in and no UI code is required.

Paging Library Example

Architecture Components Paging Demo

1.Adding Components to your Project


Architecture Components are available from Google’s Maven repository. To use them, follow these steps:

Open the build.gradle file for your project and add the line as shown below:

Add Architecture Components

In this tutorial, we are using Room, LiveData, and ViewModel.

Open the build.gradle file for your app or module and add the artifacts that you need as dependencies:

2.Create DataSource


Live Paged List Provider

Create Entity

Represents a class that holds a database row. For each entity, a database table is created to hold the items. You must reference the entity class in the Database class.

Data Access Objects (DAO)

To simplify the connection between the DataSource and the RecyclerView, we can use a LivePagedListProvider.So this will expose, actually, a LiveData of a PageList of our user.So all you will need to do is provide a DataSource.But if that DataSource is true, then it will be generated for you in the DAO.You don’t need to write any invalidating handling code.You can simply bind the LiveData of a PagedList to a PagedListAdapter and get updates, invalidates, and lifecycle cleanup with a single line of binding code.

So in our user DAO, we would return a LivePagedListProvider of our user to get the users by the last name.

Create Database

The annotation defines the list of entities, and the class’s content defines the list of data access objects (DAOs) in the database. It is also the main access point for the underlying connection.

The annotated class should be an abstract class that extends RoomDatabase.

3.Create ViewModel


In the ViewModel, we would extend from the Architecture Component ViewModel, and then we would keep a reference to that LiveData of our PagedList and we will get that reference from the DAO by calling getUsers(), and then call Create using the configuration that you want.So for example, setting the page size to 50, setting the prefetch distance to 50 and so on.

In the onCreate, we get the reference to our ViewModel.We get the reference to the RecyclerView, and we create our adapter.

4.Create Adapter


To tell the PagedListAdapter how to compute the difference between the two elements, you’ll need to implement a new class, DiffCallback.Here, you will define two things.

You will define how to compute whether the contents are the same, and how to define whether the items are the same.

Let’s look at the adapter.So our adapter would extend PagedListAdapter, and then it will connect the user, which is the information that’s being displayed, with the user ViewHolder.

We define the callback, the DIFF_CALLBACK, for our user objects and then in onBindViewHolder, all we need to do is bind the item to the ViewHolder.That’s all.

Download this project from GitHub

Conclusion

Android has a lot of new concepts and components with architecture Components.But the thing is, you can them separately.So if you want, you’ll only be able to use lifecycle, LiveData, and PagedList or only ViewModel, or only Room.But you can also use them together.So start using the Architecture Components to create a more testable architecture for your application.

 

Related Post

Rest API Pagination with Paging Library.

 

Autosizing TextViews Using Support Library 26.0

Material design recommends using a dynamic type text instead of smaller type sizes or truncating large size text.Android making this much easier to implement with the introduction of TextView auto-sizing.With Android O and Support Library 26.0, TextView gains a new property auto-size text type which allows you to optimize the text size when working with dynamic content.

Autosizing TextViews

Adding support library dependency


The Support Library 26.0 provides full support to the auto sizing TextView feature on devices running Android versions prior to Android 8.0 (API level 26). The android.support.v4.widget package contains the TextViewCompat class to access features in a backward-compatible fashion.

Support Library 26 has now been moved to Google’s maven repository, first include that in your project level build.gradle.

Add the support library in your app level build.gradle.

Enable Autosizing


To enable auto-size in XML, set autoSizeTextType to uniform.This scales the text uniformly on horizontal and vertical axes, ignoring the text size attribute.When using support Library, make sure you use the app namespace.Note that you shouldn’t use wrap_content for layout width or layout height for a textView set to auto-size since it may produce unexpected results.Instead, use match_prent or a fixedsize.

Turn off auto-sizing by selecting none instead of uniform. You can also use auto-size programmatically like this.

Provide an instance of the TextView widget and one of the text types, such asTextViewCompat.AUTO_SIZE_TEXT_TYPE_NONE or TextViewCompat.AUTO_SIZE_TEXT_TYPE_UNIFORM.

Customize TextView

If you want to customize your TextView more, it has some extra attributes for you to auto-size min and max text size and step granularity.The TextView will scale uniformly in the range between the minimum and the maximum size in increments of step granularity.If you don’t set these properties, the default values will be used.

To define a range of text sizes and a dimension in XML, use the app namespace and set the following attributes:

 

To define a range of text sizes and a dimension programmatically, call the setAutoSizeTextTypeUniformWithConfiguration(int autoSizeMinTextSize, int autoSizeMaxTextSize, int autoSizeStepGranularity, int unit) method. Provide the maximum value, the minimum value, the granularity value, and any TypedValue dimension unit.

Preset Sizes

To have more control over the final size, for example, your app needs to comply with specific text size design guidelines, you can provide a list of size, and it will use the largest one that fits.

Create an array with the size in your resources and then set the auto-size present sizes attribute in the XML.

To use preset sizes to set up the auto-sizing of TextView programmatically through the support library, call theTextViewCompat.setAutoSizeTextTypeUniformWithPresetSizes(TextView textView, int[] presetSizes, int unit) method. Provide an instance of the TextView class, an array of sizes, and any TypedValue dimension unit for the size.

 

 

How to Create Instant app from Existing App

Android Instant Apps allows Android users to run your apps instantly, without installation. Users can get to your flagship Android experience from any URL—including search, social media, messaging, and other deep links—without needing to install your app first.Android Instant Apps supports the latest Android devices from Android 6.0 through Android O. Google will be rolling out to more devices soon, including expanding support to Android 5.0 (API level 21) devices shortly.

How does Instant app work?


When Google Play receives a request for a URL that matches an instant app, it sends the necessary code files to the Android device that sent the request. The device then runs the app.

How does Instant app work

Structure of the Instant App


  • Base feature module: The fundamental module of your instant app is the base feature module. All other feature modules must depend on the base feature module. The base feature module contains shared resources, such as activities, fragments, and layout files. When built into an instant app, this module builds a feature APK. When built into an installed app, the base feature module produces an AAR file.
  • Features: At a very basic level, apps have at least one feature or thing that they do: find a location on a map, send an email, or read the daily news as examples. Many apps provide multiple features.
  • Feature ModulesTo provide this on-demand downloading of features, you need to break up your app into smaller modules and refactor them into feature modules.
  • Feature APKs: Each feature APK is built from a feature module in your project and can be downloaded on demand by the user and launched as an instant app.

 

Each feature within the instant app should have at least one Activity that acts as the entry-point for that feature. An entry-point activity hosts the UI for the feature and defines the overall user flow. When users launch the feature on their device, the entry-point activity is what they see first. A feature can have more than one entry-point activity, but it only needs one.

Structure of Instant App

 

As you see in the figure, both “Feature 1” and “Feature 2” depend on the base feature module. In turn, both the instant and installed app modules depend on the feature 1 and feature 2 modules. All three feature modules are shown in figure -base feature, feature 1, and feature 2—have the com.android.feature plugin applied to their build configuration files.

Upgrade Your Existing App

Android Instant Apps functionality is an upgrade to your existing Android app, not a new, separate app. It’s the same Android APIs, the same project, and the same source code. Android Studio provides the tools you need to modularize your app so that users load only the portion of the instant app that they need when they need it.

Step 1: Develop a use case for your instant App


Focus on a core user experience that completes a specific action and optimizes a key business metric besides app installs. Then review the user experience guidelines for Android Instant Apps.

Step 2: Set up your development Environment


To develop an instant app, you need the following:

Install Instant App SDK

Build an Android Instant App, we need to install the SDK. Go to Tools >Android > SDK Manager. Click on the “SDK Tools” tab and install “Instant Apps Development SDK” by checking the box and hitting “Apply”

Install Instant App SDK

Set up your device or emulator

You can develop instant apps on the following devices and emulators:

  • Devices: Nexus 5X, Nexus 6P, Pixel, Pixel XL, Galaxy S7 running Android 6.0 or higher.
  • Emulator: Nexus 5X image running Android 6.0 (API level 23), x86, with Google APIs(You cannot use x86_64 architectures).

Step 3: Moving existing code into a feature module


In this step, we will convert the existing application module into a shareable feature module. We will then create a minimal application module that has a dependency on the newly formed feature. Note that this feature module will be included into the Instant App build targets later. 

Convert the app module into a feature module called app-base

We start with renaming the module from 'app' to 'app-base':

create base module

Change Module type

Next, we change the module type to Feature module by changing the plugin type from com.android.application to com.android.feature  and also remove applicationId   because this is no longer an application module in the app-base/build.gradle file:

Specify base feature in the project  app-base/build.gradle

Synchronize gradle files and re-build the project with Build->Rebuild Project.

Step 4: Create appapk module to build APK file


Now that we have transformed our source code into a reusable library module, we can create a minimal application module that will create the APK. From File->New Module

Create New Module

Enter application name “app apk”, leave suggested module name (topekaapk).

If your project uses Data Binding, you need to ensure that appaapk/build.gradle includes the following in the android { ... } section.

Replace compile dependencies in appaapk/build.gradle:

Switch to “Project” view and remove unused files:Instant app remove unused folder

Switch back to “Android view” and remove the application element from appaapk/src/main/AndroidManifest.xml. It should only contain this single manifest element.

Finally sync Gradle files, re-build and run the project. The application should behave exactly the same despite all of our changes.

Create Feature module

We have just moved the application’s core functionality into a shareable feature module and we are now ready to start adding in the Instant App modules.

Step 5: Creating the instant app APK


Instant Apps uses feature APKs to break up an app into smaller, feature focused modules. One way to look at Instant Apps is a collection of these feature APKs. When the user launches a URL, Instant Apps will only deliver the necessary feature APKs to provide the functionality for that URL.

The app-base module feature APK that encompasses the full functionality of our app. We will create an Instant App module that bundles our single feature APK. At the end, we are going to have our single feature instant app!

single feature instant app

The Instant App module is merely a wrapper for all the feature modules in your project. It should not contain any code or resources.

Create an Instant App module

Select File -> New -> New Module
Create Instant App

Next, we need to update the instant app gradle file to depend on the base feature module. At this point we also need to add buildToolsVersion to explicitly use 26.0.1 since there is an issue in the current Android preview which makes the default 26.0.0. Since we’ve installed 26.0.1 with the project we don’t want to fetch 26.0.0 necessarily.

instantapp/build.gradle

The instant app does not hold any code or resources.It contains only a build.gradle file.

Now do a clean rebuild: Build -> Rebuild project.

Step 6: Defining App Links


App links are required in instant apps because URLS are the only way a user can launch an instant app (instant apps are not installed).Each entry-point activity in an instant app needs to be addressable: it needs to correspond to a unique URL address. If the URL addresses for the features in an instant app share a domain, each feature needs to correspond to a different path within that domain.

In order to enable Instant App runtime to call your application, we must establish the relationship between your web site and the app. To associate links, we will use a new feature built into Android Studio called “App Links Assistant.”. Invoke this tool through the Android Studio “Tools” menu:

App Links Assistant

From the sidebar, tap on the “Open URL Mapping Editor” button:

add url intent filters

From the editor, tap the “+” button to add a new app link entry:

Create a new URL mapping with the following details:

Host: http://topeka.samples.androidinstantapps.com

Path: pathPattern/signin

Activity: activity.SigninActivity (app-base)

map url to activity

Repeat this dialog for https variation, as well as other links:

In the end, you should have 4 mappings like this:

Url to Activity mapping

Sync gradle files if required and rebuild the project.

Again, since we have not used Android Studio wizard, the run configuration for instant app is not valid, we need to define the URL before we can launch the instant app from the IDE.

Click the Run configuration dropdown and choose “Edit Configurations…”

Select instantapp under Android App.

Edit Configuration

Replace the text ‘<< ERROR – NO URL SET>>’ with https://topeka.samples.androidinstantapps.com/signin

To run your Instant App, select instantapp from the Run configuration dropdown and click Run:

Run Instant APP

 

Now, you have created and deployed an Android Instant App. You took an existing Android application and restructured it to build both a full installed APK and an Instant APK that will be loaded when the user taps on the associated URLs.

Conclusion


You may need to separate the code in multiple features for various reasons, the most obvious one is feature separation, to let users download only the relevant portions of the app.We will create another feature module and move all UI code there (activities and related fragments). It will let us create two features (

You will create another feature module and move all UI code there (activities and related fragments). It will create two features (app-base and app-ui) later.