Monday, 17 September 2018

Universal Android JSON Parser - JSON Reader

What is JSON?

JSON stands for JavaScript Object Notation.It is an independent data exchange format and is the best alternative for XML. This chapter explains how to parse the JSON file and extract necessary information from it.

JSON Reader:

Reads a JSON (RFC 4627) encoded value as a stream of tokens. This stream includes both literal values (strings, numbers, booleans, and nulls) as well as the begin and end delimiters of objects and arrays. The tokens are traversed in depth-first order, the same order that they appear in the JSON document. Within JSON objects, name/value pairs are represented by a single token.

Parsing JSON:

To create a recursive descent parser for your own JSON streams, first create an entry point method that creates a JsonReader.

Next, create handler methods for each structure in your JSON text. You'll need a method for each object type and for each array type.
  • Within array handling methods, first call beginArray() to consume the array's opening bracket. Then create a while loop that accumulates values, terminating when hasNext() is false. Finally, read the array's closing bracket by calling endArray().
  • Within object handling methods, first call beginObject() to consume the object's opening brace. Then create a while loop that assigns values to local variables based on their name. This loop should terminate when hasNext() is false. Finally, read the object's closing brace by calling endObject().
When a nested object or array is encountered, delegate to the corresponding handler method.

When an unknown name is encountered, strict parsers should fail with an exception. Lenient parsers should call skipValue() to recursively skip the value's nested tokens, which may otherwise conflict.

If a value may be null, you should first check using peek(). Null literals can be consumed using either nextNull() or skipValue().

This code implements the parser for the universal JSON structure:


import android.util.JsonReader;
import android.util.JsonToken;
import android.util.Log;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Hashtable;

public class JsonParser {
    Hashtable hashtable;

    JsonParser(){
        hashtable = new Hashtable();
    }

    void parseJSON(InputStream in) throws IOException {
        readJsonStream(in);
    }

    void parseStream(String jsonString) throws IOException {
        InputStream is = new ByteArrayInputStream(jsonString.getBytes());
        parseJSON(is);
    }

    void readJsonStream(InputStream in) throws IOException {
        JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
        parseContent(reader);
        reader.close();
    }

    void parseContent(JsonReader reader) throws IOException {
        JsonToken jsonToken = reader.peek();
        if (jsonToken.equals(JsonToken.BEGIN_ARRAY)) {
            readJSONArray(reader, jsonToken.name());
        } else if (jsonToken.equals(JsonToken.BEGIN_OBJECT)) {
            readJSONObject(reader, jsonToken.name());
        }
    }

    synchronized private void readJSONArray(JsonReader reader, String identifier) throws IOException {
        reader.beginArray();
        while (reader.hasNext()) {
            readJSONObject(reader, identifier);
        }
        reader.endArray();
    }

    synchronized private void readJSONObject(JsonReader reader, String identifier) throws IOException {
        reader.beginObject();
        while (reader.hasNext()) {
            String name = reader.nextName();
            JsonToken jsonToken = reader.peek();
            if (jsonToken.equals(JsonToken.BEGIN_ARRAY)) {
                readJSONArray(reader, name);
            } else if (jsonToken.equals(JsonToken.BEGIN_OBJECT)) {
                readJSONObject(reader, name);
            } else {
                addAttributes(name,reader, jsonToken.name(), jsonToken);
            }
        }
        reader.endObject();
    }

    synchronized private void addAttributes(String attribute,JsonReader reader, String identifier,JsonToken jsonToken) throws IOException {
        String value;
        try {
            value = reader.nextString();
            hashtable.put(attribute,value);
            Log.d("addAttributes","Attribute"+attribute+"Value:::"+value);
        } catch (Exception e) {
            reader.skipValue();
        }
    }
}



Use the following code snippet to parse JSON InputStream


JsonParser jsonParser = new JsonParser();
try {
    jsonParser.readJsonStream(is);
} catch (IOException e) {
    e.printStackTrace();
}

Sunday, 3 September 2017

Android Oreo Features and APIs


Android 8.0(Android Oreo API level 26) released on August 21, 2017. Android 8.0 brings a ton of great features such as picture-in-picture, autofill, integrated Instant Apps, Google Play Protect, faster boot time, and much more.


Picture-in-Picture mode:


Picture-in-picture in Android 8.0.


