Test cases and workflow for in-app purchase of android app

In-app

In this blog, I would like to share android in-app product types, workflow of in-app purchases, and the set up of the test releases by a developer. These 3 things are essential for a tester to start in-app purchase testing.

In-App Product Types

The android in-app billing supports the managed in-app products and subscriptions.

Managed product: Once you purchase a product, that item cannot be purchased again until you consume the item, by sending consumption to Google play.

Subscriptions: This product type offers sell features, content, and services to users from the app with recurring weekly or monthly or annual billing.

In-app purchase workflow and settings for releasing apps to test:

The Google Play Console provides several tools to test the in-app billing. There are three stages of app deployment in android in-app purchase:

  1. Alpha
  2. Beta
  3. Production

Alpha and Beta Release (Sandbox account):

Publish app directly to Google Play’s alpha and beta release channels for testing purpose. The app will be available only to the tester who can download and install the app to the device from Play Store.

To release a test app, first, the developer should create and add test-user Gmail accounts to ‘Tester List’ group in Alpha/Beta release section.

Both the alpha/beta release is same; the only difference is adding the number of tester accounts.

  • Alpha test – we can create a small group of testers.
  • Beta test – we can create up to 50 lists per track and can add up to 2000 users in each track.

Testing in-app purchase (In-app billing – Subscription type)

To test in-app purchase, we need to publish the app to an Alpha or Beta channel in Google Play. You can choose any user to be a test account and any user of test account can make test purchases with any available payment methods, without any actual charges to their accounts.

First, the developer has to upload and publish in-app products in play console before publishing the APK itself. Then, add user account ID (Gmail ID) to License testing section in the developer console and we can add up to 400 test-user accounts to test in-app purchase products.

Steps to add: Login to developer console and Go to Settings –> Accounts details then add the addresses to License Testing field.

Note: The address should belong to Google account. It will not accept other accounts to add as license tester.

Once you add the users as license tester accounts and saved the changes, within 15 minutes those users can make a test purchase of your in-app products. After publishing the app, the tester needs to opt-in the alpha/beta release of the app using the provided opt-in URL before making test purchases. In this case, the developer will provide an opt-in link to the test users.

The opt-in URL will generate once the developer has created and added the license test users in the license section. Before that, the developer will send an invitation to users to become a part of tester group and then copy and send generated “opt-in URL” to all test-user accounts.

Once test-users get authorized test access, they can make a purchase without any actual charges. After all the processes have completed, the app will be available in tester’s Play Store who were all added as the Alpha/Beta tester.

Test purchase is auto-renewable on daily basis for any actual duration. The app will automatically renew every day until you cancel the purchase.

Important note: Licensed account must be on the user’s android device. If the device has more than one account, the purchase will be made with the account that downloaded the app. If none of the accounts have downloaded the app, the purchase is made with the first account. Users can confirm the account that is making a purchase by expanding the purchase dialog.

Steps to start an in-app purchase (Subscription) test:

  1. The user will receive an invitation to become an Alpha/Beta tester. Click on ‘Become a Tester’ button in the mail to be a part of the tester group.
  2. Later, the tester will get detailed mail along with opt-in URL link of test application from Google Play Console.
  3. Click on ‘opt-in URL.’ It will redirect to your Play Store app and shows test app with all the information.
  4. You can download and install the app to your phone from Play Store using licensed tester account.
  5. To add payment methods for purchasing the app, select Slider Menu in Google play store –> choose Account option –> Select Payment methods –>  then add your valid international Credit/Debit Card or Net banking detail along with your name and address.
  6. Click on Save in the popup window.
  7. The Payment method will be successfully saved. If you did not add your Payment method, it will ask the card details while doing the purchase.
  8. Once the payment details are successfully added, an amount of ₹50.00 will be debited from your account for Debit/Credit card verification but after few minutes, the amount will be credit back to your account. It will be debited while adding the card detail only. It will not debit while subscribing to the app (If you are a licensed test-user).
  9. Next, you can start testing subscription function in your app
  10. The following message will be displayed on Google popup when you make a payment. “This is test subscription. It will recur daily. You will not be charged.”
  11. You will get a receipt for your purchase order from Google Play Store on successful purchase.
  12. The subscription will auto-renew and send email every day until you unsubscribe the purchase.

Test Cases:

  1. Pricing info should be displayed based on region-specific currency and needs to verify whether the mentioned price has tax included or excluded.
  2. Span time of billing period and description about your subscription should be shown as per requirement.
  3. To verify, the app will deduct given price while purchasing the subscription.
  4. Services or Features should be accessible after successful purchase.
  5. Check whether the purchase auto-renews in the specified duration because it should be continuously renewing the purchase until you cancel the purchase.
  6. Check whether the subscription is expired once the specific subscription period is over. The subscription will expire only if the user canceled auto-renewal or subscription (Auto-renewable product).
  7. Check whether the app is expired on time and make sure that the users should not access purchasable content or features (Non-auto renewable product).
  8. Subscription features should be automatically restored while re-install/updating the app. If it is a Non-consumable product, the app should have restore button for restoring the purchases.
  9. Use the same purchase id to multiple devices and verify whether the app has subscribed state.
  10. Use different accounts (ID doesn’t have a subscription) to Google Play and install the app and verify that the app has Un-subscribed state.
  11. Subscription features should continue to users after canceling the auto-renewal or subscription and until it expires.
  12. Check the status of in-app purchase when users purchase while there is no network on the device. ‘No internet connection’ should be shown when the user tries to purchase a product and while accessing purchasable features.
  13. Once the network connection comes back, check the status of previously attempted purchase at that time of network failure.
  14. The app should validate the purchases on the update
  15. Check the subscribe function of product that was already purchased. It should not allow purchase again.
  16. Verify that the users get purchase receipt from Google play until they cancel the subscription.

 

