Activities & Intents


This post introduces Activities in Android and how Intents are used for any communication between activities or any other application components.

Activities

Activities are the fundamental building blocks of Android applications. An activity is an interface between the screen and the application. Activities, services, any application components must be declared in the AndroidManifest.xml file. If it is not done, the application considers that component of the application does not exist and often runtime exceptions are thrown when the application is being run.

This declaring of an activity, however, does not have to be done manually in the manifest file. But any kind of attributes associated with the activity can be added to the activity explicitly in the AndroidManifest.xml. For instance, an activity can be declared as the launcher activity (the first screen of the application that shows up on our screens as it runs) can be done by adding the line <category android:name="android.intent.category.LAUNCHER"></category> in the corresponding activity element in the manifest.

In any case, if an activity has to be declared manually, it can be done by creating an <activity> element in the manifest file. Next, the name and label of the activity can be specified using android:name and android:label attributes respectively. More can be learned about its attributes at https://developer.android.com/guide/topics/manifest/activity-element.

Communicating with intents

Intents are the glue between activities. Any communication between activities happens via intent. Intent holds the necessary information needed to perform an action. An intent usually has two pieces of information – action and data. In other words, intents carry information that the system uses to determine which component to start plus the information that the recipient component uses to act to perform an action properly

Intents are of two types –

  • Explicit: Explicit intents explicitly mention the component which should be called. The Java class is used as an identifier in explicit intent call.
  • Implicit: In an implicit intent, the action to be performed is specified and data is optional. Based on the type of action and data, the component that fits the most is started by the system. In some cases, if multiple components fit, the user is prompted with possible options and thus the user can decide which component to use to perform the specified action.

Explicit intent example

Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra(Intent.EXTRA_TEXT, "sample text");
startActivity(intent);

In the above example, the EXTRA_TEXT identifier is used as an identifier or any custom string can be used as well. The concept of key-value pairs is used when transmitting data using intents between two components. We use the same key to get the data out as the one we used to put data onto intent. getStringExtra() is used to fetch data from the intent. Intents are not just limited to sending String type data. Any basic Android data types can be transmitted between app components.

Implicit intent example

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://www.google.com"));
startActivity(intent);

In the above example, an intent object is created by specifying ACTION_VIEW as what we want to do. A URL is specified in the data, since the intention is to view the website, the default browser is launched (different data could launch different apps). Intent resolution mechanism operates by matching the best intent from the installed application packages.

Complete running examples of starting a new activity from a current one using implicit intent call and switching between activities using explicit intent can be checked at https://github.com/kamalpreetgrewal/ActivityStarter and https://github.com/kamalpreetgrewal/ActivitySwitcher respectively.

More on activities like storing data persistently, returning results from an activity is coming up in the next post. Keep reading!

Fix MongoError on first connect

The default MongoDb port is 27017. An error occurs sometimes while I am running my Node & ExpressJS application, with the message:

message: 'failed to connect to server [localhost:27017] on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]' }

Several solutions are provided on the internet to fix this. But a lot of them did not work for me. The simplest method I find to fix this on MS Windows is:

1. Open your Command Prompt as administrator.
2. Type > net start mongodb

The mongodb service starts successfully.

Template literals

I have to print a message with values of, say, two variables interpolated or inserted in it. I am talking about JavaScript here. What I do is start single or double quotes, write some part of my message string, close the quotes, insert the variable, start quotes for remaining part of the message and keep going. If the number of variables is more, it’s a pain in the ass. Sometimes one tends up forgetting closing quotes somewhere and then check out the point of error. This can be illustrated as:

var person = {name: "Kamalpreet", age: "24"};
console.log("My name is " + person.name + " and I am " + person.age + " years old.");

This has been simplified by EcmaScript6 (ES6). The third type of quotes, the back-tick ones are used to escape all this fuss. The back-tick quote is used along with $() to contain the variable syntax. An illustration for the same example above is shown below:

console.log(`My name is $(person.name) and I am $(person.age) years old`);

Same output is shown by using both the methods. Latter one is simple and a part of ES6. This is called template literals or template strings. Another point that differentiates template literals is the definition of the string can be spanned across multiple lines without use of linefeed character. For an instance,

console.log(`Hello, my name is 
${person.name} and I am ${person.age}
years old`);

Prior to the introduction of template strings, this would have been done as:

