Add selection support to RecyclerView:recyclerview-selection:28.0.0

recyclerview-selection provides item selection support for RecyclerView.It support for creating, modifying, inspecting, and monitoring changes to items in a RecyclerView list.It enables users to select items in RecyclerView list using touch or mouse input.

To add selection support to a RecyclerView instance, follow these steps:

1.Add Dependency


Add following depedency to your app’s build.gradle file.28.0.0-alpha1 is a pre-release version to support the Android P developer preview.

2.Implement ItemKeyProvider


Developers must decide on the key type used to identify selected items. There are three key types: Parcelable,String, and Long.

3.Implement ItemDetails


ItemDetails implementation provides the selection library with access to information about a specific RecyclerView item. This class is a key component in controling the behaviors of the selection library in the context of a specific activity.

4.Implement ItemDetailsLookup


ItemDetailsLookup enables the selection library to access information about RecyclerView items given a MotionEvent. It is effectively a factory for ItemDetails instances that are backed up by aRecyclerView.ViewHolder instance.

The Selection library calls getItemDetails() when it needs access to information about the area. Your implementation must negotiate ViewHolder lookup with the corresponding RecyclerView instance and the subsequent conversion of the ViewHolder instance to an ItemDetailsLookup.ItemDetails instance.

5.Reflect Selected State


When the user selects an item the library will record that in SelectionTracker then notify RecyclerView that the state of the item has changed.The item must then be updated to reflect the new selection status. Without this, the user will not see that the item has been selected.

Update the styling of the view to represent the activated status with a color state list.

item_list.xml

The selection library does not provide a default visual decoration for the selected items. You must provide this when you implement onBindViewHolder().

6.Add Contextual Actions


ActionModes used to provide alternative interaction modes and replace parts of the normal UI until finished. Action modes include text selection and contextual actions.

7.Build SelectionTracker


In order to build a SelectionTracker instance, your app must supply the same Adapter that you used to initialize RecyclerView to SelectionTracker.Builder.

Register a SelectionTracker.SelectionObserver to be notified when the selection changes. When a selection is first created, start ActionMode to represent this to the user, and provide selection specific actions.

8.Activity lifecycle events


In order to preserve state you must handling of Activity lifecycle events. your app must call the selection tracker’sonSaveInstanceState() and onRestoreInstanceState() methods from the activity’s onSaveInstanceState()and onRestoreInstanceState() methods respectively.

 

Download this Project from GitHub

 

 

Room database Migration

When upgrading your Android application you often need to change its data model. When the model is stored in SQLite database, then its schema must be updated as well.
However, in a real application, migration is essential as we would want to retain the user existing data even when they upgrade the App.

The Room persistence library allows you to write Migration classes to preserve user data in this manner. Each Migration class specifies a startVersion and endVersion. At runtime, Room runs each Migration class’s migrate() method, using the correct order to migrate the database to a later version.

A migration can handle more than 1 version e.g. if you have a faster path to choose when going version 3 to 5 without going to version 4. If Room opens a database at version 3 and latest version is >= 5, Room will use the migration object that can migrate from 3 to 5 instead of 3 to 4 and 4 to 5.

If there are not enough migrations provided to move from the current version to the latest version, Room will clear the database and recreate so even if you have no changes between 2 versions, you should still provide a Migration object to the builder.

Create New Entity Or Add New Columns 


The following code snippet shows how to define an entity:

migrate() method is already called inside a transaction and that transaction might actually be a composite transaction of all necessary Migrations.

After the migration process finishes, Room validates the schema to ensure that the migration occurred correctly. If Room finds a problem, it throws an exception that contains the mismatched information.

 

Related Post

Room Persistence Library

How to use DateTime datatype in SQLite Using Room

Room: Database Relationships

 

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

Next, you add the @TypeConverters annotation to the Field of class so that Room can use the converter that you’ve defined for each Row in the 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 dates


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

Room: Database Relationships

Room database Migrating

 

ConstraintLayout 1.1.0: Circular Positioning

Android published ConstraintLayout 1.1.0 on the google maven repository. One of the more interesting additions to 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

 

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.

Adding support library dependency


The Support Library 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.

 

 

EmojiCompat Support Library

With the EmojiCompat library(part of the Support Library 26) your app can get backward-compatible emoji support on devices with API level 19+ and get rid of ☐ (tofu).

How does EmojiCompat work?


For a given char sequence, EmojiCompat can identify the emojis, replace them with the EmojiSpan, and then render the glyphs.On versions prior to API level 19, you’ll still get the tofu characters.

EmojiCompat build on the new font mechanism to make sure you always have the latest emoji available.

Downloadable fonts configuration of emoji