FacebookTwitterGoogle+Share
Augmented Reality Vs. Virtual Reality: Which One Will Triumph?

Technology can make everything possible nowadays. It has developed in such a way that it even makes you sense and feel your presence in your dream or imagined world. Augmented Reality (AR) and Virtual Reality (VR) are two of such most crucial technology advancements that detach you from the real world. However, the theory between both the AR and VR is entirely different.

VR vs AR

Let us dive into the article, to know the subtle differences between AR and VR.

Virtual reality is an artificial environment that is created by computer graphics, which can be experienced as if that was real. Whereas, augmented reality adds an overlay to the already existing real world, instead of replacing reality (a blend of virtual reality and real life).

AR

Both AR and VR are similar in the ambition of connecting users beyond the real life. However, both the systems do this in diverse ways. With VR, you will be isolated from real-life and involve in the world that is entirely fabricated. With AR, you will be continuously in touch with real-world besides interacting virtual objects around them.

What are they used for?

Everyone believes that virtual reality is just for gaming. But, any business that would benefit from involving users in a different world can use VR technology. This technology could be used during therapeutic treatments for problems such as phobias and other circumstances like tourism to show people the things which no longer exist but are of interest.

AR exists with a much wider scope. Anything that is developed using VR technology can also be developed by AR technology. When we consider games, treatment, and tourism with AR technology, they provide more realistic experience as they were developed having the real world as a part of the technology.

Which technology will succeed?

Even though VR garnered attention in recent years, AR technology acquired substantial financial support from investors and venture capitalists. This is because; AR, in fact, is a stimulated approach towards tangible results and is far more practical with multiple implementations than VR.

As various products with augmented reality are already in the market, we can state that it is ahead of virtual reality. When it comes to VR technology, it is spreading its wings with the rise of Oculus Rift but has still a long way to go to receive a strong impression from users.

Market sector forecasts estimated that by 2020, AR and VR would hit $150 billion revenue with AR taking $120 billion shares and VR at $30 billion.

AR vs VR

Though AR does not take people completely out of the real world, it may have more commercial success as it provides a realistic experience. However, we believe that both AR and VR technologies will succeed.

IndexedDB Support in Chrome Browser

What is IndexedDB?

  • IndexDB (Index Database) is a low-level API for storing significant amount of data in the client-side, including file/blob.
  • It is a document database (NoSQL or Object) that exist in sandbox context entirely within the browser and provides a way to store large amounts of data on your user’s browser.
  • The below figure highlights the structure of database in IndexDB.

indexdb

  • You can also choose cookies and local storage for storing data but they don’t offer database usability the way IndexDB do.

Why use IndexDB?

  • IndexDB is a transactional database system similar to an SQL-based RDBMS. However, unlike SQL-based RDBMS, IndexDB is a javascript-based object oriented database, which does not use fixed column tables,
  • IndexDB stores key-value pair and let you store and retrieve objects that are indexed with a key.
  • The data stored in IndexDB is persistence. It offers rich query abilities and is available both in online and offline mode.
  • IndexDB also offers a powerful indexed based searching API to retrieve the data you need.

Checking IndexDB Compatibility in Chrome Browser

To open and configure database operations, you need to assure that your browser supports IndexDB. Implement the below code in your application in order to check the IndexDB compatibility in chrome browser.

window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;

if(!window.indexedDB){

console.log("Your Browser does not support IndexedDB");

}

If the browser is supporting IndexDB, you can open and configure the database.

Issues While Checking IndexDB Compatibility

While checking IndexDB compatibility in chrome browser, we have faced one issue. When we were using older chrome version, the code which we implemented to check IndexDB compatibility was working fine.

Here is the code snippet we used on older version.

window.indexedDB = window.$indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;

if(!window.indexedDB){

console.log("Your Browser does not support IndexedDB");

}

But, after we upgrade our chrome version to 57.0.2987, the IndexDB is not supporting the latest chrome browser. To fix this issue, we made one small change in the above OR condition. We removed ‘$’ symbol from window.$indexedDB. After making this change, the IndexDB is supporting the latest browser.

Find below the working code snippet.

window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;

if(!window.indexedDB){

console.log("Your Browser does not support IndexedDB");

}

IndexDB is appropriate to handle large amounts of data and to perform complex search queries. It uses indexes to store the data and transactions to perform operations.

Why temperature monitoring and control is necessary across industries and how to manage it?

Temp-Humidity-Icon-Blog-800x500Industries have different specifications, requirements, and motives when it comes to temperature control of its product or environment. Let’s see some industries where temperature needs to be constantly regulated and why.

Food & Beverage Industry

Companies dealing with manufacturing, processing, packaging, transporting or storage of food ingredients/materials/products need constant monitoring of the food temperature levels. The operations of these industries are controlled by regulatory bodies like FDA to prevent contamination, spoilage or other hazards, some of which could even turn deadly for people. These regulations are implemented to safeguard the health of consumers/general public which has to be mandatorily followed by the businesses. Unless food products are monitored and their temperature levels are maintained, the bacterial growth cannot be curbed and could result in casualties. Therefore, the companies should constantly monitor the temperature to prevent harmful bacteria & pathogenic microorganism growth.

Breweries require specific temperature conditions for yielding best results in beer fermentation process. Coolers and fermenters are to be monitored constantly to prevent temperature from going too high or low.

