Header Image - Randall Morgan

Tag Archives

3 Articles

Android Native Development with Java Getting to know Android

This entry is part 1 of 1 in the series Android Native Development with Java

Mobile platforms such as Android and IPhone are becoming the de facto computing devices.  Many people have left their laptops and even tablets behind as the power of smart-phones has increased. Now applications that once ran on the desktop are running on smart-phones. Software development is changing. Every product must contend with mobile support whether it be a website or service, or a desktop application. Users now expect that their data will travel with them and they will have access to it from all the devices they own. For the software developer, that means supporting multiple devices, often supporting multiple code bases and feature sets. Android has been around now for about a decade and has grown to own most of the mobile market. IOS is a close second. There are tools out their that will help the mobile developer develop products for both platforms using a single code base. I’ve written about my favorite, Dart/Flutter in other articles. However, these tools often lack either the flexibility to accomplish certain tasks, or they simply do not support a critical function of the device. When this occurs it is often necessary to fall back on native development. Either writing code that your main application can call, or writing the complete application in the platforms native code. This means that even a cross platform developer using tools such as Flutter or Xamarin often need to maintain a considerable amount of platform specific knowledge. Simply put, knowing native development for a platform is important even if you use cross platform tool sets.

I recently began taking some Android course (thanks to a Google Scholarship, THANK YOU GOOGLE!!! ) and thought I would share my knowledge and experience here. These are not the first Android courses I have taken. But I still feel I am far from an expert in Android development. Things change so quickly and I often am playing catch up just trying to stay abreast of new technologies. Sharing my knowledge with others and teaching others helps me ground my own understanding of a topic. So here I will share what I know a little at a time.

Tools Needed

Throughout this series I will be using Android Studio. At the moment it is version 3.0.1. The latest API is 27 revision 1. Android Studio is free and can run on Linux, Mac, and Windows.  It includes an emulator for running your compiled code though, other emulators from 3rd parties are available. AndroidStudio can be downloaded from: https://developer.android.com/studio/index.html If you would like to follow along I suggest you download and install AndroidStudio. Read the “User Guide” particularly the sections starting from “Meet Android Studio” to “Build And Run Your App”. These sections will help you get things setup and walk you through setting up the emulator. I will assume a familiarity with the Java programming language throughout this series. If you have never used Java but have C++ or C# experience, you should be able to follow along just fine.

Step One:

Ok, now that you have Android Studio setup and working and have an virtual device working for testing. It’s time to start coding.

The base for most Android Apps is the Activity. An activity typically loads the User Interface (UI) and provides some interaction with the user. An activity goes through a number of stages during it’s life cycle.  For most applications the activity is the heart of the application. Most applications have one or more activities however, it is possible for an application to be written without using an activity. These are rare however and are more advanced than we will cover here. You can think of an activity as a user task.

Fig. 1.1 Android Activity Life Cycle. Courtesy, www.developer.android.com

Fig. 1.1 Android Activity Life Cycle. Courtesy, www.developer.android.com

As stated, activities have a life cycle. The android framework provides 6 core callback methods that allow you to interact with the activity life cycle. These are: onCreate(), onStart(), onResume(), onPause(), onStop(), and onRestart() as shown in figure 1.1.

Android activities get created and destroyed based on the user’s interaction and system resource requirements. If the user navigates aways from your application and opens another app that requires resources your app is using, your application will be destroyed and then rebuilt when the user navigates back to it. The same actions can occur when the user rotates the device your app is installed on. Rather than doing a complicated dance to redraw the layout in the new orientation, android simply destroys your app and then recreates it when the user returns to it. This may seem like a drastic measure to take however, android works hard to limit power consumption and extend battery life, and this approach aids that goal.

The onCreate() method is fired when the activity is first created. Android requires that if we use an activity we must override this method in our code. In the onCreate() method we perform the activity logic that should only be completed once in the activities life cycle. Here we can load the layout, set class variables, and retrieve data that may be needed for the activity.

The onCreate() method receives an parameter of savedInstanceState of type Bundle. A bundle is a collection of state variables and data saved from the last run of the application. If the application has never been ran before the bundle will be null and the android framework will create it for us on the first run.

So let’s try some code! Open Android Studio and create a new project. Call it “ActivityApp” and select “Empty Activity” for the application type. Android Studio will create some boiler plate code for you. It should look like this:

 [cc lang="java" tab_size="4" lines="20"]
package me.randallmorgan.activityapp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
  }

}
[/cc]

The first line provides our Java package name. This name comes from the concatenation of the app name and the reverse of the domain name you enter when creating the project. This is a typical java standard for package naming. It ensures that no two packages are named exactly the same. So that when these packages are distributed, there is no confusion as to which package is which or who is responsible for the package. Android follows this java standard package naming convention.