The downloadable fonts configuration uses the Downloadable Fonts support library feature to download an emoji font. It also updates the necessary emoji metadata that the EmojiCompat support library needs to keep up with the latest versions of the Unicode specification.

Adding support library dependency

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.

Adding certificates

When a font provider is not preinstalled or if you are using the support library, you must declare the certificates the font provider is signed with. The system uses the certificates to verify the font provider’s identity.

Create a string array with the certificate details.

Initializing the downloadable font configuration

Before using EmojiCompat, the library needs a one-time asynchronous setup(in application class).

When a downloadable font configuration, create your FontRequest, and the FontRequestEmojiCompatConfig object.

It depends on the way you’re using it, the initialization takes at least 150 ms, even up to a few seconds. So you might want to get notified about its state.for this, use the registerInitCallback method.

Use EmojiCompat widgets in layout XMLs. If you are using AppCompat, refer to the Using EmojiCompat widgets with AppCompat section.

You can preprocess a char Sequence using the process method. You can then reuse the result instead of the initial registering in any widget that can render spanned instances.So, for example, if you’re doing your own custom drawing, you can use this to display emoji text.

 

Download this project from GitHub

Fast Scrolling in RecyclerView Using Support Library 26

InListView, you could have a fast scroller which allowed you to drag a scrollbar to easily scroll to wherever you wished using fastScrollEnabled attribute.With Support Library 26, you can also easily enable fast scrolling for RecyclerView.

Fast Scrolling RecyclerView

Add Dependency


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

Add Support Library 26 in your app level build.gradle.

Enable Fast Scrolling


If fastScrollEnabled boolean flag for RecyclerView is enabled then,fastScrollHorizontalThumbDrawable,fastScrollHorizontalTrackDrawable, fastScrollVerticalThumbDrawable, and fastScrollVerticalTrackDrawable must be set.

  • fastScrollEnabled : Setting this as true will require that must provide the following four properties.
  • fastScrollHorizontalThumbDrawable :  StateListDrawable used for drawing the thumb which will be draggable across the horizontal axis.
  • fastScrollHorizontalTrackDrawable : StateListDrawable used for drawing the line that will represent the scrollbar on the horizontal axis.
  • fastScrollVerticalThumbDrawable : StateListDrawable used for drawing the thumb which will be draggable on the vertical axis.
  • fastScrollVerticalTrackDrawable : StateListDrawable used for draw the line that will represent the scrollbar on the vertical axis.

 

Now, Create native shapes StateListDrawables.

line.xml

line_drawable.xml

thumb.xml

thumb_drawable.xml

 

Now Create RecyclerView and enable fastScrollEnabled.

 

Download this project from GitHub

 

 

 

Android NDK

Android Native Development Kit (NDK) allow you to embed C/C++ code (native code) into your applications. You can use it to either build from your own source code or use existing pre-built native libraries.

NDK-build is a shell script that launches the NDK build scripts. It generates the binaries and copies the binaries into your application’s project path.

Android NDK

NDK provides a tool that allows Java applications to invoke native code and vice versa.

Android NDK example

To compile and debug native code for your app, you need the NDK, CMake, and LLDB.

CMake

It is default build tool for native libraries is CMake inAndroid Studio.It’s an external build tool that works with Gradle to build your native library.

LLDB

It is a debugger for Android Studio to debug native code.

After installation create a new android project

NDK Project

Project structure

 

Create new c++ source files

  1. Right-click on the cpp directory and select New > C++ class.
  2. Enter a name for your source file, such as PrimeNumber.

 

CMake build script

CMake build script is a plain text file.Now configure your build script by adding CMake commands. To instruct CMake to create a native library from native source code, add the add_library()commands to your build script.

When you add a source file or library to your CMake build script using add_library()

Hear, we seare PrimeNumber to native-lib.

 

when making changes to your CMake  script file after you have already linked it to Gradle, you should sync Android Studio with your changes by selecting Build > Refresh Linked C++ Projects from the menu bar.

Finally, we can implement the native source code, which contains the native function. We need to include the header file jni.h . We can see in the example that the native function returns a  jboolean(JNI data type).

The name of the function is composed of: The Java_  string  +  file path relative to the top level source directory that contains the Java source code (with underscore instead of slash) +  the name of the Java source code (without the java extension) + the native function name

We have three arguments: 1 JNIEnv * is a pointer to the VM, also called interface pointer  2.jobject is a pointer to the implicit “this” object passed from the Java side.3 Integer number.

The Java source code includes 3 lines

● First of all, you must have a static initializer in which we load the native library.This code will be executed before any other method.

● Then we must declare the native function. We will use the native keyword which tells the virtual machine that the function implementation is found in a shared native library.

● Finally, we can use the native function directly, in this example will check prime number.

 

Download this project from GitHub.