Android 8.0 (API level 26) allows activities to launch in picture-in-picture (PIP) mode. PIP is a special type of multi-window mode mostly used for video playback. PIP mode is already available for Android TV; Android 8.0 makes the feature available on other Android devices.


When an activity is in PIP mode, it is in the paused state, but should continue showing content. For this reason, you should make sure your app does not pause playback in its onPause() handler. Instead, you should pause video in onStop(), and resume playback in onStart(). For more information, see Multi-Window Lifecycle.


To specify that your activity can use PIP mode, setandroid:supportsPictureInPicture to true in the manifest. (Beginning with Android 8.0, you do not need to set android:resizeableActivity to true if you are supporting PIP mode, either on Android TV or on other Android devices; you only need to setandroid:resizeableActivity if your activity supports other multi-window modes.)


Android 8.0 (API level 26) introduces a new object, PictureInPictureParams, which you pass to PIP methods to specify how an activity should behave when it is in PIP mode. This object specifies properties such as the activity's preferred aspect ratio.


The existing PIP methods described in Adding Picture-in-picture can now be used on all Android devices, not just on Android TV. In addition, Android 8.0 provides the following methods to support PIP mode:



  • Activity.enterPictureInPictureMode(PictureInPictureParams args):  Places the activity in picture-in-picture mode. The activity's aspect ratio and other configuration settings are specified by args. If any fields in args are empty, the system uses the values set the last time you called Activity.setPictureInPictureParams(). The specified activity is placed in a corner of the screen; the rest of the screen is filled with the previous activity that was on screen. The activity entering PIP mode goes into the paused state, but remains started. If the user taps the PIP activity, the system shows a menu for the user to interact with; no touch events reach the activity while it is in the PIP state.
  • Activity.setPictureInPictureParams():  Updates an activity's PIP configuration settings. If the activity is currently in PIP mode, the settings are updated; this is useful if activity's aspect ratio changes. If the activity is not in PIP mode, these configuration settings are used regardless of theenterPictureInPictureMode() method that you call.

Notifications


In Android 8.0 (API level 26), we've redesigned notifications to provide an easier and more consistent way to manage notification behavior and settings. These changes include:

A notification long-press menu in Android 8.0 (API level 26).

Users can long-press on app launcher icons to view notifications in Android 8.0.


  • Notification channels: Android 8.0 introduces notification channels that allow you to create a user-customizable channel for each type of notification you want to display. The user interface refers to notification channels as notification categories. To learn how to implement notification channels, see Managing notification channels.

  • Notification dots: Android 8.0 introduces support for displaying dots, or badges, on app launcher icons. Notification dots reflect the presence of notifications that the user has not yet dismissed or acted on. To learn how to work with notification dots, seeNotification badges.

  • Snoozing: Users can snooze notifications, which causes them to disappear for a period of time before reappearing. Notifications reappear with the same level of importance they first appeared with. Apps can remove or update a snoozed notification, but updating a snoozed notification does not cause it to reappear.

  • Notification timeouts: You can set a timeout when creating a notification using setTimeoutAfter(). You can use this method to specify a duration after which a notification should be canceled. If required, you can cancel a notification before the specified timeout duration elapses.

  • Notification settings: You can call setSettingsText() to set the text that appears when you create a link to your app's notification settings from a notification using the Notification.INTENT_CATEGORY_NOTIFICATION_PREFERENCES intent. The system may provide the following extras with the intent to filter the settings your app must display to users: EXTRA_CHANNEL_ID, NOTIFICATION_TAG, and NOTIFICATION_ID.

  • Notification dismissal: Users can dismiss notifications themselves, and apps can remove them programmatically. You can determine when a notification is dismissed and why it's dismissed by implementing the onNotificationRemoved() method from the NotificationListenerServiceclass.

  • Background colors: You can set and enable a background color for a notification. You should only use this feature in notifications for ongoing tasks which are critical for a user to see at a glance. For example, you could set a background color for notifications related to driving directions, or a phone call in progress. You can also set the desired background color using setColor(). Doing so allows you to use setColorized() to enable the use of a background color for a notification.

  • Messaging style: In Android 8.0, notifications that use the MessagingStyle class display more content in their collapsed form. You should use theMessagingStyle class for notifications that are messaging-related. You can also use the addHistoricMessage() method to provide context to a conversation by adding historic messages to messaging-related notifications.

Autofill framework