Lines 3 and 4 include the needed framework libraries AppCompatActivity and Bundle. Line 6 is the beginning of our application. We declare a public class MainActivity that extends the AppCompatActivity class found in the android framework code. The public, protected, and private prefixes to our class and methods are used to annotate the visibility of the code. We wont worry about these just yet. But we’ll come back to them in a later post.

Next we Override the onCreate() method from the framework’s AppCompatActivity class and provide our own code to initialize our activity. First we call the onCreate() method of our parent calls AppCompatActivity. This ensures that the framework does the work it needs to do to initialize our activity, such as extracting the state information from the saveInstanceState bundle. Finally, we call setContentView() passing in the resource id of our layout. In this case, the default activity_main.xml layout.

The setContentView() method takes the layout file and turns it into an actual view on the screen. We use the resource layout file to store our UI design. We’ll talk about UI design next time. For now, let’s continue with the activity life cycle.

Logging

Android Studio provides a logging system that allows us to see debug messages. These messages can be grouped into various categories such as Error, Warning, Info, Assert, Debug, Verbose, and WTF (What a Terrible Failure). The WTF level is typically reserved for the framework developers and under normal development conditions shouldn’t be used by mobile developers. To use the logging methods we first need to import the “android:util.Log” library. Next we set a tag value. This tag can be any string value but is usually set to the current class name. Then to print out information to the debug output window (Logcat) we only need to call the Log.d() method. The Log.d method takes to strings values and an option Throwable. A throwable is an exception. Exceptions are a type of error handling that allows a program to catch recoverable errors and do some processing on non recoverable errors  (like logging them).

Log.d() is used for debugging messages. There are other Log methods. One for each type of error message we listed earlier. The ones you might use are Log.d(tag, msg), Log.e(tag, msg), log.i(tag, msg), Log.v(tag, msg), Log.a(tag, msg). The Log.wtf(tag, msg) should only be used if you understand what you’re doing. This is for catastrophic errors only!!! Again, it is best left to the Android framework developers.

So let’s see how logging works. Go back to our ActivityApp project. Open the main_activiy.java file. Edit the code as follows:

[cc lang="java" tab_size="2"]
package me.randallmorgan.activityapp;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

public class MainActivity extends AppCompatActivity {
  final String mTag = "MainActivity";
  
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    
    super.onCreate(savedInstanceState);
    setContentView(R.layout.test_activity);
    
    Log.d(mTag, "onCreate called.");

  }
}
[/cc]

We’ve added line to declare a class wide string variable of “mTag” and set it’s value to “MainActivity” following standard convention. Next we added a line to the end of our onCreate() method to log our message passing Log.d() the variable mTag, and our message “onCreate called.”. If you run the app in your emulator and open the Logcat window you should be able to locate our message: … D/MainActivity: onCreate called. You may need to filter the output using the dropdown  to show only the messages in the Debug category.

Visualizing the Activity Life Cycle

Ok, now that we have debugging working, let’s try out some of the other functions that get called during the lifecycle of our activity. Edit your code to read as follows:

[cc lang="java" tab_size="2"]
package me.randallmorgan.activityapp;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

public class MainActivity extends AppCompatActivity {
    final String mTag = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.test_activity);
        Log.d(mTag, "onCreate called.");

    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(mTag, "onStart called.");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(mTag, "onResume called.");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(mTag, "onPause called.");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(mTag, "onStop called.");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d(mTag, "onRestart called.");
    }
    
}
[/cc]

Now compile and run the app. Open the Logcat window and you should see the follow debug messages:

  • onCreate called.
  • onStart called.
  • onResume called.

Now rotate the view in the emulator. You’ll see a bunch of text scroll through the Logcat window. If you examine it you should see the following message:

  • onPause called.
  • onStop called.
  • onCreate called.
  • onStart called.
  • onResume called.

As you can see, our app was stopped by the Android framework and then recreated in the new orientation.

Ok, that’s it for today. Next time we’ll discuss layouts and the resource xml files. Then we’ll look at interacting with our layout.

Getting Started With Flutter – Part 1 Introducing Flutter

by SysOps 0 Comments
This entry is part 1 of 1 in the series Getting Started With Flutter

As I began to write this morning, I had Chrome open to the gitter.imflutter page. I’ve been a regular there for more than a month now.  Tismorning was unique. First a post was made that this past month had more traffic on the flutter site than any previous month. Second, that several people, myself included found that the flutter.io page was down do to exhausting it’s bandwidth for the month. Luckily, Google had it back up within a couple hours! This goes to show how popular flutter is becoming.