Airline & Cruiseline catering services are involved in serving high-quality food to passengers from different regions of the world. They should be certain in the quality of food they are providing and food temperature plays a vital role in the food quality.  It is essential to track the temperature of food at the time of cooking as well as serving in these industries.

Healthcare:

Pharmaceutical companies need to maintain the temperature levels in a warehouse between 68°F and 78°F to maximize shelf life of their products. The companies also require tracking of their humidity levels to ensure that medicines are kept in the best environment.

Laboratories with sophisticated medical instruments require the environment temperature to be controlled for accurate results and performance. Humidity changes to laboratory environment may result in corrosion or micro corrosion of mission critical equipments, increased maintenance cost, inaccurate readings, and replacement.

Blood Banks store blood bags at adequate temperatures to ensure safety in transfusion practices. Blood transfusion could cause serious consequences if the transfused blood is not safe. Due to power disruptions and equipment failures sometimes blood banks throw away blood bags that are unsafe for transfusion.

ICU Room temperatures need to be maintained between predefined ranges to ensure the wellbeing of patients. To patients whose temperatures fall outside of the normal range, healthcare professionals should use temperature management tools to restore normal body temperatures, such as heating or cooling blankets. ICU Rooms require careful and constant monitoring of its room temperature for the comfort of the patient as well as for slowing down the growth of bacteria and other microorganisms.

Retail Industry:

Malls & Supermarkets needs to maintain their floor temperature in an adequate range for the comfort of people visiting the malls as well as for maintaining a safe temperature for increasing the shelf life of products. Supermarkets must control and monitor its environment temperature to ensure the quality of food products being stored and to prevent spoilage. A supermarket will have a variety of products that includes vegetables, fruits, milk items, meat, beverages and other perishable food products which make it essential for temperature and humidity regulations inside the stores.

Real Estate

Apartments and property management communities may require continuous monitoring of various critical control parameters including air temperature, moisture content, pressure, motion, pollution, fuel storage, contamination, etc., are well interpreted and red-pinged when needed assuring safety and well-being to its inmates at all times.

Managing the temperature parameters:

Even though businesses set up the air conditioning, chilling & cooling systems for temperature control, it needs to be monitored 24*7, to prevent any incidents from happening. A fully automated system that notifies the assigned user whenever the temperature fluctuates from the required range must be installed in these facilities. Fully operating temperature control and monitoring system with real-time data on temperature and humidity levels will allow effective management of food safety, ICU rooms, Malls & retails, Laboratories, blood banks, etc.

Software solutions like Ionhaccp will allow you to record and track the temperature and humidity details of a room or product. Its workflow is designed to ensure strict verification and constant watch on the temperature levels. Any deviations will be notified by Email as well as SMS which allows the assigned field staff to take corrective measures.

Behold! Beyond Biomag 3D iOS App is Here

It’s been a week since we launched Beyond Biomag 3D, a reference app for biomagnetism practitioners and clients to locate the Anatomical Biomagnetism pairs in the human body using 3D male and female models.

With the help of this app, users can self-heal his/her health concerns using a pair of magnets of medium intensity. It assists users to understand various scan points and their corresponding pairs in the body, where the user has to place the magnets to neutralize the pH level. The app is designed with 3D model representation of male and female bodies, scan guide briefing about scan points and their respective therapies, and a dictionary with anatomical biomagnetism pairs.

Amazing Features

3D Models

The app is developed using Unity 3D engine, which allows you to rotate the 3D models in 360 degrees to locate scan points and corresponding pairs

Biomag 3D app

Reliability in Self Healing

With proximate spotting of scan points on the 3D model and easy navigation to a specific body section, our Beyond Biomag 3D app makes self-healing easier and effective.

Biomag 3D App

Dictionary

The built-in dictionary that allows you to search for anatomical biomagnetism pairs based on health concerns and associated microbiome.


Dictionary edited  Dictionary2 Edited

Gender Switch

Easy toggling between male & female models. The app functionalities are similar in both the models.

Biomag 3D

Language

The application interface currently supports switch between English and Spanish language.

blog4

An iOS user can start using the Beyond Biomag 3D app today by downloading it for free from the App Store. The free version has 25 Biomagnetism Pairs. To explore the app with 250+ biomagnetism pairs and 1000+ health concerns, you can subscribe to our annual plan for $99.99 only (taxes applicable).

Download the app today and enjoy the amazing benefits of Beyond Biomag 3D.

Apple App Store

What is Jenkins?

During the earlier days of my career at Vmoksha, I have been assigned to set up Jenkins for an Android project development. With a mere knowledge of Java Software Development in those days, it was quite a challenge for me. Initially, I tried to understand what Jenkins is, why it is used and how it helps our android projects. I read the Wikipedia article of Jenkins but couldn’t understand much though. Then, I have done a thorough research to understand about Jenkins.

I know you are also searching for Jenkins and landed on this page. I am pretty sure that after reading this Jenkins blog, you will comprehend Jenkins better.

Introduction

Jenkins is a Continuous Integration (CI) server or tool which is written in java. It provides Continuous Integration services for software development, which can be started via command line or web application server. And also, it is happy to know that Jenkins is free software to download and install.

Continuous Integration

Before going in details to Jenkins, let me tell you what Continuous Integration (CI) is.

Continuous Integration (CI) is a development practice that requires developers to integrate code into a shared repository several times a day. It is a process of running your tests on a non-developer (say testers) machine automatically when someone pushes new code into the source repository. The below diagram shows the CI workflow.