Account creation, login, and credit card transactions take time and are prone to errors. Users can easily get frustrated with apps that require these types of repetitive tasks.

Android 8.0 (API level 26) makes filling out forms, such as login and credit card forms, easier with the introduction of the Autofill Framework. Existing and new apps work with Autofill Framework after the user opts in to autofill.


You can take some steps to optimize how your app works with the framework. For more information, see Autofill Framework Overview.












Downloadable fonts


Android 8.0 (API level 26) and Android Support Library 26 let you request fonts from a provider application instead of bundling fonts into the APK or letting the APK download fonts. This feature reduces your APK size, increases the app installation success rate, and allows multiple apps to share the same font.


Fonts in XML


Android 8.0 (API level 26) introduces a new feature, Fonts in XML, which lets you use fonts as resources. This means, there is no need to bundle fonts as assets. Fonts are compiled in R file and are automatically available in the system as a resource. You can then access these fonts with the help of a new resource type, font.

The Support Library 26 provides full support to this feature on devices running API versions 14 and higher.



Autosizing TextView


Android 8.0 (API level 26) lets you set the size of your text expand or contract automatically based on the size of the TextView. This means, it is much easier to optimize the text size on different screens or with dynamic content. For more information, about autosizing TextView in Android 8.0, see Autosizing TextView.


Adaptive icons






Android 8.0 (API level 26) introduces adaptive launcher icons. Adaptive icons support visual effects, and can display a variety of shapes across different device models. To learn how to create adaptive icons, see the Adaptive Icons guide.


Color management


Android developers of imaging apps can now take advantage of new devices that have a wide-gamut color capable display. To display wide gamut images, apps will need to enable a flag in their manifest (per activity) and load bitmaps with an embedded wide color profile (AdobeRGB, Pro Photo RGB, DCI-P3, etc.).


WebView APIs


Android 8.0 provides several APIs to help you manage the WebView objects that display web content in your app. These APIs, which improve your app's stability and security, include the following:
  • Version API
  • Google SafeBrowsing API
  • Termination Handle API
  • Renderer Importance API

To learn more about how to use these APIs, see Managing WebViews.

The WebView class now includes a Safe Browsing API to enhance the security of web browsing. For more information, see Google Safe Browsing API.



Pinning shortcuts and widgets



Android 8.0 (API level 26) introduces in-app pinning of shortcuts and widgets. In your app, you can create pinned shortcuts and widgets for supported launchers, subject to user permission.

For more information, see the Pinning Shortcuts and Widgets feature guide.



Maximum screen aspect ratio


Android 8.0 (API level 26) brings changes to how to configure an app's maximum aspect ratio.

First, Android 8.0 introduces the maxAspectRatio attribute, which you can use to set your app's maximum aspect ratio. In addition, in Android 8.0 and higher, an app's default maximum aspect ratio is the native aspect ratio of the device on which the app is running.




Multi-display support




Beginning with Android 8.0 (API level 26), the platform offers enhanced support for multiple displays. If an activity supports multi-window mode and is running on a device with multiple displays, users can move the activity from one display to another. When an app launches an activity, the app can specify which display the activity should run on.

Note: If an activity supports multi-window mode, Android 8.0 automatically enables multi-display support for that activity. You should test your app to make sure it works adequately in a multi-display environment.


Only one activity at a time can be in the resumed state, even if the app has multiple displays. The activity with focus is in the resumed state; all other visible activities are paused, but not stopped. For more information on the activity lifecycle when several activities are visible, see Multi-Window Lifecycle.


When a user moves an activity from one display to another, the system resizes the activity and issues runtime changes as necessary. Your activity can handle the configuration change itself, or it can allow the system to destroy the process containing your activity and recreate it with the new dimensions. For more information, see Handling Configuration Changes.


ActivityOptions provides two new methods to support multiple displays:


setLaunchDisplayId()

Specifies which display the activity should be shown on when it is launched.

getLaunchDisplayId()

Returns the activity's current launch display.

The adb shell is extended to support multiple displays. The shell start command can now be used to launch an activity, and to specify the activity's target display:


adb shell start <activity_name> --display <display_id>



Unified layout margins and padding


Android 8.0 (API level 26) makes it easier for you to specify situations where opposite sides of a View element use the same margin or padding. Specifically, you can now use the following attributes in your layout XML files:
  • layout_marginVertical, which defines layout_marginTop and layout_marginBottom at the same time.
  • layout_marginHorizontal, which defines layout_marginLeft and layout_marginRight at the same time.
  • paddingVertical, which defines paddingTop and paddingBottom at the same time.
  • paddingHorizontal, which defines paddingLeft and paddingRight at the same time.
