Motion in android

So earlier this year I attended a talk where the speaker wanted to introduce us to meaningful motion in android apps and he convinced us to use this in our apps as well. Motion came in with Material design, actually not really came but became popular with Material design and since google has added the same kind of motions to their apps as well, developers have started using it. I love motion, not only does it boost engagement but it’s instantly noticeable. Think of the apps you use that feature motion design and how pleasing, satisfying, fluent and natural they feel to experience. Eg. Zomato, Play music etc. Now think of some apps that don’t use any kind of motions and you’ll realise they look a bit boring and you as users will always prefer apps with some kind of motion. Touch So firstly let’s discover the feedback on touch. It helps to communicate to the user in a visual form that some interaction has been made. But also keep in mind that this animation should be enough for them to gain clarity and encourage further explorations and not distract them. For adding backgrounds you can use the following : ?android:attr/selectableItemBackground — Show a ripple effect within the bounds of the view. ?android:attr/selectableItemBackgroundBorderless — Show a ripple effect extending the bounds of the view. View Property Animator Introduced in API 12, this allows us to perform animated operations (in parallel) on a number of view properties using a single Animator instance Some of the parameters that can be added to a view are as follows : alpha() -Set the alpha value to be animated to scaleX() & scaleY() — Scales the view on it’s X and / or Y axis translationZ() — Translates the view on its Z axis setDuration() — Sets the duration of the animation setStartDelay() — Sets the delay on the animation setInterpolator() — Sets the animation interpolator setListener() — Set a listener for when the animation starts, ends, repeats or is cancelled. Now let’s write some code on how to do this on a button for example: mButton.animate().alpha(1f) .scaleX(1f) .scaleY(1f) .translationZ(10f) .setInterpolator(new FastOutSlowInInterpolator()) .setStartDelay(200) .setListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }) .start(); Note : Use ViewCompat class to implement the ViewPropertyAnimator from Android API version 4 and up Object Animator Similar to the ViewPropertyAnimator, the ObjectAnimator allows us to perform animations on various properties of the target view (both in code and XML resource files). However, there a couple of differences: The ObjectAnimator only allows animations on a single property per instance e.g.Scale X followed by Scale Y. However, it allows animations on a custom Property e.g. A view’s foreground colour. Her we need to set the evaluator, set the delay and call start(). private void animateForegroundColor(@ColorInt final int targetColor) { ObjectAnimator animator = ObjectAnimator.ofInt(YOUR_VIEW, FOREGROUND_COLOR, Color.TRANSPARENT, targetColor); animator.setEvaluator(new ArgbEvaluator()); animator.setStartDelay(DELAY_COLOR_CHANGE); animator.start();} Interpolators An Interpolator can be used to define the rate of change for an animation, meaning the speed,…

Continue ReadingMotion in android

Using Partial in Handlebars and Reusing Code

Open Event Webapp uses handlebar partials for optimizing code. We can reuse a template using Handlebars partial. How to use Handlebars partial ? To use Handlebars partial, we have to follow some easy steps: Step 1: In the .hbs file containing code, register your partial by using function Handlebars.registerPartial  Handlebars.registerPartial('myPartial', '{{name}}') Step 2: Calling the partial {{> myPartial }} In Open-Event Webapp we have made partials for common templates like navbar and footer. 1. // Navbar template (navbar.hbs) <!-- Fixed navbar --> <nav class="navbar navbar-default navbar-fixed-top"> <div class="container"> <div class="navbar-header navbar-left pull-left"> <a class="navbar-brand" href="{{ eventurls.main_page_url }}"> {{#if eventurls.logo_url}} <img alt="{{eventurls.name}}" class="logo logo-dark" src="{{ eventurls.logo_url }}"> {{else}} {{ eventurls.name }} {{/if}} </a> </div> <div class="navbar-header navbar-right pull-right"> <ul style="margin-left:20px" class="nav navbar-nav pull-left"> {{#sociallinks}} {{#if show}} <li class="pull-left"><a href="{{link}}" style="padding-right:0; padding-left:0;margin-left:15px"><i class="fa fa-lg fa-{{icon}}" aria-hidden="true" title="{{{icon}}}"></i></a></li> {{/if}} {{/sociallinks}} </ul> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse" style="margin-left:1em;margin-top:1em;"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <div class="hidden-lg hidden-md hidden-sm clearfix"></div> <div class="collapse navbar-collapse"> <ul class="nav navbar-nav navbar-right"> <li class="navlink"><a id="homelink" href="index.html">Home</a> {{#if timeList}} <li class="navlink"> <a id="schedulelink"href="schedule.html"> Schedule</a> </li> {{/if}} {{#if tracks}} <li class="navlink"> <a id="trackslink" href="tracks.html">Tracks</a> </li> {{/if}} {{#if roomsinfo}} <li class="navlink"> <a id="roomslink" href="rooms.html">Rooms</a> </li> {{/if}} {{#if speakerslist}} <li class="navlink"> <a id="speakerslink" href="speakers.html">Speakers</a> </li> {{/if}} </ul> </div> </div> </nav> //Compiling Template by providing path 2. const navbar = handlebars.compile(fs.readFileSync(__dirname + '/templates/partials/navbar.hbs').toString('utf-8')); // Register Partial 3. handlebars.registerPartial('navbar', navbar);