jenkins

In this type of procedure, there is a huge advantage of knowing whether all the jobs (configured project in Jenkins) work properly or not. And also we can get fast feedback. The fast feedback is very important so you will always know, right after you broke the build. In the console, you will get the detailed log messages. From this, you will get to know what the reason for job fail was and you can also get to know how you can revert it back. Using an Artifact Repository in CI server will successfully deploy the built snapshot and release which is available to other developers.

If jobs run occasionally then the problem is that since the last time there will be a lot of code changes might have happened. So it will be hard to figure out which changes introduced the problem. But when it is set to run automatically on every code push then it is always easy to know what and who introduced the problem.

Some of the attractive reasons why you need automate build testing and integration are:

  • Developer time is concentrated on work that matters:  Most of the work like integration and testing is managed by automated build and testing systems. So the developer’s time is saved without wasting on large-scale error-ridden integrations.
  • Software quality is made better: Issues are detected and resolved almost right away which keeps the software in a state where it can be released at any time safely.
  • Makes development faster: Most of the integration work is automated. Hence integration issues are less. This saves both time and money over the lifespan of a project.

Continuous Build System can include tools like Jenkins, Bamboo, and Cruise Control, etc. Bamboo has better UX support but it is not a free tool. Jenkins is an open source tool, easier to setup and configure and also has a very active plug-in development community which makes it favored. Now, let us dive into the Jenkins tool.

Jenkins History

Jenkins was originally developed as the Hudson project. Hudson’s creation started in summer of 2004 at Sun Microsystems. It was first released in java.net in Feb. 2005.

During November 2010, an issue arose in the Hudson community with respect to the infrastructure used, which grew to encompass questions over the stewardship and control by Oracle. Negotiations between the principal project contributors and Oracle took place, and although there were many areas of the agreement a key sticking point was the trademarked name “Hudson” after Oracle claimed the right to the name and applied for a trademark in December 2010. As a result, on January 11, 2011, a call for votes was made to change the project name from “Hudson” to “Jenkins”. The proposal was overwhelmingly approved by community vote on January 29, 2011, creating the Jenkins project.

On February 1, 2011, Oracle said that they intended to continue development of Hudson, and considered Jenkins a fork rather than a rename. Jenkins and Hudson, therefore, continue as two independent projects, each claiming the other is the fork. As of December 2013, the Jenkins organization on GitHub had 567 project members and around 1,100 public repositories, compared with Hudson’s 32 project members and 17 public repositories.

Continuous Integration with Jenkins

Jenkins tool is heavily used in CI which allows code to build, deployed and tested automatically.

Jenkins Continuous Integration

Let us depict a scenario where the complete source code of the application was built and then deployed on the test server for testing. It sounds like a robust way to develop software, but this method has many weaknesses. They are,

  • Developers have to pause till the complete software is developed for the test results.
  • There is a huge possibility that the test results might show lot many bugs. This makes developers be in a complex situation to find the root cause of those bugs since they have to check the entire source code of the application.
  • Delivery process of software is slowed down.
  • Continuous feedback referring to things like coding or architectural issues, build failures, test condition and file release uploads were missing so that the quality of software can go down.
  • The whole process was manual which increments the risk of repeated failure.

It is obvious from the above-stated problems that along with slow software delivery process, the quality of software also went down. This leads to customer unhappiness. So, to overcome such confusion there was a crucial demand for a system to exist where developers can gradually trigger a build and test for each and every change made in the source code. Therefore, Jenkins tool is used in CI. It is the most mature CI tool possible. Now let us see how Continuous Integration with Jenkins crushes the above shortcomings.

For software development, we can hook it up with most of the repositories like SVN, Git, Mercurial, etc. Jenkins has lots of plugins that are available freely. These plugins help to integrate with various software tools for better convenience.

One really nice thing about Jenkins is, build configuration files will be on disk which makes massive build cloning and reconfiguring easy.

Advantages of Jenkins

  • Jenkins is an open source tool with much support from its community.
  • Installation is easier.
  • It has more than 1000 plug-in to make the work easier.
  • It is easy to create new Jenkins plugin if one is not available.
  • It is a tool which is written in Java. Hence it can be portable to almost all major platforms.

The diagram below depicts that Jenkins is integrating various DevOps stages:

 Jenkins Advantages

Once the project is configured in Jenkins then all future builds are automated. It has basic reporting features like status and weather reports (job health).

j3

Most companies who handle continuous integration use their individual cloud-based continuous integration servers built on applications like Jenkins. With Jenkins, organizations can advance the software development process through automation. So overall to say, Jenkins integrates development life-cycle processes of all kinds which include building, documenting, testing, packaging, staging, deploying, static analysis and plenty more.

Building RESTful APIs using Node JS, Express JS, and MS SQL Server

RESTful APIs

REST (Representational State Transfer) is web standards based architecture and uses HTTP Protocol. A REST Server simply provides access to resources and REST client accesses and modifies the resources using HTTP protocol. REST uses various representations to represent a resource like text, JSON, and XML but JSON is the most popular one.

Why do we need RESTful Web Services?

REST is an architecture style for designing networked applications. REST is a lightweight alternative to mechanisms like RPC (Remote Procedure Calls) and Web Services (SOAP, WSDL, et al.). The World Wide Web itself, based on HTTP, can be viewed as an REST-based architecture. The entire modern web browsers are REST client. RESTful applications use HTTP methods (GET, POST, PUT, and DELETE) to perform CRUD operations.