console.log("Hello, my name is " + \
person.name + " and I am " + person.age + \
" years old");

These were few simplifications towards cleaner code introduced in ES6. There are few more which I will write about as I learn.

Some methods of arrays

Iteration of arrays can be done via use of a map function instead of using for loops. Given an array, each element of the array is operated upon. Function creates a new array instead of updating the existing one.

// Multiply each element of oldArray with 3 to create a newArray
var newArray = oldArray.map(function(val) {
    return val * 3;
});

I have to add all numbers in an array. What I have learned since beginning is use a for loop to iterate over the length of an array while adding them to an accumulator variable. Similar operation can be performed using the reduce function. currentElement as the name denotes is the item of the array currently iterated.

// Sum using reduce function with default value of 'sum' is set to '0'
var sum = array.reduce(function(sum, currentElement) {
    return sum + currentElement;
}, 0);

The filter method is used to query arrays and filter out elements depending on the condition specified. This is equivalent to iterating through all elements using for and then using a conditional statement, depending on the results of which the elements are stored in a vector or array or some other data structure. A new array is created when this is used.

// I need only elements that are less than 5 i given array.
var oldArray = [1,2,3,4,5,6,7,8];
var newArray = oldArray.filter(function(val){
    return val < 5;
});
// newArray = [1,2,3,4]

The sort method sorts the elements of the array and the array being operated upon is altered. No copy of the existing array is made. Arrays of strings can also be sorted.

// Sort elements of array in ascending order, 'a' and 'b' are elements being compared at a time
array.sort(function(a, b){
    return a-b;
    // If sorting in descending order, return b-a
});

It is to be noted that a negative value returned implies element ‘a’ is smaller than ‘b’ and hence should be assigned a smaller index. A value greater than 0 implies the larger index value should be assigned to ‘a’ and when equal to 0, means both ‘a’ and ‘b’ are equal.

reverse reverses the elements of the array.

var array = [1,2,3];
var reverseArray = array.reverse()

concat is used to merge the contents of two arrays into one. It takes an array as an argument and returns a new array with the elements of this array concatenated onto the end of the array on which this operation is applied.

var array = [1,2,3];
var concatArray = [4,5,6];
var newArray = array.concat(concatArray);
// newArray = [1,2,3,4,5,6];

I have a string and I want to tokenize it into different elements and save that in an array. split does this depending on the delimiter passed in as argument to this function.

var stringToSplit = "I am learning how to split";
var array = stringToSplit.split(' '); // space is used as delimiter here.

On splitting, array has 6 elements for each word in the string.

Next function is join which joins the elements of the array to form a string.

var hobbies = ["reading", "writing", "drawing"];
var hobbiesStr = hobbies.join(" and ");
console.log(hobbiesStr); // reading and writing and drawing

These are few of the methods available for arrays which ease up performing the corresponding functions without having to iterate and compare or append manually. So JS makes these things easier with the pre-defined functions.

Objects in JS

Objects in JS can be created by:

  1. Use of variables
  2. Use of functions
// table variable                      |              // use of function
var table = {                          |              var table = function() {
    "legs":4,                          |                  this.legs = 4;
    "color":"brown",                   |                  this.color = "brown";
    "material":"wood"                  |                  this.material = "wood";
};                                     |              };

An instance of these objects can be created as:

var myTable = new table();

Arguments can be passed as needed in the constructor with corresponding changes in definition of the constructor. All the variables defined as property of this are public. In order to make a variable private, var keyword is used. Private variables are created to control changes that happen to their values from outside. Functions to modify these values are then defined within the constructor. This is illustrated in Bike object below.

var car = function() {
    var speed = 20;            // private variable

    // public methods below
    this.accelerate = function(paceup) {
        speed += change;
    };

    this.decelerate = function() {
        speed -= 5;
    };

    this.getSpeed = function() {
        return speed;
    };
};

Hour 2 : JS

Continuing learned using boolean values, conditional statements, switch case and use of functions. Everything goes on like we might have learned in some other language. Encountered only a new operator category called the strict equality operator and strict inequality operator.

Strict equality operator uses === instead of the normal == for the equality operator. So is the case for strict inequality operator which uses !== and not !=. These strict comparison operators compare the types of values being compared unlike the normal comparison operator that coerces the data type and checks only the values. No more differences than standard practices of these operators and conditionals!