Continue ReadingUsing Partial in Handlebars and Reusing Code

PIL to convert type and quality of image

Image upload is an important part of the server. The images can be in different formats and after applying certain javascript modifications, they can be changed to different formats. For example, when an image is uploaded after cropping in open event organizer server, it is saved in PNG format. But PNG is more than 5 times larger than JPEG image. So when we upload a 150KB image, the image finally reaching the server is around 1MB which is huge. So we need to decide in the server which image format to select in different cases and how to convert them.

(more…)

Continue ReadingPIL to convert type and quality of image

Templating with Handlebars and Nodejs

There are many frameworks present today that does DOM manipulation. But, DOM manipulation is useful only with simpler Javascript apps. If we want to deal with huge amount of data, we will need to take the support of templating. One of the templating libraries is Handlebar.js. Handlebars.js is the lightest and one of the fastest templating libraries I have worked with. How to work with Handlebars ? Handlebars can be said as the superset of Mustache templating language. In Open-event-web app, Handlebars is used along with Node.js. 1. To install Handlebars npm install handlebars 2. To include handlebars const handlebars = require('handlebars'); const fs = require('fs-e'xtra); 3. To compile a file ( Extension .tpl or hbs) const tpl = handlebars.compile(fs.readFileSync(__dirname + '/templates/schedule.hbs').toString('utf-8')); fs.writeFileSync(distHelper.distPath + '/' + appFolder + '/tracks.html', tpl(jsonData)); Here jsonData is the JSON Array of objects provided to the template. An example of a .hbs templating file can be : <div class="track-names col-md-2"> {{# tracks}} {{#if title}} <ul class="title-inline"> <li style="background-color:{{{color}}}" class="titlecolor"></li> <li>{{title}}</li> </ul> {{/if}} {{/tracks}} </div>    

Continue ReadingTemplating with Handlebars and Nodejs

AngularJS structure and directives

Today I am going to tell you how to build a well worked Angular JS structure, as well as to be able to maintain your app's elements correctly. It's a basic and most important thing to learn and remember before you start building your own website or app because in the early phases of a project the structure doesn't matter too much, and many people tend to ignore it, but in the long term it will affect code maintainability. It also helps you to develop it quicker and solve bugs without any additional troubles. I must admit that I was one of them who  had made this mistake and ignore AngularJS correct structure. The thing is that I had not known how to build Angular JS app correctly before I started coding CommonsNet, and I wanted to start and provide a real outcome as quickly as possible. But unfortunately my mistake has stoped me later. I have realised it this week while implementing a quite simple feature - adding HTML elements dynamically. It turned out that I had a trouble while adding them. I had't known that it's better not to manipulate DOM elements in Controllers, but instead do it in directives. Let me to explain it step by step from lessons I've learned while refactoring CommonsNet code structure. Please note that I'm just sharing my experience in building rather a small project and I'm covering only a small part of that subject, so some of these tips may be first - useless if you want to build an extended one, and then - not enough if you want to learn more. I recommend you to find further resources. AngularJS Structure First of all please see at AngularJS structure provided below. It's a very basic structure, but it' is important to have in mind that you should follow that pattern while developing your own app. If you want to have an order in your files you should seperate them by directories and create different ones like: controllers, directives, services, js and views. This structure makes it very easy for the reader to visualize and conceptualize the concepts you are covering. My CommonsNet structure differs a bit because I have one main js directory, and all subdirectories like directives, controllers and services  inside it. I think it's also an acceptable solution. Imagine that I hadn't had any directives or services directives' files before last Wednesday... Then,  it's also recommended to put index.html at the root of front-end structure. The index.html file will primarily handle loading in all the libraries and Angular elements. Next, controllers are main part of AngularJS apps. It always happens that developers when starting out tend to put too much logic in the controllers. It's a bug. Controllers should never do DOM manipulation or hold DOM selectors, that's where we use directives and ng-model. Likewise business logic should live in services, not controllers. Data should also be stored in services, except where it is being bound to the $scope. Services are singletons that persist throughout the lifetime…

Continue ReadingAngularJS structure and directives

Using the new Awareness API

Google released the new Awareness API for everyone, a suite of signals concurring to gives the developer the context in which our user is, all as part of the Play Services 9.2.0, already available on Android devices around the globe. This library combines 7 different feeds managing both the battery drain and the used memory, providing us with data such as user location, weather, time, headphones connection status, places, nearby beacons and currently performing activity. INTRO The Awareness API comes with two different versions, one is a callback based one (Fence API) and the other one is a polling based one (Snapshot API): while the first one will notify us when the conditions we specified are met, the second expects us to query the suite for the data from a unified interface. There are 7 kinds of context that we can work with in Awareness API such as Time — Local time at current user’s location Location — Latitude/Longitude Place — Places around user Activity — Detected user activity (biking, walking, running, etc.) Beacons — Check nearby beacon(s) Headphones — Are headphones plugged in? Weather — Current weather conditions Now the Two set’s of API’s : Snapshot API — Allows you to “request an information based on user’s context” as listed above. Fence API — Allows you to “receive a signal when user’s context has changed and reaches the condition” through callback function, for example, if user moves closed to the specific coordinate with headphones plugged in, Fench API will call the registered BroadcastReceiver and let you do your job. Getting started Create a project in https://console.developers.google.com (or in case you already have one, you can use it instead) And then browse to API Manager page and search for Awareness and click at Awareness API and Click Enable and wait until it finishes enabling 3. Go to Credentials tab and click at Create credentials -> API key -> Android key. Enter the name you project, for example, Android key and click Create (or if you have already created Android key previously, you could skip this step and use the existed one) 4. Add dependency in build.gradle compile 'com.google.android.gms:play-services-contextmanager:9.2.0' 5. Open AndroidManifest.xml file and add meta-data to <application> tag like this: <meta-data android:name="com.google.android.awareness.API_KEY" android:value="YOUR_KEY" /> <meta-data android:name="com.google.android.geo.API_KEY" android:value="YOUR_KEY" /> <meta-data android:name="com.google.android.nearby.messages.API_KEY" android:value="YOUR_KEY" /> We also need to add permissions for this: 6. Open AndroidManifest.xml <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION" /> Now we come to the actual java code. open your activity and initialise the GoogleApiClient in onCreate() private GoogleApiClient mGoogleApiClient; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_layout); mGoogleApiClient = new GoogleApiClient.Builder(this) .addApi(Awareness.API) .build(); mGoogleApiClient.connect(); } So this ends the setup part. Now we move on to the actual data retrieval from the API. Accessing Snapshot API Awareness.SnapshotApi.getDetectedActivity(mGoogleApiClient) .setResultCallback(new ResultCallback<DetectedActivityResult>() { @Override public void onResult(@NonNull DetectedActivityResult detectedActivityResult) { if (!detectedActivityResult.getStatus().isSuccess()) { Log.e(TAG, "Could not get the current activity."); return; } ActivityRecognitionResult ar = detectedActivityResult.getActivityRecognitionResult(); DetectedActivity probableActivity = ar.getMostProbableActivity(); Log.i(TAG, probableActivity.toString()); } }); This will return the most probable activity done by the user. We can get a particular activity like walking, running, driving as well by integers defined below public…

Continue ReadingUsing the new Awareness API

Integrating Travis CI and Codacy in PSLab Repositories

Continuous Integration Testing and Automated Code Review tools are really useful for developing better software, improving code and overall quality of the project. Continuous integration can help catch bugs by running tests automatically and to merge your code with confidence. While working on my GsoC-16 project, my mentors guided and helped me to integrate Travis CI and Codacy in PSLab github repositories. This blog post is all about integrating these tools in my github repos, problems faced, errors occurred and the test results. Travis CI is a hosted continuous integration and deployment system. It is used to build and test software projects hosted on github. There are two versions of it, travis-ci.com for private repositories, and travis-ci.org for public repositories. Read : Getting started with Travis CI Travis is configured with the “.travis.yml” file in your repository to tell Travis CI what to build. Following is the code from '.travis.yml' file in our PSLab repository. This repo contains python communication library for PSLab. language: python python:   - "2.6"   - "2.7"   - "3.2"   - "3.3"   - "3.4" # - "3.5" # command to install dependencies # install: "pip install -r requirements.txt" # command to run tests script: nosetests With this code everything worked out of the box (except few initial builds which errored because of missing 'requirements.txt' file) and build passed successfuly :) :) Later Mario Behling added integration to FOSSASIA Slack Channel. Slack notifications Travis CI supports notifying  Slack channels about build results. On Slack, set up a new Travis CI integration. Select a channel, and you’ll find the details to paste into your '.travis.yml'. Just copy and paste the settings, which already include the proper token and you’re done. The simplest configuration requires your account name and the token. notifications: slack: '<account>:<token>' notifications:   slack: fossasia:***tokenishidden**** Import errors in Travis builds of PSLab-apps Repository PSLab-apps repository contains PyQt bases apps for various experiments. The '.travis.yml' file mentioned above gave several module import errors. $ python --version Python 3.2.5 $ pip --version pip 6.0.7 from /home/travis/virtualenv/python3.2.5/lib/python3.2/site-packages (python 3.2) Could not locate requirements.txt. Override the install: key in your .travis.yml to install dependencies. 0.33s$ nosetests E ====================================================================== ERROR: Failure: ImportError (No module named sip) The repo is installable and PSLab was working fine on popular linux distributions without any errors. I was not able to find the reason for build errors. Even after adding proper 'requirements.txt' file,  travis builds errored. On exploring the documentation I could figure out the problem. Travis CI Environment uses separate virtualenv instances for each Python version. System Python is not used and should not be relied on. If you need to install Python packages, do it via pip and not apt. If you decide to use apt anyway, note that Python system packages only include Python 2.7 libraries (default python version). This means that the packages installed from the repositories are not available in other virtualenvs even if you use the –system-site-packages option. Therefore I was getting Import module errors. This…

Continue ReadingIntegrating Travis CI and Codacy in PSLab Repositories

Twitter Section Using loklak webtweets

In Open event web app, the user can provide URL of social links such as Twitter, Facebook etc in the event.json file inside the ZIP. The previous functionality was to use Twitter API and to generate a timeline showing the tweets of the twitter URL mentioned in event.json by user. But, it can be done by following another approach which reduces the third party dependency i.e Loklak-webtweets. I have implemented the twitter section using loklak webtweets which can be done very easily. Step 1:  Including necessary files from loklak-webtweets repository inside index.html. You can find them in js/ folder of this repository. <script src="./dependencies/jquery.min.js"></script> <script src="./dependencies/bootstrap.min.js" type="text/javascript"></script> <script src="./dependencies/loklak-fetcher.js" type="text/javascript"></script> <script src="./dependencies/tweets.js" type="text/javascript"></script>   Step 2:  Specify the data source in HTML from which twitter data will be fetched. Here I have extracted the last word from the twitter URL provided by the user and passed it to HTML. const sociallinks = Array.from(event.social_links); var twitter =""; sociallinks.forEach((link) => { if(link.name.toLowerCase() === "twitter") { twitter = link.link; } }) const arrayTwitterLink = sociallink.split('/'); const twitterLink = arrayTwitterLink[arrayTwitterLink.length - 1]; const urls= { twitterLink: twitterLink, tweetUrl: twitter, }; This code will search twitter link in social links array present in event.json and get its last character which will be provided to data-from and data-query attribute of HTML. <section class="sponsorscont"> <div class="tweet-row"> <div class="col-sm-12 col-md-12 col-xs-12"> <i class ="social_twitter fa fa-twitter"></i> <div class="tweets-feed" id="tweets" data-count=50 data-query=" {{{eventurls.twitterLink}}}" data-from="{{{eventurls.twitterLink}}}"> <div class="arrow-up"></div> <p id="tweet" class="tweet"> Loading... </p> <span style="margin-bottom: 20px;" id="dateTweeted"></span> <p>Follow<u> <b><a href="{{eventurls.tweetUrl}}"/> @{{eventurls.twitterLink}}</a> </b></u> for more updates</p> </div> </div> </div> </section> Step 3 : Now we just need to add styling so that it looks decent. For that, I have written some SASS. .tweets-feed { color: $black; line-height: 30px; font-size: 20px; transition: opacity 0.2s linear; margin-bottom: 20px; height: 100px; a { color: $black; text-decoration: underline; font-weight: 700; } #dateTweeted { font-size: 15px; display: block; } } .tweet-row { padding: 0 80px; margin-bottom: 80px; .social_twitter { font-size: 60px; margin-bottom: 12px; } } The output from the above code is a well designed Twitter section fetching tweets from the URL provided as a string in event.json by user.  

Continue ReadingTwitter Section Using loklak webtweets

Handling data in android

So this week I was working with getting some data from the sqlite database in android and someone who was a beginner in android also asked me to help him with the same. I asked him what he knew and he said that even after reading up a lot he wasn’t able to figure out what exactly to do with the data he wants to save and use in his app. I have seen that this is a problem with a lot of people starting to develop android apps. So, I decided to write a blog on how can you handle your data in your android apps. Most of the android apps need to save data even if only to save some user preferences. So primarily there are 3 ways to save your data : In form of key values (SharedPreferences) Reading/Writing to files Writing to a database So let’s go step by step. When we need to store just some preferences of the users like if they want notifications or what kind of theme they want : light or dark etc. So basically if we want to store a key value in the persitant storage of the app we can do that using SharedPreferences. To use sharedpreferences, we initialise the sharedpreference object like SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); in oncreate and cache it. Then we just need to add or retrieve what we want using this cached SharedPreferences object. To Add a key value pair : sharedPreferences.edit().putString("someKey", "someValue").apply(); Also you can put all kinds of stuff here. For example right now we added a string with key “someKey” and Value “someValue”. We can also add Booleans, Floats, Ints, Longs, StringSets etc. To retrieve the same value we do something like this sharedPreferences.getString("someKey", "DefaultValue"); Now if you want some logs or some values that can be exported and sent to your server, you should write them to files and maybe read some json inputs etc. as well. Basically android has a File system similar to other platforms. All android devices have two file storage areas : “Internal” and “external” storage. The difference between them is as follows : Internal : Always available Files saved here are accesible by only your app When user uninstalls the app, system removes all your app’s files from internal storage Best to use this when you want to be sure that neither the user nor the other app’s can access your files External : It’s not always available because user can mount external storage as USB storage and remove it as well It’s readable by anything(Other apps, users etc.) When you uninstall, system removes your app’s files from here only if you save them in the directory from getExternalFilesDir() Now to read and write files, you need extra permissions android.permission.WRITE_EXTERNAL_STORAGE android.permission.READ_EXTERNAL_STORAGE So now let’s get down to it. How do I save and read files in my app? You first initialise the File object File file = new File(context.getFilesDir(), filename); This will create a file with filename in the internal storage. For external…

Continue ReadingHandling data in android

Responsive Image Overlay

Image overlay is a very common concept in front-end development. It is easy to implement but difficult when we deal it with different screen sizes, where we need to cover the image with the overlay each time the screen size is changed. I have gone through various blog posts when I need to implement the same for Open-event webapp and researched a solution that works for all screen sizes without any media query. How to add an overlay to an image ? If we need four images in a single row nearly 300*300px.  The code below shows the markup. image-holder : The parent class to take the image and overlay inside it. background-image: This class takes image source. responsive-overlay: This is the key point to make it responsive. Responsive-overlay contains a class hover-state to add overlay absolutely and a class social-links. social-links: It adds content to hover-state.   <div class="image-holder"> <img class="background-image" alt="" src=""> <div class="responsive-overlay"> <div class="hover-state text-center preserve3d"> <div class="social-links vertical-align"> </div> </div> </div> </div> The styling is written with SASS in .scss file as shown below. //overlayimage and backgroundshade can be set in config.scss .image-holder { position: relative; overflow: hidden; margin-bottom: 12px; .background-image { height: 300px; width: 300px; display: block; margin: 0 auto; background-color: $background-shade; } .responsive-overlay { @include responsiveoverlay; .preserve3d { height: 300px; } .hover-state { @include hoverstate; height: 300px; width: 300px; } @mixin responsiveoverlay { height: 100%; position: absolute; top: 0; width: 100%; } @mixin hoverstate { background: $overlayimage; display: block; height: 300px; left: 0; margin: 0 auto; opacity: 0; position: relative; top: 0; -moz-transition: all 0.3s ease-out; -webkit-transition: all 0.3s ease-out; transition: all 0.3s ease-out; width: 300px; z-index: 2; } This code will work for responsiveness as well. The main catch here is the responsive-overlay class which is made 100% in width but set to position absolute. The images which are 300 * 300 px in size will take an overlay of the same size because of hover-state class. Instead, if we adjust sizes of images in small screens the above code will adjust overlay on the image automatically. Like, on tablets we can have an overlay like this. And on mobile screen output is like that : Conclusion Responsiveness is easy if we follow correct concepts. Here, the concepts of absolute and relative positioning in CSS have done the magic. Now we can play by adding different contents and effect on hover following the same basics.

Continue ReadingResponsive Image Overlay