Advantages:

  1. Simple
  2. Easy to use/implement
  3. Easy to build
  4. Uniform interface
  5. The REST API is always independent of the type of platform or languages
  6. Visible, reliable, and scalable

Why opt Node JS for building RESTful APIS?

Node.js is a powerful JavaScript framework built on Google Chrome’s JavaScript V8 Engine. It is used to develop I/O intensive web applications like video streaming sites, single-page applications, etc. Node.js is open source and used by thousands of developers around the world.

nodejsProcessingModel

Advantages:

  1. Quick & easy development
  2. High performance
  3. Run on single thread to handle multiple concurrent requests
  4. Easy to write API and interaction code
  5. Streaming support
  6. Monitoring possibilities
  7. Authentication support
  8. Lightweight, fast, and scalable

About Express JS:

Express is a flexible Node.js web application framework that provides a robust set of features to develop mobile and web applications. It facilitates the rapid development of Node based Web applications. Few core features of Express framework −

  • Allows setting up of middleware to respond to HTTP Requests.
  • Defines a routing table which is used to perform different actions based on HTTP Method and URL.

Allows to the dynamic rendering of HTML Pages based on passing arguments to templates.

Express JS node architecture

Getting Started

Prerequisites:

  1. Node JS
  2. MS SQL Server Database

App Setup & Execution:

Step 1: Create a package.json file.

{
  "name": "<Application Name>",//e.g.  – node_app
  "version": "0.0.0",
  "description": "<Description about your application>",
  "main": "server.js",
    "dependencies": {
        "express": "^4.14.0",
        "body-parser": "^1.15.2",
         “mssql”:”^ 3.3.0”
    },
    "scripts": {
    "start": "node server.js"
  },
  "author": {
    "name": "<Your Name>",
    "email": "<Your Email>"
  }
}

Note:  The package.json file can be created by using npm init command (recommended way).

Step 2: Create server.js file.

//Initiallising node modules
var express = require("express");
var bodyParser = require("body-parser");
var sql = require("mssql");
var app = express(); 

// Body Parser Middleware
app.use(bodyParser.json()); 

//CORS Middleware
app.use(function (req, res, next) {
    //Enabling CORS 
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, contentType,Content-Type, Accept, Authorization");
    next();
});

//Setting up server
 var server = app.listen(process.env.PORT || 8080, function () {
    var port = server.address().port;
    console.log("App now running on port", port);
 });

//Initiallising connection string
var dbConfig = {
    user:  “<dbUserName>”,
    password: “<dbPassword>”,
    server: “<dbHost_URL>”,
    database:” <dbName>”
};

//Function to connect to database and execute query
var  executeQuery = function(res, query){             
     sql.connect(dbConfig, function (err) {
         if (err) {   
                     console.log("Error while connecting database :- " + err);
                     res.send(err);
                  }
                  else {
                         // create Request object
                         var request = new sql.Request();
                         // query to the database
                         request.query(query, function (err, res) {
                           if (err) {
                                      console.log("Error while querying database :- " + err);
                                      res.send(err);
                                     }
                                     else {
                                       res.send(res);
                                            }
                               });
                       }
      });           
}

//GET API
app.get("/api/user ", function(req , res){
                var query = "select * from [user]";
                executeQuery (res, query);
});

//POST API
 app.post("/api/user ", function(req , res){
                var query = "INSERT INTO [user] (Name,Email,Password) VALUES (req.body.Name,req.body.Email,req.body.Password”);
                executeQuery (res, query);
});

//PUT API
 app.put("/api/user/:id", function(req , res){
                var query = "UPDATE [user] SET Name= " + req.body.Name  +  " , Email=  " + req.body.Email + "  WHERE Id= " + req.params.id;
                executeQuery (res, query);
});

// DELETE API
 app.delete("/api/user /:id", function(req , res){
                var query = "DELETE FROM [user] WHERE Id=" + req.params.id;
                executeQuery (res, query);
});

Note: You can add multiple routes based on your requirement.

Step 3: Open CMD, execute npm install command.

Step 4:  After successful installation of node modules, run below command into CMD.

node server.js

CMD

The node server will start running into port number 8080 with corresponding API Routes; you can point to the below URL to test the application.

http://localhost:8080

Step 5: Testing REST APIs

We can use any of the REST Clients like Postman Chrome App or through any of the Programming languages like Java, C#, PHP, etc., to consume the APIs.

Here is the demonstration using Postman App

Postman App

Note: The complete code reference can be downloaded from the below link,

https://github.com/avinashl3175/Vm_BlogContent/blob/master/Node_API_Demo.zip

 

Android Runtime Permissions

From Android M, Google has changed the way of permissions that applications handle. Earlier, we simply mention permissions in AndroidManifest.xml, but from Android 6.0 version, we need to check every time for permission related task. Applications need to ask the permission at runtime while it is running and also have to provide enough contexts on why the permissions are required. All the permissions, though we have to declare in manifest whenever application want to access the APIs that need the runtime permission, apps has to check whether that permission has been granted or to request the required permission using support library.

Types of Permissions:

  1. Normal permission
  2. Dangerous permission

The Normal permissions do not directly affect the user’s privacy. If application lists a normal permission in its manifest, then these permissions will be automatically granted by the system upon installation. Some of the most common normal permissions are given below.

Check and change data connection: Include network state, Wi-Fi State, Bluetooth, Internet, etc.

Example:

Android permissions

The Dangerous permissions are the permissions which give application access to the user’s private data or affect the system/other apps. If you list a dangerous permission in manifest then the user has to explicitly give permission to your application.

Android permissions

Advantage of Runtime Permissions:

