Sunday, August 28, 2016

Mobile or Web (or both)?

Many beginning developers are questioning themselves about the area of the software development they want to build their career in and I was one of them (I'm still beginning, but I did choose already).

Today there are several major areas you can focus on.

  1. Operation Systems (Windows, Android, iOS etc.) - here you would write pretty low-level code that would handle interaction with the hardware.
  2. Game Developing - could be broken down into many subcategories, such as game engines, UI in games, gameplay etc. 
  3. Mobile - building apps for mobile devices running Android, iOS, Windows Phone etc. This area is growing really fast nowadays because of new mobile devices. Android is embedded in TVs, cars, VR and IoT (I personally think, that someday Android development would be one of these major areas of software development itself).
  4. The Web is growing just as fast as mobile, and the reason for it is online clouds. Almost everything is going to the web, it's convenient, you can access it almost everywhere, and in developed countries, it's fast and cheap. 
  5. Data science - this one is about big data analysis, machine learning and sometimes artificial intelligence. Note that it's actual science. You would be learning much theory before doing something actually working, unlike the other categories.
  6. Embedded software - this is low-level software that is built for one particular product, for example, for a digital camera. This category got a second breath with the emergence of the Internet of Things.
There are more, but it could take a whole post to list them all. If you think there is a category that definitely should be on this list, please drop a comment I will include it.

Today I want to talk about the two most popular (for now) categories: mobile and web development.

Mobile VS Web


Some people think that there is some kind of competition between these two. And they are right, in some way.

Mobile and web developers always try to make the experience on their platform feel better that on the other. 

Which is better, create a mobile app or just make an ada``ptive design of web version for mobile devices?

What is great about this competition is that it's healthy, it makes both platforms create new ways of interacting with the users, enchant them, simplify their life, and make them amazing.

I even heard the opinion that you should both web and mobile. Which, as I think, is wrong because if you want to build the career it's better to focus on something instead of picking all into sight.

So if you want to be a developer what should you pick? Unfortunately, it's not that straightforward but let's look at advantages and disadvantages of every category and I hope it will help you to decide on your own.

Web Development

Advantages Disadwantages
Cross-platform. You can run your app on every device that has a web browser. Runs only with browser so if you want to build offline app using web technologies (e.g. Atom) you need to ship a browser with it
A huge developers community You can only use JavaScript and it's kinda slow so you limited in optimization.
Fast development cycles (write->build->test->repeat) You do not have the computer resources control unless you're using some framework for building offline apps

Mobile Development

Advantages Disadwantages
Over a billion of people have a mobile phone There are two major platforms and you should choose only one (while it's better to have your app on both)
A huge developers community as well (for Android and iOS). Slow development cycles.
Full control over resources. You should care about optimal resources usage.
You can use native low-level processing (for example NDK) to optimize your app

For me, mobile is more convenient. And I don't mean that Web is worse, it should be your choice.

If you want to build something more interactive it's better to learn mobile, if you want your apps to be accessible from anywhere and anything that has a browser it's better to get to Web development.

I hope I helped you to choose the direction to go.

See you in the next one!

Sunday, August 21, 2016

The Boy Scout Rule in Coding


The Boy Scout Rule is the simple rule that can solve a huge problem of software development within a team.

It states: "Always leave the campground cleaner than you found it". Sounds pretty simple, right?

But, despite its' simplicity, not every developer follows this rule (me neither sometimes).

Sometimes, it's just kinda hard to take responsibility for someone else's code. I tell myself: "If someone else made that mess, why I should even work with it?".

But undoubtedly, it's way better for everyone to take care of the code you working on with a team. All the same, we are programming in the high-level languages and those were made for people who work with machines, not the machines themselves.

What is clean code?

To keep the code clean you obviously should know what clean code is and what it takes to write one.

Let's formulate some qualities of the clean code.

1. Clean code is focused.

You don't want your methods to consist of various blocks of unrelated code. You want one particular method to do one particular thing.

First of all, it's easier to remember what the method does and if it has a good name (which is a quality of clean code too) then the user of this method don't even need to know what it does behind the scenes, he can use it out of the box.

But you can say, what if my method should do many things behind the scenes? The key to handling this problem is an abstraction. 

For example, take the Glide library which I discussed in one of my posts Image Loading With Glide. To load an image you should handle HTTP connection, media decoding, memory and disk caching etc. But Glide makes it look like one thing, loading an image.

2. Clean code is expressive

I already talked about it when mentioned that method should have a good name.

Good naming can make your code self-documenting and make documentation less important and in some cases even redundant.

Let's think of a simple example.

  int method(int[] array) {
    if (array == null || array.length < 0)
      return 0;

    int integer = array[0];
    for (int number : array)
      if (number < integer)
        integer = number;
    return integer;
  }

It's pretty easy to determine what this code does, but it would be even easier if we choose better names for the method and variables.


  int min(int[] numbers) {
    if (numbers == null || numbers.length < 0)
      return 0;

    int currentMin = numbers[0];
    for (int candidate : numbers)
      if (candidate < currentMin)
        currentMin = candidate;
    return currentMin;
  }

I just changed the names, nothing else, it does the same thing (and now even the name implies that it searching the minimum in the array). But now it looks much much better.

To be honest, when I was writing the example of bad naming, I made a mistake. I wrote `number > integer instead of `number < integer` and noticed it only when I changed the names. In such a simple procedure, such a huge mistake just because of bad naming. Imagine what can happen when you work on a huge system!

3. Clean Code is minimalistic

Some studies say that it's better to keep your classes and procedures small. 

For classes, there is a magical number that states how many public methods it should have this number is 7. 7 public methods per class makes it easy to remember all the responsibilities of the class. But it doesn't mean, of course, that every class should have only 7 methods, just keep this number close to it.

For methods, there is no concrete number. Robert "Uncle Bob" Martin in his book "Clean Code" says
The first rule of fucntions is that they should be small. The second rule of functions is that they should be smaller than that. Functions should not be 100 lines long. Funcions should hardly ever be 20 lines long. 
While Steve McConnell in "Code Complete" says the following
The routine should be allowed to grow organically up to 100-200 lines, decades of evidence say that routines of such length no bore error prone than shorter routines.
Some people (including Steve McConnel) say that a method should fit the screen without scrolling which is, in my opinion, is the good estimate, despite the fact that everyone has different screens.

I personally think that you should break down the method as soon as you find yourself trying to remember what does some part of the method do. Probably, when someone will look at this part he won't understand it, so it's better to replace it with well-named procedure.

These are in my opinion are top 3 qualities of clean code. There are more of course and you can find all of them in already mentioned books: Code Complete by Steve McConnell and Clean Code by Robert C. Martin.

Now when you know what clean code is you can start following The Boy Scout Rule of coding and make your and your co-workers' live easier. Sometimes it would be easy as renaming some variables. Sometimes it would require changes in the architecture of the software but it always worth it because you are the one who will work with this code.

Now let's make our code a better place! Maybe there is a badge for it ;)


Sunday, July 31, 2016

Image loading with Glide


Image loading seems like an easy task at the first glance but as every task, it has its' own caveats.

First of all, you probably want to do this asynchronously because you don't want to flood your main thread with that kind of tasks.

Then, you want to cache images so you don't load them every time your activity of fragment resumes.

You need to handle error cases when the network is not available or server is sending you garbage or doesn't send anything at all. If you don't do this it will definitely harm the user-experience.

After all, you probably need to do some pre-processing steps before showing the image to the user such as cropping, resizing, reversing etc. Also, it would be convenient to have an easy way to set an image in an ImageView.

You may ask: "Why do you think that you know what I need and want?". The answer is that you're not alone. Android developers already made tons of apps that use pictures from the network.

And what happens when many developers are facing the same problem? Right, they make (most likely an open source) library.

The libraries

There are many libraries that solve the problem and, on the high level, they do it pretty much similar. For example, if you just want to load the image in the image view you will write something like this

String imageUrl 
    = "http://i1.kym-cdn.com/photos/images/facebook/000/002/109/orly_owl.jpg";
LibraryClass.with(context).load(imageUrl)
    .into(imageView);

No matter what concrete library you use (except it's something really exotic).

The most popular ones are Picasso, ImageLoader, Glide, and Fresco (made by Facebook). It's hard to say which one is the best one and developers say that picking one is the matter of taste. But I think that it's worth to mention that Gilde and Fresco support gif loading and Glide is recommended by Google.

Facebook engineers also say that Fresco is more optimized in terms of memory usage but when considering this note that Fresco is not as well tested as Picasso, Glide, and ImageLoader (which is the oldest one).

To show examples I will use Glide because I have been working with it.

Image Loading

First of all, to use Glide you need to add a Gradle dependency.

compile 'com.github.bumptech.glide:glide:3.7.0'

There are several ways you can use an image in your app. You can load it directly in an image view or save its' bitmap to use it anywhere else, for example, in a notification.

Let's consider first use-case. To simply load an image in an image view you must write exactly the code above except you must change LibraryClass to Glide that is it will look like this 

Glide.with(requester).load(imageUrl)
    .into(imageView);

I intentionally changed context to requester to emphasize that it could be not context. with() methods accepts Activity, Context, or Fragment as an argument which in my opinion is very handy.

There are many small features that will make UX of your app much better. For example placeholders, you definitely don't want your user to watch on the empty screen while your images are loading, your app should indicate that it's loading something to show to the user. Placeholders are the great way to do that. It can be a message that says that image is loading, loading animation or simple gray pane that shows that something should be there.

And placeholders are really well implemented in Glide (as well as other libraries) and it's easy to use. That's how it's done.

Glide
    .with(requester)
    .load(imageUrl)
    .placeholder(R.drawable.image_placeholder)
    .into(imageView);

You can show error image (the image that should be shown if something went wrong) using the same way

Glide
    .with(requester)
    .load(imageUrl)
    .error(R.drawable.image_error)
    .into(imageView);

In both of these methods, you can pass a Drawable object as the argument instead of resource id.

The second feature that can enhance UX of your app is animations. When your image appears out of nowhere in a blink of an eye it's kinda little disturbing and doesn't look like things act in the real world, which is a violation of Material Design guidelines.

In Glide as well as many other libraries there is a built-in way to animate the appearance of your images. In Glide you can do this using crossFade() method.

Glide
    .with(requester)
    .load(imageUrl)
    .placeholder(R.drawable.image_placeholder)
    .error(R.drawable.image_error)
    .crossFade()
    .into(imageView);

Also, you can pass an int as an argument to set the duration of the fade animation.

Load as Bitmap

To load image as bitmap you just need to use method asBitmap() set the constraints and use get() like this


Glide
    .with(requester)
    .load(imageUrl)
    .asBitmap()
    .placeholder(R.drawable.image_placeholder)
    .error(R.drawable.image_error)
    .into(width, height)
    .get();

Note that get() should be used only in a background thread which, in my opinion, is fair. If you don't use your image in UI why would you download it in UI thread?

Summary

Image loading includes many steps that cannot be removed from the process and these steps sometimes, not hard but dreary to implement. But the code as everything else ever written is (if properly constructed) reusable and programmers make new libraries every day since the beginning of the programming era.

Libraries as Glide make it possible to load images in just one line of code providing you with the instruments that will make your users' experience better. 

P.S. If you want to dive in and learn about Glide in details visit their javadocs and GitHub Wiki.

Sunday, July 24, 2016

Introduction to Firebase Database for Android



I've already written a post about Firebase and its' features but features highlighted in the post are additional to the core functionality of Firebase.

What is this core functionality? Well, this is the thing that Firebase started from. It's Realtime Database.

A real-time database is, basically, the database that can effectively store dynamic data. By dynamic, I mean data that is constantly changing for example stocks prices.

Firebase Database

So Firebase has its' own built-in real-time database which you can use as a backend for your app. Let's consider the structure of this database.

First of all, it's worth to mention that this database is not relational and doesn't use tables as you might expect. It uses JavaScript Object Notation (JSON) to store the data so it's kinda "object-oriented" database. 

I think that this it an advantage at least for developers because JSON, in my opinion, is easier to understand than relational tables if you're working within an object-oriented language. Also, using JSON eliminates some pitfalls that are associated with relational tables but, as always, brings some others.

The second important thing that Firebase Database is stored in the cloud and Firebase provides its' own hosting for it so you don't need to care about it. The amount of space you allowed to work with is described in your subscription plan.

And the most important feature in terms of development is that you can set data change listeners that will fire every time data in the database is changed and moreover give you a snapshot of changed node in the object tree.

Now when we have a big picture let's dive in and look how it works.

Closer Look

From this point, I assume that you have an account for Firebase.

First of all, we need to create our application.

App creation window

You can choose any name you like whereas app URL should be unique for every app registered in firebase. 

When you successfully created your app you can enter your dashboard and see an empty database.


Now you can go ahead and add some data directly from the dashboard or use the SDK to do so from your Android, iOS or Web app. Let's try do add something manually.

Manually added nodes

The important thing to notice that every node in the tree has its' own URL, we will use it later to refer to the concrete piece of data and attach a change listener to it.

Android SDK

For instructions on how to add Firebase to your Android app visit this page.

To use the database in our app we should add this gradle dependency in our app 
com.google.firebase-database:9.2.1

Now let's write some data to our database using Android app. One of the greatest things about this SDK is that you can write into the database using Plain Old Java Objects (POJO). This feature gives you an opportunity to keep your code clean and on the consistent level of abstraction.

Let's create POJO for our messages

public class Message {
    private String author;
    private String message;

    public Message (String auth, String msg) {
        this.author = auth;
        this.message = msg;
    }
    
    public String getAuthor() {
        return author;
    }

    public String getMessage() {
        return message;
    }
}

Note that for every field in Message class there is a public getter. It's a rule of SDK. If you don't have a public getter for some of the field you may get an exception so be sure to check that.

And the actual write method will look like this.

private void addMessage(String author, String message) {
    Firebase ref = new Firebase("https://tomasteryexmpl.firebaseio.com/chat/messages");
    Firebase messageRef = ref.push();

    messageRef.setValue(new Message());
}

It should be a method of the class that handles your database workflow. You can also pass composed Message object instead of author and message separately.

Let's do some clarifications. The ref variable stores a reference to the list of messages that we made earlier.

Method push() creates the unique key for the new entry in this list and returns its' reference in the database so messageRef stores reference to the new message.

When you have your reference you can easily write data to it using setValue(Object) method. And now you're done this method will successfully write your messages to the database and each message will have its' own unique key. Kinda easy, huh?

Let's look what happened to our data.

Added a message with unique code

Read the Database

In Firebase data reading differs from standard databases. To read from a database you should attach an asynchronous listener to the node you want to read. This listener will be triggered first time for initial state and every time data in this node is changed.

There are 2 types of listeners: ValueEventListener and ChildEventListener. The difference, basically, is that ValueEventListener will send you a snapshot of the whole object when it's changed while ChildEventListener will only send a snapshot of the changed child.

To listen for the messages it will be better to set a ChildEventListener to messages node so that we don't get the full list of messages every time a new message is sent.


private void setMessageListener() {
    Firebase ref = new Firebase("https://tomasteryexmpl.firebaseio.com/chat/messages");

    ref.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot snapshot, String previousChildKey) {
            Message newMsg = snapshot.getValue(Message.class);
            addMessageToUI(newMsg);
        }
        //... ChildEventListener also defines onChildChanged, onChildRemoved,
        //    onChildMoved and onCanceled, covered in later sections.
    });
}

And that's pretty all that you need to do to set a child listener to a node. Now every time a message is added to the database addMessageToUI will be called and you will see your message in your app. There are libraries that can do that for you (like Firebase UI) but these are out of the scope of the post.

To get more information about reading the database visit this page in Firebase Docs.

This is pretty all that you need to know to build a basic Android messaging app. For me, it looks extremely easy in comparison to all the backend mess that you would set up without Firebase.


Sunday, July 17, 2016

What is Content Provider

Today I will continue my "What is *Android component*" series and tell you about one of the essentials parts of an Android application a content provider.

Previous posts from this series:
What is Activity
What is Fragment

The problem

First of all, let's consider the problem that this component is meant to solve.

It's often useful for applications to retrieve data from other apps on the smartphone. Many pre-installed Android apps have the data that can improve the user experience of other apps. 

For example, phone book has information about the people that are probably your friends and it can be used by social networking app like LinkedIn to connect with someone you know in this social network.

User dictionary has information that can help users type faster by providing them with the most used words when they use a custom keyboard.

So, it would be convenient to have some tool that can share those kinds of data.

Something that would provide a consistent interface across all the apps on an Android device.

The solution

The solution came from the pair Content Provider and Content Resolver. These 2 Android components not only solve the problem but give much more benefits for an Android developer, but first things first.

Content Provider

What is great in Android SDK is that most of the components' names speak for itself.

Basically, all the Content Provider does is provide access to the content of some app.

There is a database in the core of a Content Provider and Content Provider adheres concepts of encapsulation and hides the structure of the underlying database and provides its' own methods to work with it.

To request data from a Content Provider you should know a Uri so that it knows what kind of data you want. Usually, in the implementation, a content provider uses UriMatcher to distinguish different types of queries.

For example, you can request all weather for particular location using something like this content:/com.weatherpp.app/mounain_view but when you need weather for particular date you may need to use another Uri, probably something like this content:/com.weatherpp.app/mounain_view/06/17/16 and Content Provider is meant to understand what you want using this Uri and give you this data. (By the way, com.weatherapp.app part is called content authority)

Content provider should implement an interface that allows to insert, update and delete data from the database. To be precise, all content providers extend the ContentProvider class but I don't want to go into implementation details to keep things abstract and easy to understand.

Content Resolver

Content Resolver is a thing that determines which content provider to query using the Uri you give to it.

How does resolver do this? It's pretty easy, to be fair. Remember the content authority? This com.weatherpp.app thing. Before using a content provider you should register it in the system through your app's manifest and provide its' authority. And using this authority Content Resolver can understand which provider you want to use, somewhat similar to how a content provider decides what piece of data you want to query.

It's worth to mention that unlike content provider you don't need to implement content resolver. It's already implemented and built-in in the system. You can get it using context.getContentResolver() in your application.  

When to use Content Provider

So in which situations you should use content provider?

As I said, content provider gives many benefits to developers besides sharing data between apps. So in my opinion answer is: anytime you're working with a database.

To explain my answer, let me tell you about the benefits.

Abstraction

The first, and I think the most important, benefit is an additional level of abstraction between the database and an object using data.

Abstraction, as I see it, is always a good thing because it allows you to think in terms of the problem domain and not think about small, tricky details of implementation.

Encapsulation

This thing kinda supports abstraction, without encapsulation abstract things are not abstract.

Encapsulation also saves you from thinking about structure and implementation of your database operations.

Scalability

This is an outcome of abstraction. First of all, you can be sure that if you have different layers of abstraction changes in low-level implementation won't affect high level. 

So when you add a table to a database or new column to a table you don't need to change all the code that uses this database/table you simply change you provider's code or don't change anything at all.

Flexibility

Actually, you're not required to expose all your data to other apps if you're using content providers.

So you can use it for your convenience and if you want to expose it you can do it by changing only one line in the manifest. You change it and voila you have your very own API.

Consistency

If you use content provider you have a consistent interface for all your data operations such as insert, delete, and query. And it's consistent not only inside your application but inside the whole platform.

And as Reto Meier said once
If you chose to not use content providers, well you chose poorly.

Sunday, July 10, 2016

Top 6 learning resources for Android Developers




In my opinion, learning is a lifelong process, and that's a popular point of view today mainly because it's information age. Knowledge now is the most powerful tool, not the only one that is needed for success, though. Furthermore, without it, no other tool can help you achieve it.

I think that you already know the importance of learning if you read this blog. So today I'll give you my top 10 learning resources for Android Developers.

1. Udacity

Udacity is my favorite online-learning platform. And I think it'll always be. The enthusiasm and passion with which its' CEO and co-founder Sebastian Thrun develops and maintains the platform are encouraging.

First of all, it worth to mention that Udacity is not an Android tutorials platform. There are a plethora of courses and nanodegrees for different professions and specialties, such as iOS, web development, tech entrepreneurship, machine learning, cloud computing and so on and so forth.

With his platform, Sebastian Thrun wants to repair today's broken education system. Provide learners with an affordable source of knowledge and give them an opportunity to enter the business area of their dreams and moreover, perform great in this area.

For Android developer, there are 2 great nanodegrees. One is for beginners and the second one is for intermediate. Both are made by in partnership with Google that makes this information a first-hand. In my opinion, this is a great opportunity to learn for those who participated in the platform development.

The one for beginners was introduced not long ago, at Google I/O 2016 I believe. It contains Android Development for Beginners wich was the first course I've completed on Udacity, and many other courses that will help a starting out developer to build a portfolio full of basic Android apps. 

And the second one and the one that I'm in the process of passing Android Developer Nanodegree. This one is great so far and as I think is most complete Android course out there. It'll teach you how to build advanced applications that require careful design and implementation.

These nanodegrees are $199/month and $299/month for Nanodegree Plus (you'll get a job offer or 100% refund) and if you graduate in 12 months you'll get 50% tuition refund. Also, you can complete all the courses for free but you'll not get benefits of nanodegree such as code reviews, personal instructions etc.

2. Android Weekly

This is not an educational platform like Udacity. It's not even a blog or something. It's a newsletter, but the effort that its' editors put in every newsletter is priceless and make it such a great source of new information about Android. 

I mean, this is just a mediator, but such a great mediator. Android Weekly is not only for those who wants to learn about Android but also for those who just want to be up to date with everything that happens in Android community.

It provides you with information about latest blog posts from all around the web, new podcast releases, new youtube videos and even conference and job offerings. Without it, I would probably bash my head against a wall searching all this.

I really encourage you to visit Android Weekly and subscribe to their newsletter.

3. Android Hive

Yet another great way to learn about Android. The author of this blog is Ravi Tamada and he is as said a Hardcore Android Developer.

There are so many great, valuable, and detailed tutorials about Android and  technologies related to it.

Almost anything you can think of in Android Development is already written as a tutorial on this blog. Really recommend it!

4. Android Developers Blog

Who can get you in the insights of Android better that people who made this? I think no one.

And this is what all about this blog is. The people from Google's Android team sharing tips, tricks, insights and new features of Android.

If there's something that should be discussed in Android community, be sure that there is already a blog post about it on Android Developers Blog.

5. Google Code Labs

I've already written a blog post about these the other day, but it never hurts to mention them another time.

Great tutorials with on the go instructions about special features that you may want to implement in your Android app.

6. Android Development Training

And of course last but not least the Android Development Training

Here you can find most up to date information about crucial parts of Android Development provided with code samples from real Android apps and detailed explanations of all what is going on in the code.

If you stuck during development and don't know how to implement a common feature this is the first place where you should go for help.

Also, in the Udacity courses this training often acts as a reference for students.

So here's my Top 6 of learning resources for Android Devs. If you know something great and this is not in this list please share in the comment section below, I'm learning too so extra supply of knowledge can not hurt.

It's all for today, see you in the next one! (or in the comment section :) )

P.S. It would be douchy to include myself in this list but I'm writing about Android Dev too!

Sunday, July 3, 2016

What is Fragment

The concept of a fragment is tied very tight with the concept of an activity. And if you don't understand clearly what activity is I encourage you to read last week's post first and then return to fragments.

Also, here's the post that will help you to get a nice overview of basic Android classes such as Context, Activity, Fragment, Thread etc.

What is the problem

With the growth of popularity of Android system more and more developers started to pay attention to it. More and more apps were developed for Android and it entailed more and more complexity in these apps. In particular, this complexity was growing in activities and layouts.

Possible solutions

First of all, developers wanted something that would be reusable in several activities. And this, as I think, gave a birth to ActivityGroup

As the documentation says it's
A screen that contains and runs multiple embedded activities
which seems like a bit overhead. In this implementation, every activity has its' own context, while developers wanted something that would be a part of one single activity context.

And with the arrival of tablets, this problem became more obvious. And at that moment of time Google introduced the fragment concept. Intentionally, fragments were designed to meet exactly the needs of tablet layouts, but now there are a plethora of use-cases for fragments. 

So what is Fragment

Fragment represents a behavior or part of the user interface in an activity. Multiple fragments can be used in one activity to represent different parts of the activity. Also, one fragment can be used in different activities.

A fragment itself doesn't know about other fragments in the activity part of which it appears to be.
By definition, it's independent part of an activity and can do its' job even without other fragments. So if you fall into a situation when one of your fragments depends on another fragment you should think about the design of your application.

A fragment always should be embedded in an activity and the activity's lifecycle actually defines the fragment's lifecycle. If an activity is on pause then all of its' fragments are on pause. If an activity is destroyed then all of its' fragments are destroyed. If an activity is running not all (if at all) of its' fragments are running, though.

While activity is running, a developer can manually and independently control the fragment's lifecycle. For example, he/she can add new fragment, or delete old one or pause it. 

Also, while doing these transactions it's possible to add them in the backstack so the user can revert a transaction by pressing "back" button.

And it worth to mention that fragments operate on the same level of abstraction as activities.

There are two types of fragments: static and dynamic.

Static fragments

Generally, static fragments are fragments that will not be replaced by other fragments during the lifecycle of an activity. To add an instance of this fragment to your activity you can use the <fragment> tag in the XML file that represents your activity's layout. And that's it your fragment will work as if it would be an activity. Also, using this approach you will be able to find this fragment using its' android:id.

Dynamic fragments

I think that the name is self-explanatory. Yeah, right, dynamic fragments are the ones that could be added, deleted and replaced while corresponding activity is running. These fragments are added in ViewGroup programmatically using FragmentManager. To refer to this type of fragments during runtime you would use a special tag that should be unique for every fragment in the activity.

A couple of use cases

The most popular and easiest use-case for fragments is the implementation of master-detail flow on tablets.

Master-detail flow is the technique that used in many mobile apps. Generally, it's when you have a list of items that describe something briefly and the screen that shows details of this something. For example, in an email app, you don't see a full email right away you see the title, maybe some text but you should tap on it to see details.



Usually, on smartphones, there is no place for both, master and detail layouts and these are separate activities. But tablets are much much bigger than smartphones so it's more convenient to have everything on one screen. Like in this picture.


So in this case, fragments perform like both: part of an activity and reusable parts. You can use detail fragment in smartphone and tablet layouts, but in smartphone layout, it will have

Also, fragments can be used without layout as a separate thread of your activity, but when do so remember that the fragment's lifecycle depends on the activity's lifecycle.

Wrap up

Fragments are powerful, as said with great power comes great responsibility and, in software development, complexity. But you don't need to understand all this complex underlying basements of fragment to take advantage of them.

For me, fragments were something that only sophisticates the structure of an application. But it was because the lack of understanding. Now I understand what is fragment and think that it's elegant solution to the problem that arose with the growth of Android system. 

And I hope that I tackled this lack of understanding for you. If I didn't and you still have questions fell free to ask in comment section below!

That's all for today, see you in the next one!

P.S. If you want to bee up to date about posts on this blog follow me on Twitter.

Sunday, June 26, 2016

What is Activity

Hi, today we will talk about one of the basal things in Android application an Activity.

How to understand an Activity

Activity is the basis of your application and entry point as well.

From the user side, it's a single focused thing that user can do while interacting with your application. Most of the Activities interact with the user and take care of creating a window for your UI. 

Also, using multiple Activities to represent various tasks helps a programmer to make app's code less complex and easier to maintain. 

Activities can be used as fullscreen or floating windows and as a part of another activity (in an ActivityGroup, note that it's deprecated since API 13).

Activity insights

Firs of all to start an activity you should define it in your manifest using <activity> tag inside <application>. Like this:

<manifest>
  <application>
      <activity android:name=".MyActivity" />

  </application>
</manifest >

Every class that extends Activity should implement these two methods
  1. onCreate(Bundle) - which is an entry point of your Activity, where you should initialize it (or recreate it we will talk about it later). You can think about it as a kind of constructor for your class. Usually, here we set an activity layout using setContentView(int) and set all the necessary fields including ones that relate to our layout using findViewById(int).
  2. onPause() - this one is called when the user leaves your Activity. At this point, you can save all data that can be necessary for future Activity launches (usually using ContentProvider which I will talk about in future posts).
There are many more events in Activity lifecycle, let's look at these.

Activity lifecycle

A set of activities is managed as a stack it means that when a new activity is started it is placed in the top of the stack and remains there until it destroyed or another activity is started. On the other hand, previous activities are below the new one in the stack and remains there while all the upper activities exist.

While in the stack, an activity can be in one of the four states.
  1. Activity is running (at the top). While in this state activity performs all the actions.
  2. Activity is not in focus but visible, or paused. It means that there's another activity that is semi-transparent or doesn't take all window's space so OS still should maintain UI of background activity. In this state, activity is still alive and can perform actions, but it's not recommended because it can be killed in the case of extremely low memory, while in this state. This is why we save all the data in onPause().
  3. Activity is not visible, or stopped. In this case, activity is still alive and still holds the state and member information, but there is more probability that it will be killed to free memory for something else.
  4. Activity is dropped, as I said OS can drop activity if it needs to free memory for something that has more priority. It does it by asking activity to finish, or simply killing its process (it's one of the reasons why you should save data before paused state). When the user decides to go back to this activity it's completely recreated, the developer should consider it and restore it to the previous state.
Here's a diagram from Activity documentation that shows most important parts (colored) of an activity lifecycle and all the methods that are called during this lifecycle. 
As you may see, activity exist even if app process killed it's just remaining in the activity stack and waits until the user navigates to it again, in this case, it should be recreated, using saved data. When activity is finished or system should completely destroy it, onDestroy() method is called and OS shutting it down.

In the onDestroy() method activity app should release all the remaining resources (close all the connections, shut down all the threads related to it etc.)  

Why lifecycle is so important

As I said, the system can decide to kill your activity if there's some higher priority process that requires memory. In this case, you should save your activity state in order to recreate it, when user will navigate to it again.

But this is not the only case when you should recreate an activity. Another reason to recreate it is configuration change.

Such things as orientation change, language change, or input devices plugging (like a keyboard) will cause your activity to go through its' lifecycle straight up to onDestroy() and after that system creates a new instance of your activity and calls onStart(Bundle) on it with savedInstanceBundle that contains the state of previous activity.

The reason to do so is quite simple. The fact is that in different configurations you app can use different resources, for example, you may want your app to look different in portrait and landscape orientations because in landscape you have more horizontal space.

However, you may want your app to not be recreated after some configuration changes. For example, if you don't care about whether a keyboard is plugged in or not (or you want to handle it yourself). 

In this case, you can tell the system to just warn your activity about a configuration change instead of killing it.

To do so you should use android:configChanges  attribute in activity's manifest to specify those changes. After that whenever specified configuration is changed onConfigurationChange(Configuration) will be called on your activity, and you can handle it yourself.

Also, activity's lifecycle in many ways controls lifecycles of all it's fragments (I will write about these in future posts).

Ways to save the state of an activity

I hope that when you have read the above, you have that one question. How to save the state of my activity? So if you do, read on.

There are two ways to do so. And these two ways should be used in different cases.

Case #1: You need to save some underlying information. Consider your user made some changes in his profile in this situation when the user leaves edit activity you should save all the applied changes to the database. Doing so you kill two birds with one stone. You update your database with new information and save the current state of your activity and when the user comes back to it the app will read it from the database.

As was said it's preferable to do in onPause(). It looks something like this.

@Override
protected void onPause() {
  super.onPause();
  //Always call the superclass method first, it performs operations required by system
  
  //Save applied changes to the database
  
}

@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  // Read from database and populate the views
}

Case #2: You need to save the state of your UI. Let's refer to our example with edit activity. The user can start typing something in EditText and leave you application because of an important message or something, and when he returns he wants everything in text fields to be as he left it. To achieve this effect you should use onSaveInstanceState(Bundle) and populate the bundle with the data you need to save. 

Actually, SDK already takes care of it but if it didn't you would write something like this

@Override
public void onSaveInstanceState(Bundle outState) {
  outState.putString(EDIT_TEXT_STATE, mEdit.getText().toString());
  
  super.onSaveInstanceState(outState);
  //Call superclass method as well. As I said, it handles states of some elements for you.
}

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState); // Always call the superclass first
   
  // Check if there is a state Bundle
  if (savedInstanceState != null) {
    mEdit.setText(savedInstanceState.getString(EDIT_TEXT_STATE));
  }
}

Summary

It's pretty much all the basics of activities. With it, you can build activities that don't care if system kills them, they will stay in the state that they were left. For complete reference about activities visit the documentation page and the guide. Here you can learn about intent-handling and result activities.

See you next week, peace!

Tuesday, June 21, 2016

Google starting Android Developer Certification

Certifications for developers is not a new thing. For example, Microsoft offers a wide range of certifications not only for developers but for almost anyone who works with their products (Office, Skype, Microsoft Server etc.). Oracle, Cloudera, and a plethora of other IT companies make certification programs for their products as well. 

These (in theory) help employers to connect with those who search for work in their field. It's (should be) kind of a confirmation that you have these skills that you're talking about.

But in practice, it doesn't work that well, many certified programmers don't know much about real software development process and don't have the necessary experience to start working in a team of qualified developers. So, employers did understand that and ceased to pay attention to certificates.

The most important criterion in employment is what applicant really did and can do, his portfolio and capability of learning from mistakes and failures. 

Meaningful certification

To be at least a little bit significant, certification should lead a developer through a development of a real software product that developer can put in his portfolio. 

It should be not just a piece of paper that endorses that you did pass a one-time exam but a process during which you use those skills that should be certified to build something really valuable.

Maybe something that you can really sell or publish in an app store (probably with some modifications).

Associate Android Developer Certification

And with that being said, I want to talk about Google's certification program.

Google didn't certify developers before. It's their first certification program despite they have really wide range of product for developers: Angular, Go, Dart, great amount APIs, Google Play Services etc.

And I think the reason why they didn't do so is that they are hiring many developers every month and face the problem of certificates. But seems like they come up with an idea of how to make certification better.

First of all, there is a performance-based exam that should show the candidate's ability to perform real-world tasks in a real-world project. Also, the grading system is fully transparent and that will allow employers to understand for what this certificate was given.

With these two improvements, a certificate should become more valuable for employers, it becomes not just a piece of paper but something that shows applicant's performance during development not just during the exam. That's what both employers and employees want from a certificate. 

What is in the future

The first certification program is for Entry-level Android developers and this, I think, is for the testing. Google want to know how it will work out and maybe they will have to change the way of certification in future. But if it works out well, I think, there will be other programs for high-level developers.

Also, the reason why they choose android for the first program is that it's highly popular now among new programmers and this will allow them to get more feedback. So it becomes clear that they're just testing their system for something bigger.

As for me, I'm already signed up for this certification program and waiting for July to pass an exam and get my first software development certificate. :)

And if you are just starting out like me, go ahead and sign up, even if it's not that good, it definitely will not hurt.

It's all for today, go ahead, sign up and good luck!

See you next week!

Sunday, June 12, 2016

Google Code Labs


The best (and the easiest as well) way of learning is by doing. But to get the idea of what you need to do you need someone to tell you (this is the main purpose of this blog).

Google Code Labs are doing exactly that. In codelab, you go through the lesson and build a small app that contains some feature like Google Sign in, Android Pay, Face Detection etc.

There are also codelabs that teach you to use new tools of SDK and Android Studio like ConstraintLayout.

At the moment, I've tried one codelab called "Build a Material Design App with Android Design Support Library" and have learned about ViewPager and NavigationDrawer also you can learn how to implement flexible space with image during this code lab.

One flaw that me and my friend noticed is the lack of comments in the code. Most of the codelab you will be asked to copy/paste/rewrite some code to make things work the desired way.

But for me, it was an encouragement to learn about used thing trough reading docs and blog posts.

There are a plethora of codelabs for any kind of developer. Whether you want to learn about Android, The Web or Firebase integration there is a codelab for you. Also, there are codelabs about Google APIs, Unity game engine, Virtual Reality and even one about Google Codelabs.

There is the list of codelabs that I want to complete during this week and I think that you will be interested in them too.

Building Apps that Sign In with Google


The reason why I want to complete this is that I always signing in every app with Google account if there is a possibility to do so. All these registration steps exasperate me and if I can start using an app without them I will and I want my users to be able to do so.

Echo with Android Howie Library

This I want to pass because one of my friends asked me to build an app for introverts :). The idea is that you will record something like in Whats App but you instead of sending it to someone you will save it on your phone and will be able to listen to it later. And this codelab will help me with this app.

Using ConstraintLayout to design your views


When I saw ConstraintLayout at Google I/O Keynote I reacted skeptically. I still think that ability edit source code gives you more flexibility and control over layout that any drag-and-drop layout builder. 

But I want to give it a try. At the end of the day, developers (me as well) will send feedback about it and it'll become better with time.

Automated Performance Testing and Android Testing codelabs


Proper tests will never hurt your app. Actually, developers dislike testing because the main goal of it is to break your app. But in the perspective testing will help you to provide your users with high-quality product and updates. I think that it worth breaking your app if it will lead your app to success.

Face Detection with the Mobile Vision API

Do I even need to explain why I want to complete this codelab? 

IT'S FREAKING COOL!

Face detection is awesome! You can not only detect faces, with Mobile Vision you can also catch facial expressions, and all of it on MOBILE PHONE. We didn't even think about it 5-7 years ago and now it's just a deal of passing a codelab.

All these I want to complete in a week. Likely, I will update this post after completing every codelab and will tell you what I think about it. So be tuned in follow me on TwitterG+ and Facebook to not miss future updates.

It's pretty all for today. See you in the next one!

Sunday, June 5, 2016

Benefits of Awareness

Today apps are more and more bound to the users context and developers seek for the way to provide a unique experience for each and every user.

One of the first apps that were designed to do so was Google Now a Google's smart mobile assistant that was meant to provide the user with information like weather, traffic, flight delays even before the user needs it.

To make this kind of apps, you need to be aware of user context. What is around him? Is it raining? What is he doing?

To answer these questions, you need to use sensors, a bunch of APIs and do it all in the background. It means that your app will drain the battery and affect the system health even if it's not accessed at the moment.

Bad influence on the battery life can be the cause of your app deletion from user's smartphone.

But these battery and performance optimizations can be a cause of pain for the developer. You need to develop the main idea of your app to make it clear and straight.

And here comes Awareness API.

As was said in my previous post I will tell you about what it is and how you can use it.

It didn't come out yet, but you can sign up for early access today and try it for your app.

What it is

As I said Awareness API was made to provide your app with information about the user's context.

It can give 7 different types of context like location, place, activity, time, weather, beacons nearby, and headphones status.

The nicest thing about the API that it manages its' impact on battery life automatically. So you only need to request the data about context and you can almost forget about managing system health when doing so.

The API itself consist of two distinct APIs that your app can use depending on how you want to use context information.

The first one is the Fence API



Fence API is like a watcher that will tell you when the event that you need to react to is happening. 

Generally, it looks like this, your app telling the API "hey, I need to know whenever my user is walking near a Whole Foods store", in this case, you use two types of context: activity and place. When the user's context match this conditions your app will be notified about it even if it's not running at the moment.

Using this information you can send a notification, for example, about a planned shopping trip.



And the Snapshot API

This API lets your app get information about the context that surrounds user at the moment.

In this case, your app is already performing some operations and then request the API, "Hey, I need to know what user is doing now and where he is". It can be useful for apps that store some kind of data produced by the user such as photos, videos, audio records etc. 

For example, you can request weather conditions and location for your photo app to make your gallery more convenient, classify photos by location or weather or kind of places (work, home, coffee shops etc.) they made at.

It also can be useful for analytics. You may want to know if what conditions your users use your app more often to make it better for this certain situations.

Types of context

Here are 7 types of context and what information they can provide
  • Time - this will provide you with current local time.
  • Location - this is the pure location on the map. Latitude and longitude.
  • Place - place and the kind of place (if can be identified).
  • Activity - accurately detected user activity like running, walking, riding a bicycle etc.
  • Weather - current weather conditions at the user's location.
  • Headphones - are headphones plugged in?
  • Beacons - namespace, type, and content of nearby beacons.

Using these you can build extraordinary apps and provide your users with content based on their current context and all this with minimalized impact on battery life and system health.

Share your use-cases in the comment section below.

This is all for today, see you next week, peace!

Sunday, May 29, 2016

Why I'm charmed by FireBase

What is Firebase


Firebase is a cloud service provider for mobile and web developers.

It was originated as real-time database service in 2011 and still it's the crucial characteristic of it.

But with it, Firebase offers the huge amount of features. Like built in Analytics, App Indexing, Hosting, Authentication, brand new Dynamic Links, Notification handling, Crash Reporting, and AdMob.

Most of these are totally free. There also paid plan featuring testing and Google Cloud Platform integration.

These features are new and were presented at Google I/O 2016, for me it was one of the most exciting parts of the keynote. I didn't put it in My Top 8 Announcements From Google I/O 2016, though. Because I think it worth to write a separate post about.

What I like the most about it is that it gathers almost all backend that you need for your mobile or web app in one place and manages everything for you. You don't need to connect your app with Google Analytics, AdMob, a real-time database, etc. separately, now you can have all these in one place.

And new features like Dynamic Links and Remote Config are awesome. They bring user experience to the new level without any hard work from the developer.

Dynamic Links

The most annoying issue in mobile for me is that browsing experience is always inconsistent, unlike the web.

Deep Links were here to solve the problem, they were great in theory, but in fact, they didn't work as we wanted.

Dynamic Links also don't solve this problem completely (Instant Apps do) but they ease the pain from it and do it way better than classic Deep Links.

Basically, Deep Link is the URL that knows about your users' context and depending on that context it can provide various behavior.

It can get your user to your website/app store page or directly to your app depending on whether your application is installed on the users' phone. It will behave differently on Android, iOS, and desktop.

The most remarkable part is that it can survive app store installation process and you can use the context of your user to bring him the best service when he opens your app for the first time or bring him to particular content within your app (for example some recipe in cooking app) that was encoded in the link.

Dynamic Liks are the base for Firebase Invites.

Invites

These really can help you to grow your app. People are most likely will use your app if they receive an invite from a friend.

It's not a new concept. Invites were invented long time ago, but developers were on their own in implementing them.

In the beginning, there were referral codes and I can't imagine that someone will be doing this copy-paste-email-copy-paste mess for %5 discount.

After that, developers started using referral links to achieve the similar effect, but still, the mess.

Some apps have UI for invites that are very convenient, a user just need to make 2-3 taps to invite a friend and the invited friend should do 2-3 taps to start using the app with the help of Deep Links.

But do you have time to implement that? Your main care is your app, not bells and whistles. But invites are important bells and whistles, invites can make the difference between success and failure of your app.

Fortunately, Firebase team did all the dirty work for you and brought Firebase Invites to you, so you can focus on your app functionality instead of making your own invites.

As I said, they are using Dynamic Links so you can be sure that UX will be fine.

And when you have an audience you need to re-engage with it. Remote Config will help you to do so.

Remote Config

We live in information century and today this information transfers really fast, we need some tools that will help us to react to this and bring better user experience across all devices.

One way to handle it is updating your app, but to do so you need to pass through all these development cycles like redesigning, redeveloping, testing etc. it's too slow, you can lose your users while trying to bring the new update.

To avoid this FireBase presented Remote Config. Essentially, it's key-value table that is stored in the cloud. But despite its' simplicity, it's all you need to react incredibly fast to feedback from your users.  

We are not prefect, we can do typos in our apps' text, and this is hraming user expreience, but now we don't need to repuload our app in app store just because of typos or something like that, just chnage the value of string with typo in your Firebase Console and you're done. (typos are annoying, aren't they?)

People from Firebase shared a great use-case for mobile games.

Consider you have a group of people that are too good in your game. They are getting 3 stars at any level. It's not what games are about, right? They want the challenge (remember flappy bird?), something that will make them try harder.

Ok, so you can bring them the challenge, make this levels harder, but they are the only group, what will be with other users?

It's not a problem now! There is a feature called Audience Segmentation that allows you to apply different configurations for different groups of users. You just make level settings to make it harder for those users that making great success in your game and you're done, again.

Also, you can use it to test a new feature on a small group of your users before showing it to everyone.

But wait, where you will get this all information, about what your users need the most.

Here's where Analytics come in.

Analytics

Analytics is not a new feature. Firebase Analytics just gather all analytic tools in one place (and that's as I said one of the greatest things about Firebase).

What I like the most in Analytics is Audiences. 

You can group your users by how they behave in your app. Are they making purchases? Are they from Japan? Are they too good in your game? Knowing all this you can provide different service to different users. Make your app flexible. 

And you can make your own custom events that will describe the group of users.

For example, if you have an online store app like eBay, you can make Audience of users that have a car (using Awareness API, that I will discuss in later posts) using the custom event to send them notifications about sales on items related to vehicles and increase your revenue from it.

Summary

Firebase is a generalization of developing experience since the moment the Intenet was invented. It has a plethora of tools for developers that'll provide great UX. 

I didn't try it out yet, but can't wait to get my hands on it and be sure I'll share the experience of using it in this blog.

There are many other features if Firebase to develop your app, grow it, and earn from it. These are just most important in my opinion and if you want me to describe them too just let me know in the comment section below.  

You can find the docs and other information here.

This is all for today, see you next week!