Note: If you customize your app's logic to support different languages and cultures, including text direction, keep in mind that these attributes don't affect the values of layout_marginStart, layout_marginEnd, paddingStart, or paddingEnd. You can set these values yourself, in addition to the new vertical and horizontal layout attributes, to create layout behavior that depends on the text direction.


Pointer capture


Some apps, such as games, remote desktop, and virtualization clients, greatly benefit from getting control over the mouse pointer. Pointer capture is a new feature in Android 8.0 (API level 26) that provides such control by delivering all mouse events to a focused view in your app.

Starting in Android 8.0, a View in your app can request pointer capture and define a listener to process captured pointer events. The mouse pointer is hidden while in this mode. The view can release pointer capture when it doesn't need the mouse information anymore. The system can also release pointer capture when the view loses focus, for example, when the user opens another app.



App categories


Android 8.0 (API level 26) allows each app to declare a category that it fits into, when relevant. These categories are used to cluster together apps of similar purpose or function when presenting them to users, such as in Data Usage, Battery Usage, or Storage Usage. You can define a category for your app by setting the android:appCategory attribute in your <application> manifest tag.

Sunday, 27 August 2017

Android Parallax Scrolling Effect


Create Amazing Animations with Android Design Support Library

         Easily create stunning animations with less code using the Android design support library. Toolbar has become a popular choice over ActionBar/AppBar due to its versatility and customizability. This tutorial will show you how to create an expandable/collapsible toolbar with parallax scrolling effects using widgets such as AppBarLayout, CoordinatorLayout, CollapsingToolbarLayout, etc.

     For parallax scrolling, use Coordinator Layout as the base layout and add AppbarLayout, Nested Scrollview, or Recyclerview as direct child layouts. Discover how to configure parallax effects and different Toolbar animations in this guide. Learn about the layout structure of the Coordinator Layout. 


CoordinatorLayout

CoordinatorLayout is a layout in Android that provides a top-level container for windows and serves as a base for swipe-to-refresh, scrolling techniques, floating action buttons (FAB), Snackbars, and other material design components. It is used to coordinate the behavior of multiple child views, allowing them to interact with each other and respond to gestures.

Maximize the Potential of Your Android Layouts with CoordinatorLayout

Do you want to take your Android layouts to the next level? Look no further than CoordinatorLayout. This super-powered FrameLayout provides two primary use cases: as a top-level application decor or chrome layout, and as a container for specific interactions with one or more child views.

With CoordinatorLayout, you can specify Behaviors for child views, enabling them to interact with one another and respond to gestures. The result? A wide range of interactions and layout modifications, from sliding drawers and panels to swipe-dismissable elements and sticky buttons.

Take advantage of the power of CoordinatorLayout by assigning anchor views to its children. These anchors correspond to arbitrary descendants of the CoordinatorLayout, providing even more customization options for your layouts. Upgrade your Android layouts today with CoordinatorLayout. 

Consider the following picture:




       The CoordinatorLayout coordinates Views within the layout. In this example, it contains an AppbarLayout, a scrollable view, and an anchored FloatingActionButton. The AppbarLayout includes a CollapsingToolbarLayout with an ImageView and Toolbar. The NestedScrollView contains a TextView. The FloatingActionButton is anchored to the AppbarLayout.

 

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"android:layout_height="match_parent" android:background="@android:color/background_light" android:fitsSystemWindows="true" >
<!-- AppbarLayout -->
<!-- CollapsingToolbarLayout -->
<!-- ImageView and Toolbar -->
<!-- /CollapsingToolbarLayout -->
<!-- /AppbarLayout -->
<!-- NestedScrollView -->
<!-- TextView -->
<!-- /NestedScrollView -->
<!-- FloatingActionButton -->
</android.support.design.widget.CoordinatorLayout>

AppBarLayout

AppBarLayout is a special type of Toolbar that serves as a container for branding, navigation, search, and action items. The desired scrolling behavior of the AppBarLayout can be set through the setScrollFlags() method. The real power of AppBarLayout lies in the proper management of different scroll flags in its views.

CollapsingToolbarLayout