In Android 6.0, applications provide transparency to users.  Users have to grant permissions to applications while the application is running rather than during installation and it asks to grant the permission only when some specific function is being used within an app. At that point, users have to decide whether or not to grant their permission. But in the earlier versions of Android 6.0, a user has to grant all the app permissions before installing from the Play Store and if he doesn’t allow the permission then the system doesn’t install the application at all. As a result, many malicious apps are able to access user private data after granting the permission at installation time, which leads to a major security breach. But in Marshmallow, the user can allow or deny individual permission and the application can continue run with limited efficiencies even if the user denies a permission request. In addition, users now have the option to revoke individual app permissions after he has granted them, but in the earlier versions to Marshmallow, the user can’t revoke individual app permissions once he has granted them.

Android permissions

Permission Groups:

Different types of permissions are separated into groups based on which data or resource it requests access for. Once permission from a group has been granted then other permissions within that group do not need to be granted again. For example, permission group for SMS can send or receive the SMS. Those are two different permissions but the user only needs to allow one.

Android 6.0 Marshmallow has nine main groups of permissions:

Calendar: Read and/or write to the calendar.

Camera: Give the application the ability to access the camera.

Location: Access fine or coarse location.

Microphone: The ability to record audio.

Phone: Includes phone state, the ability to make calls, read and write to the call log and voicemail.

Sensor: The ability to use various sensors in the device, like a gyroscope.

SMS: Similar to how the phone is handled including sending and receiving texts. MMS and cell broadcasts.

Storage: Read and write to device’s external storage.

 

Enable/Disable the Runtime Permissions Manually for App

The user can deny the permissions at any time by going to the application’s Settings screen. There are some steps to enable/disable the app permissions given below.

Step1: Open your device’s Settings app.

Step2: Tap apps and find an app which you want to work with. Select it.

Step3: Tap applications permissions on the App Info screen.

Step4: You will see the list of permissions the app requests, tap on the switch to make it ON/OFF.

Runtime permissions

Permission Workflow

Android Marshmallow

Requesting Permissions at Runtime:

In Android 6.0, users allow permissions to applications while it is running, not during installation. This approach streamlines the application install process since the user does not require grant permissions when they install or update the application. It also gives the user control over the application’s functionality. Since the permissions are requested individually, the user can allow some permission and deny others permissions. For example, user can grant camera permission but can deny location permission and the application may function seamlessly.

How to Check for Runtime Permissions:

If your application requires runtime permission, you must check whether you have that permission enabled every time to perform an operation. The user is always free to revoke the permission.

  • Check the Target SDK version: If the device running is former to Android 6.0, there is no need to call new runtime permission workflows.     

Android Marshmallow

  • Check if permission granted
  1. Check whether required permission is granted. Call the ContextCompat.checkSelfPermission (Context, String) method, Context current context and String Permission.
  2. If the application has the permission, the method returns PackageManager.PERMISSION_GRANTED and the application can proceed with the operation.
  3. If the application does not have the permission, the method returns Package Manager.PERMISSION_DENIED and the application have to explicitly ask the user for permission.

runtime permissions

  • Handle Never Ask Again

ShouldShowRequestPermissionRationale (String permission): This method can be called to determine if the user denied this permission previously or not. If this method returns true, then it’s perfect time to tell the user exactly why the permission is needed before requesting it again.

If the user denies the permission request in the past and chose the Never ask again option in the permission request system dialog, this method will return false. Next time we call requestPermissions, this dialog will not appear for this kind of permission anymore. Instead, it just does nothing.

runtime permissions

The result of rational dialog will be shown when this permission is requested for the first time and also be shown if the user has ever marked that permission as Never ask again. For the next case, onRequestPermissionsResult() will be called with PERMISSION_DENIED without any permission grant dialog.

  • Request for Permission:

If the application doesn’t have the permission which requires, the application must call requestPermissions(String [ ] permissions, int requestCode) methods to ask the appropriate permissions. Pass permission array and request code as parameters.

Example: The following code checks if the application has permission to use the location service and requests the permission if necessary.

Android permissions

Android permission

  • Handle the permissions request response:

If the user has granted or denied the permission request, we have to handle response and execute the functionality according to response. This can be achieved by overriding the OnRequestPermissionsResult() in the Activity where the permission was requested. This method returns the result code for granted or denied permission.

permission Request Response

Note: Suppose, the user wants to use some APIs that need runtime permission that has not allowed yet. The function will immediately throw a SecurityException, which will cause to the application crashing.

Android permissions

permission Request

Conclusion:

Runtime Permission is a must in Android Marshmallow. The user will be happier allowing permissions because they are much more likely to install your app without a wall of permissions at the installation. The aim of this new model is to give the user full control over application’s permissions. By using this, users will soon have a better understanding of exactly why app need permission to access any features, which means less Play Store complaints and hopefully a higher download rate.

 

Sensor Characteristics

The sensor is a transducer that converts a physical property into an electrical signal. The physical property can be Weight, Temperature, Pressure, Percentage Composition, Force, Electric or Magnetic or Electromagnetic, Position and Orientation, etc.

The sensors are classified as active sensors and passive sensors based on their working principle. The active sensors use an external or self-generated signal to measure. For example, RADAR emits a series of intense radio waves for a short time and waits for the radio waves or signal to return and calculate the distance of the distant object using the signal flight time. The passive sensors work by changing their electrical properties like resistance or capacitance based on the physical property. For example, an LDR changes its resistance based on the intensity of light.

Sensors must have the following significant properties to define the quality of a sensor:

Range