While flutter has been around a year or two, it is still has not been released for production. This past year flutter showed a great amount of growth as it is begining to come of age. This new level of maturity has cuased those like myself (who desire to build mobile apps for multiple platform from a single code base) take the leap. Yes, it is a risky venture. We all know how technologies tend to come and go and more often than not, end up as vapor ware. However, with flutter the risk is mitagatedsome by the fact that Google is both actively developing it and using it internally. They have been pushing it to their partners and have made flutter and it’s underlying dart language open sourced.

Now if you haven’t heard of flutter, you may be asking what it is. Flutter is a cross platform mobile development framework from Google. It is built on the Dart programming language. Dart is Google’s answer to some of the odities and limitations of Javascript. Be forewarned however, that Dart is different. Coming from a C background I find Dart has some peculiarities.  So it has taken me a bit to get comfortable with it. Still, I find that things don’t always work the way I think they should. This however, is just the learning curve that is more a result of my background inserting expectations on a language that is modeled on concepts foreign to the languages I have experienced in the past. This said, their are powerful features in Dart that make it well worth learning.

In this serries of articles I will walk you through some simple demos of flutter and it’s various features. At this point in flutter’s life, everyone is a noobe. The framework is still in it’s infancy so only the developers have a good grasp of all it’s workings. However, flutter is gaining steam and starting to get a foot hold in the App development market. People are already using it for major applications. Primarily because it reduces development time and does away with the need for multiple code bases to support multiple platforms.

So let’s get started building a simple app.

Prerequisites

Ok, to get started we need some tools and the Flutter platform. I’ll be using MS Code as an IDE mostly because it’s a simple IDE and has a Flutter plugin available. You can also use IBM IDEA, or Android Studio. You can infact use any Text Editor (Not a word processor) however, you’ll be missing the code highlighting and other features. There is plenty of info out there on the net on how to install this stuff. So rather than repeat it here, I’ll point you to the experts:

MS Code IDE: https://code.visualstudio.com/download

Flutter: https://flutter.io/setup/

Follow the instructions given on these sites to get your IDE and the Flutter framework setup. I’ll wait here until you’re done.

Ok, if you installed any of the three IDE’s I suggested, you can easily install the flutter plugin. In MS Code just search the plugins for flutter and install it.

Our First App

 

Building a Flutter App for Android The Holiday Shopping App.

by SysOps 0 Comments

Here it is a New Years and Iam still working with Flutter and Dart. Back before Christmas I started working with Flutter and built a few simple apps for my android phone. The first “real” app I created was for a friend. She is an artist in Arizona and blogs about art weekly. She’s been doing this for years. I host her site on my webserver, and help maintain her site. Working out issues when ever she wants a new gadget installed or the javascript she copied isn’t working for her.

So to help her out I wrote an android App that allows her followers to read her RSS feed. I plan on adding push notification to the app for her in the future. However, at this point that’s just a little beyond my knowledge of flutter and Android. With flutter I feel I am gaining knowledge quickly. I started my second app which required me to scape some data from an online database. The scrapping was easy using Python, Selenium, and BeautifulSoup. Tools I have plenty of experience with in the past. However, I soon realized that it was going to take some time to create booth a web api for the database and build the app. This app is a simple pet abuse lookup app. It’s allows people who are rehoming pets to check if the perspective new owner is in a criminal database for animal abuse. If they are, a summary of the public court records  can be seen.

So it being near christmas and me still needing an app that would be more complex yet not too complex to build. I settled on building a  Holiday Gift Shopping List App.   Below are a few screen shots. The current working model here still needs the database to be coded. At this point the app is working however it is working with a mock data adapter. A class that presents hard coded data in a maner similar to how I expect the database to work. if you look closely, you will see that if all the gift’s checkboxes are checked, the snowflake icon changes to a checkmark. The phone icon can be used to open the dialpadwith the user’s phone number ready for you to press call. The white + in the upper right open’s the user’s contacts so a Giftee may be added from the contact list. The Circle plus (+), let’s you add a gift idea to a user without opening the user gift list. Great for a quick idea!

All in all, the folks on gitter.im/flutter/flutter helped me out quite a bit. If you’re learning flutter there are quite a few helpful folks there. Icluding some members of the Flutter and Dart development teams.  They have all been very helpful. I’ve manage to help a few folks myself as I have learned Flutter and Dart. Which is nice because it helps drive home what you really know.

In the future I may do a tutorial on building the Holiday Gift App. For now, I’ve got other Flutter projects on the back burner and this one still needing the database connected. So, for now, I’ll complete this and move on.

Hope you all had a great New Years and a Wonderfully productive new year!

 

Newsletter Powered By : XYZScripts.com