CollapsingToolbarLayout is a wrapper for the Toolbar that implements a collapsing app bar. It is designed to be used as a direct child of the AppBarLayout and is commonly seen in profile screens in applications such as WhatsApp. This layout includes components such as the Collapsing Title, scrollFlags, CollapsedTitleGravity, ContentScrim, etc.

Toolbar

Toolbar is a standard toolbar used within application content. Unlike the action bar, which is part of the Activity's window decor controlled by the framework, a Toolbar can be placed anywhere within the view hierarchy. The Toolbar can be designated as the action bar for an Activity by using the setActionBar() method.

Behavior

App bars have four main regions (referred to as blocks) that make up their scrolling structure: status bar, toolbar, tab bar/search bar, and flexible space, which accommodates images or extended app bars.

To add an AppBarLayout:

    1. Add the latest design library to your build.gradle file:

dependencies {

compile 'com.android.support:design:X.X.X'

// X.X.X specifies the version

}

    1. Make your Activity extend android.support.v7.app.AppCompatActivity.

public class MainActivity extends AppCompatActivity {

    1. Add the Toolbar inside an AppBarLayout, and the AppBarLayout inside a CoordinatorLayout:

<android.support.design.widget.CoordinatorLayout

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical">

Layout xml

<android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="?attr/colorPrimary" android:elevation="@dimen/toolbar_elevation"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" style="@style/AppTheme.Widget.Toolbar"/> </android.support.design.widget.AppBarLayout> ...

</android.support.design.widget.CoordinatorLayout> "


From that point, the configuration depends on some flags described below.

Standard app bar



AppbarLayout flags:


SCROLL_FLAG_ENTER_ALWAYS: When entering (scrolling on screen) the view will scroll on any downwards scroll event, regardless of whether the scrolling view is also scrolling.

SCROLL_FLAG_ENTER_ALWAYS_COLLAPSED: An additional flag for 'enterAlways' which modifies the returning view to only initially scroll back to it's collapsed height.

SCROLL_FLAG_EXIT_UNTIL_COLLAPSED: When exiting (scrolling off screen) the view will be scrolled until it is 'collapsed'.




SCROLL_FLAG_SCROLL:
 The view will be scroll in direct relation to scroll events.

SCROLL_FLAG_SNAP: Upon a scroll ending, if the view is only partially visible then it will be snapped and scrolled to it's closest edge.




Specs:

The standard app bar height is 56dp on mobile and 64dp on larger screen sizes.

The app bar has two scrolling options:
  • The app bar can scroll off-screen with the content and return when the user reverse scrolls.
  • The app bar can stay fixed at the top with content scrolling under it.

App bar with tabs




The standard app bar component that can include the following blocks: a toolbar, tab bar, or flexible space.

Tabs may have one of these behaviors:
  • The tab bar stays anchored at the top, while the toolbar scrolls off.
  • The app bar stays anchored at the top, with the content scrolling underneath.
  • Both the toolbar and tab bar scroll off with content. The tab bar returns on reverse-scroll, and the toolbar returns on complete reverse scroll.

Flexible space





Because the app bar is flexible, it can be extended to accommodate larger typography or images. To extend the app bar, add a flexible space block.

Flexible space may be displayed one of two ways:
  • The flexible space shrinks until only the toolbar remains. The title shrinks to 20sp in the navigation bar. When scrolling to the top of the page, the flexible space and the title grow into place again.
  • The whole app bar scrolls off. When the user reverse scrolls, the toolbar returns anchored to the top. When scrolling all the way back, the flexible space and the title grow into place again.

Flexible space with image





Use flexible space to accommodate images in the app bar with the desired aspect ratio.

In this example, the aspect ratio is 4:3. When scrolling, the content pushes up the image, which shrinks the flexible space. At the end of the transformation, the image gets tinted with the primary color, independent of scrolling.

Flexible space with overlapping content





Content can overlap the app bar.

The app bar has two scrolling options:
  • The app bar is initially positioned behind the content. Upon upward scroll, the app bar should scroll faster than the content, until the content no longer overlaps it. Once anchored in place, the app bar lifts up for content to scroll underneath.
  • The app bar can scroll off-screen with the content and return when the user reverse scrolls.In this interaction, the app bar cannot include tabs.

Universal Android JSON Parser - JSON Reader

What is JSON? JSON stands for JavaScript Object Notation.It is an independent data exchange format and is the best alternative for XML. ...