Every sensor has a range in which they work with an acceptable error. If the input is not in range, then the output is unpredictable.

Drift

The signal level varies for the same input over a long period; this is called as drift. The drift will cause an error in the measured value. The drift may result from aging of the sensor or temperature variance.

Sensitivity

Sensitivity is defined as the change in output per unit change in input of the property being measured. The sensitivity of the sensor may be constant or linear for the entire range of sensor or vary exponentially if the sensor is a non-linear sensor

Selectivity

Selectivity is the ability of the sensor to measure a target property in the presence of other properties. For example, if an oxygen sensor does not react to other gasses like CO2 then it has good selectivity.

Resolution

The resolution of a sensor is the minimum change in the target property that can produce a detectable change in output. For example, consider a temperature sensor with a resolution of 1C; this temperature sensor cannot produce a different output for 0.1C change in input.

Response and Recovery Time

The response time is the time taken by the sensor for its output to reach 95% of its final value when it is exposed to a target material. The Recovery Time is defined conversely.

Linearity

If the sensitivity of the sensor is constant for the range, then it is called as linearity of the sensor. The linear sensors are easier to use while the non-linear sensors require complex mathematical equations to measure the physical property.

Hysteresis

The hysteresis is the characteristic of a sensor by which the sensor produces a different set of outputs if the data is recorded in different directions (increasing input or decreasing input). The hysteresis can be observed in the following figure:

sensor-characteristics-1

Calibration

If a meaningful measurement is to be made, it is necessary to tune the output of the sensor with accurately known input.

Full-Scale Output

The full-scale output is the difference between the output for maximum input and the output for minimum input. Based on this, the ADC’s reference voltages have to be selected properly.

Precision

The precision of a sensor is its ability to produce same output when repeatedly measured for the same input. The precision is determined using statistical analysis standard deviation.

Accuracy

The accuracy of a sensor defines how close the output is to the real value. The accuracy defines the maximum error the sensor may produce.

sensor-characteristics Accuracy

References:

https://www.uam.es/docencia/quimcursos/Scimedia/chem-ed/data/acc-prec.htm

http://www.mfg.mtu.edu/cyberman/machtool/machtool/sensors/fig2.gif

Material Design for Android

Introduction

In 2014, Google developed a new visual design language called Material Design for Android Lollipop and higher versions. The visual specifics in material design are amusing, and the material objects have x, y and z dimensions, which allows you to create an incredible 3D world. Material design is not about how to use dazzling colors, best images, and the elevation of the object; it is about how we create the amazing experience to users with the positive brand reality.

Google has proposed some rules and regulations while adding the material design to application to improvise its standards. Instead of using a palette selection tool that pulls colors to the content of an app, using of material design makes the Android application’s graphic layout more simplified and standard format. To be noted, the material design is not only being used for rectangular or tablet screen; it should also be used for circular watch screen, etc. So if we create a grid, then it precepts all the spacing and should match to all the types of screens, which is a must for apps that are identified everywhere.

Android Material Design

Overall to say, material design is straightforward, clear and brilliant. Because of these dazzling features, it has become an imperative for a broad number of gadgets than any other UI in history.

Goals of Material Design

  • To design the application UI like a magical paper. Let’s say, something that appears like real, appreciable objects.
  • Animations have been pulled to make the experience more lively by safeguarding the maximum amount of content is always visible.
  • With Material Design, Google also determined to robotize the experience for users.
  • Mobile rules are fundamental but touch, voice, mouse, and keyboard are all excellent input methods.

The materials take energy from the users, from their fingers, from their mouse click, their touch and use it to transform and animate.

In material design, software elements are treated as real things. For example, take paper and ink. Every pixel drawn in an application is similar to a dot of ink on a piece of paper. Assume that paper is plain and doesn’t have any color whereas the ink can be of any color. So the content color of a paper depends on the color of the ink. Likewise in Android application, it can be a menu, button or image.

And also the paper can be of any size. It might fill the whole screen, or it might even shrink to small square or round shape. So the ink will not have any restrictions. It will be throughout the paper. It just has to fit inside the paper to be visible. The papers can change its shape, split, move, join and re-size. Likewise, every application made in material design will have all these characteristics.

Principles of Material Design

1.  Material is the metaphor

A material metaphor is a bring together theory of a rationalized space and a system of motion. A metaphor is a figure of speech that specifies flashy effect to one thing by observing another thing. It is open to imagination and magic.

Material Design Principles

2. Surfaces are spontaneous and natural

Surfaces and edges provide visual hints that are familiarized in our knowledge of reality. The use of ordinary material attributes conveys to a primal part of our brain and advice us to quickly understand its need.

Material Design Surfaces

3. Dimensionality supports interaction

The basics of light, surface, and movement are keys to transfer how objects cooperate. Sensible lighting shows bond, divides space, and demonstrate moving parts.

Material Design Dimensionality

4.  One flexible design

A single underlying design system establishes interactions and space. Each device follows a different view of the same fundamental system. Each view is made custom-fit to the size and interaction appropriate for that device. Colors, iconography, hierarchy, and spatial relationships stand constantly.

Material Design Flexible Design

5.  Content is bold, graphic, and wilful

Bold content provides grouping, meaning, and focus. Cautious color choices, edge-to-edge imagery, and intentional white space create captivation and clarity.

Material Design

6.  Color, surface, and iconography highlights actions

User action is all about the significance of experience design. Color in material design is inspired by bold complexion, deep shadows, and brilliant highlights. The whole design is reconstructed by the change of points in the immediate actions.

Android Material Design Color