Hour 1 : JS

Having not used JS even to a novice level, I had planned to learn it and create something substantial. And today was the first day to executing the plan. I will brief out the things I learned in the sequence on a map.

undefined, null, boolean, string, number, symbol and object are the 7 data types. Variables are declared with var keyword and accessing the value of a variable that has not been initialised returns an error of undefined type or sometimes a NaN. Names of variables can have alphanumeric characters, $ or _ but not a space or cannot start with a number. JS is case-sensitive. Arithmetic operations work on universal principles, so nothing new there.

Since double quotes are used to encase string literals, they have to be escaped when one wants them to be a part of the literal. However, this can be avoided by using single quotes to enclose the literal and vice-versa. Square brackets with zero based indexing is used to access characters in a string. Strings in JS are immutable and hence have to be defined all over instead of manipulating only the characters one wishes to modify. For instance,

var myStr = "Jello World";
myStr = "Hello World"; // This has to be fixed all over instead of accessing the first character using myStr[0].

Multi-dimensional arrays can be created by nesting several elements as part of a single element. An example:

var myArr = [[1, 2], [3, 4]];
var a = myArr[1,1]; //This assigns value of 4 to variable <em>a</em>.

Few operations to update arrays are:

  1. push() – Appends data to end of the array.
  2. pop() – Pops an element from end of the array.
  3. shift() – Pops first element of the array.
  4. unshift() – Adds element in the beginning of the array.

function keyword is used to define a function which is called via its name and arguments, if it requires any. Variables defined inside the function have local scope and those outside have the global scope. The value of the global variable is overridden by the local variable, that is a rule, ofcourse when both have same names. Global variables can be defined without the keyword var which is not considered a good practice because it comes with consequences which I have to determine yet.

This is all I grabbed in the 1 hour today, à bientôt!

(Im)Mutable

Mutable and immutable are common English words. Something that can be changed is mutable and that cannot be is immutable. I came across these few years ago but it was an over-head-flow then. There are two classes in Java String and StringBuilder and both suffice almost the same purpose with some additional features in the latter. So I explored the difference in terms of their performance and genesis and came across these keywords.

The meanings of these words are similar in other programming languages. Here I will take the instance of Java only. So coming to the class String, it is immutable and the StringBuilder is mutable.

Considering the mutable objects, their content can be changed post construction. Performing any manipulation on the mutable object will over-write the content in the object initially created. Note no new object is created as most of us normally expect. Let us create a StringBuilder like:

StringBuilder sb = new StringBuilder();
sb.append("Kamalpreet");
sb.append("Kaur");
sb.append("Grewal");

In the memory heap, this will be only one object looking like:

The reference to the StringBuilder points to the same object. However such is not the case for immutable objects like String. Let us create like below:

String s = "Kamalpreet";
s.concat("Kaur");
s = s.concat("Grewal");

Due to immutable behavior of String class, the new results will be stored in a new object. Note the third line in the code above. If the assignment is not done, the reference will continue to point to the initial string with value Kamalpreet.

This all applies to all other mutable and immutable objects in different programming languages.

Why is reading so important?

Why is reading so important? by Dushka Zapata

Answer by Dushka Zapata:

Imagine a room within four brick walls.

It’s comfortable and you have what you need.

But it has no windows.

This room is an ordinary life. Acceptable, but limited.

Reading is like creating a window.

A window means a breeze. It means light, and the sun shining in, and a view.

The view can be anything, anything you want. A beach, the sky, a story, history; soldiers ready to raise the alarm, a boy in a cabin, a beautiful woman with a long yellow dress, a tiger, desperate and hungry, trapped on a life raft.

You can look out at whatever you wish; and you can learn. Pick what you want to learn about: the entirety of world knowledge is at your fingertips.

The more you read the more you open windows in the brick walls until you are left with no bricks. Just a vast expanse full of everything you have chosen.

Now remove your favorite story.
Pack up the soldiers and say goodbye to the woman and watch the tiger and the life raft drift away. 
Shut out the light.
Close off the breeze.
Replace every brick.

Return to your life, acceptable, circumscribed and finite.

This is a life without reading.

Now, you ask, am I saying reading is better than real life?
Is it better to live, or is it better to read?

And I ask you: why should you be without either?
 
My answer is – both. Pick both. Open all the windows.

Why is reading so important?