7.  Users introduce alteration/change

Alterations in the UI extract their energy from user actions. Motion that forces from touch respects and emphasizes the user as the best mover. It means that the widgets or material takes the energy from users’ fingers during the mouse click or on touch and that energy is used to animate to show it as reality.

Android Design User Alteration

8.  Animation is choreographed on a common step

All action takes place in one surrounding. When objects are restructured and transformed, the user will be given with the experience without collapsing the continuity of it.

Android Material Design Animation

9.  Motion provides meaning

Motion is meaningful and convenient. It helps to focus attention and preserves continuity. The following elements assists in material design for apps of Android version 5.0 (Lollipop) or higher.

Android Material Design Motion

Themes

The material theme is defined as,

@android:style/Theme.Material (dark version)

@android:style/Theme.Material.Light (light version)

@android:style/Theme.Material.Light.DarkActionBar

Android Material Design ThemesAndroid Material Design

 

To use the material theme in your apps, customize the color palette as shown below,

<resources>
<!-- inherit from the material theme -->
<style name="AppTheme" parent="android:Theme.Material">
<!-- Main theme colors -->
<!-- your app branding color for the app bar -->
<item name="android:colorPrimary">@color/primary</item>
<!-- darker variant for the status bar and contextual app bars -->
<item name="android:colorPrimaryDark">@color/primary_dark</item>
<!-- theme UI controls like checkboxes and text fields -->
<item name="android:colorAccent">@color/accent</item>
</style>
</resources>

The following example describes how to add material design to a button

styles.xml

<resources>
<!-- Base application theme. -->
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
<!-- Customize your theme here. -->
<style name="MyButton" parent="Theme.AppCompat.Light">
<item name="colorControlHighlight">@color/calbutton_focus</item>
<item name="colorButtonNormal">@color/background_color</item>
</style>
</resources>

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height=" match_parent ">

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:theme="@style/MyButton"
android:layout_gravity="center"
android:text="Click"
android:textAllCaps="true"
android:textColor="@color/white"/>

</LinearLayout>

Cards and Lists

Cards and Lists are the two new widgets in Android with material design styles and animation. To create cards and Lists, RecyclerView can be used, which is introduced from Android version 5.0 (Lollipop). It is an adoption of ListView, which supports various layout types and contributes performance improvements. Part of data can be shown inside the card with a constant look over apps in CardView.

An example shown below demonstrates how to add a CardView in your layout.

 

build.gradle

dependencies {
// CardView
compile 'com.android.support:cardview-v7:23.3.+'
}

activity_card.xml

<android.support.v7.widget.CardView
android:id="@+id/card_view"
android:layout_width="200dp"
android:layout_height="200dp"
card_view:cardCornerRadius="3dp">
...
</android.support.v7.widget.CardView>

 

To use RecyclerView widget in your layout, necessary attribute is shown below,

build.gradle

dependencies {
// RecyclerView
compile 'com.android.support:recyclerview-v7:23.1.1
}

activity_main.xml

<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clipToPadding="false"
android:scrollbars="vertical" />

Android Material Design Cards and Lists

Floating Action Button

Another interesting widget introduced in material design is floating action button.  This button floats on UI in a circular shape with an action attached to it. By default, its behavior is to animate on the screen as an expanding piece of material.

We can also provide shadows and elevation to the buttons. The distance between surfaces and the depth of its shadow signifies elevation. To set the elevation of a view, use the android:elevation attribute in your layouts. The bounds of a view’s background drawable determine the default shape of its shadow.

In addition to the X and Y properties, views in Android material design now have a Z property. This new property serves as the elevation of a view, which concludes the size of the shadow i.e., a view with greater Z values launches bigger shadows.

< android.support.design.widget.FloatingActionButton
android:id=”@+id/my_floatbutton”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android: layout_gravity="top|end”
android: src="@android:drawable/ic_add”
android:background=”@color/white”
android:elevation="5dp" />

14

build.gradle

dependencies{
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
}

activity_main.xml

<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android: layout_width="wrap_content"
android: layout_height="wrap_content"
android: layout_gravity="bottom|end" // position the floating button
android: layout_margin="@dimen/fab_margin"
android: src="@android:drawable/ic_dialog_email"/>

You can also define own background color for floating button using app:backgroundTint. The size of the button can also be defined by using app:fabSize attribute.

Floating Android Material Design

CollapsingToolbarLayout

A new widget called CollapsingToolbarLayout was also introduced from Android version 5.0 (Lollipop). This comes with an amazing animation; whenever a user scrolls up the control provides the fabulous animating effect. According to the Android documentation, CollapsingToolbarLayout is a wrapper for Toolbar which implements a collapsing app bar. It makes the header image collapse into the Toolbar, adjusting its title size and it is designed to be used as a direct child of an AppBarLayout.

To add CollapsingToolbarLayout to your layout, see the following,

build.gradle

dependencies{
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
}

activity_main.xml

<android.support.design.widget.CollapsingToolbarLayout
android:id="@+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleMarginEnd="64dp"
app:expandedTitleMarginStart="48dp"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
.....
.....
</android.support.design.widget.CollapsingToolbarLayout>

Android Material Design Collapse

Conclusion

Google developed material design to bring together the user experience from different Google platforms. Totally, material design made the user interaction smooth, simpler and greater intuitive. When you think about material design, it has so many technologies, which will only create the impression for users while using apps during interactions. The physical world is the very big part of the material design. So all in all, what do you think of Material Design in Android? Don’t you think it’s the best part to unite and enhance the user experience while using the Android application?