Android IP Subnet Practice App – Part 1 – External Libraries

I started app development on iOS, Swift and Xcode, so naturally I was used to Cocoa Pods to get external libraries. Android Studio (with Kotlin) has a similar method, but of course it’s a bit different. I’m no Android expert but I’ll share my learnings so far trying to put together an app that allows the user to practice calculating IPv4 subnets. If you’re not familiar with those, they are a crucial skill to understanding TCP/IP networking.

Concept

Just to get a very basic app working, we’ll build an experimental layout in order to test and see if the subnetting code is working. The basic idea is to get something that looks like this:

Subnet Practice Concept App

The top element is a text field that captures the user’s input, while the bottom element is a button that runs the code to find the “network address”, or the first IP address in a subnet, given an IP address and subnet mask. Above, we can see that from “192.168.0.5/24”, the network address “192.168.0.0/24” has been calculated after “TEST” was pressed. That’s what we’re shooting for.

Layout

We’ll create these three simple elements on a Relative Layout in activity_main.xml like this:

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

    <EditText
        android:id="@+id/edittext_entry"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="100dp"
        android:text="192.168.0.5/24" />

    <TextView
        android:id="@+id/textview_result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/edittext_entry"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="60dp" />

    <Button
        android:id="@+id/button_test"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/textview_result"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="60dp"
        android:text="Test" />

</RelativeLayout>

Hopefully this is pretty simple – it just creates the three elements and lays them out vertically in the center of the screen.

Adding an external library

Googling around, I found an IP address processing library on Github here:

https://github.com/seancfoley/IPAddress

On the Github page, it explicitly states the Maven Central (a large repository of libraries, connectivity to it is built-in to Android Studio) group and artifact ID’s, as well as the versions:

  • Maven group id: com.github.seancfoley
  • Maven artifact id: ipaddress
  • Maven versions: 2.0.2, 3.0.0, 4.3.3, 5.3.3

We can take this information and put a line in the app-level build.gradle file to download and install the library. Find the dependencies section (usually at the bottom) and add this line:

dependencies {
    //Others here removed for brevity
    implementation 'com.github.seancfoley:ipaddress:5.3.3'
}

Sync the gradle file and the library should be installed!

Kotlin code

In MainActivity.kt, we’ll connect to the layout elements and add logic. Make sure to enable view binding. Then we’ll write an onCreate function that looks like this:

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val binding = ActivityMainBinding.inflate(layoutInflater) #view binding
        setContentView(binding.root) #view binding

        val et = binding.edittextEntry #grab the EditText
        val r = binding.textviewResult #grab the TextView (result)
        val b = binding.buttonTest     #grab the Button

        b.setOnClickListener() {
            val str = et.text.toString() #get text from EditText
            val netAddr = IPAddressString(str).toAddress().toZeroHost().toString() #Magic to calculate network address
            r.text = netAddr #set TextView (result) to network address
        }
    }
}

This line:

val netAddr = IPAddressString(str).toAddress().toZeroHost().toString()

…takes whatever string is in the EditText and does these steps:

  • IPAddressString(str) turns the string into an IP address string, which is necessary for parsing the original string to a properly formatted IP address.
  • .toAddress() converts the string to an IP address object
  • .toZeroHost() finds the lowest IP address in the subnet, usually called the network address or subnet address. This library calls it a Zero Host.
  • .toString() converts the network address back to a string so it can be put in the TextView

This is definitely where the magic is happening in this code.

Hope this was all clear enough. Leave a comment or send me a message if it’s not!

Monetize Your App – Google AdMob

In the last couple of posts, we wrote a simple times tables flash card app. Let’s add some advertisements to it so we can make some money if anybody decides to actually use it.

Enter Google AdMob, one of the simplest and easiest ways to monetize an app.

The base code that we’ll be adding to is here on my Gihub account:

https://github.com/jamesmcclay/android_kotlin_times_tables

Let’s apply and get some ads popping up in our app!

Start the process

The application process starts here:

https://admob.google.com/home/

Clicking on “Get Started” will do what it promises.

If you’re already logged in with a Google Account, this part is easy. Your account will be created and you’ll be taken to the main AdMob page:

Google AdMob Dashboard

Click on “Add Your First App” to start adding an app.

Add your app

This part is pretty quick too. Just follow the prompts, answer the questions and create your app.

Now that we’ve created an app, we’ll need to add an ad to it. Once we’re done creating the app it leads us to the main page for the app. Clicking on “Add Ad Unit” will take us through the process to create an ad.

Create an ad unit

Ad units are just an ad within the app. There’s several different types to choose from. Some are simpler and less intrusive like the banner, and others take up the whole page and completely interrupt the flow of the app. Choose wisely. In this case, we’ll pick the simplest one, the banner.

Once the ad unit is created, we’ll get some identifiers we can use in our code to display the ad and connect it to our account to get paid.

Add the SDK

Now it’s time to write some code. We’re mostly going to be using the code given to us by Google, but since it’s in code we have a lot of control over how/when/if the ad is displayed. We’re following the quick start instructions on the Google documentation found here:

https://developers.google.com/admob/android/quick-start

We need to add some stuff to the build.gradle file located in the root directory (not the app-level one):

buildscript {
    repositories {
        google()
        mavenCentral()
    }
}

allprojects {
    repositories {
        google()
        mavenCentral()
    }
}

I also ran into an issue where I had to change a line in settings.gradle to be this:

repositoriesMode.set(RepositoriesMode.PREFER_SETTINGS)

The key was changing “FAIL_ON_PROJECT_REPOS” to “PREFER_SETTINGS”. After that, syncing gradle worked.

Now we need to add the dependency to the app-level build.gradle file (the other one) like this:

dependencies {
  implementation 'com.google.android.gms:play-services-ads:20.4.0'

  // For apps targeting Android 12, add WorkManager dependency.
  constraints {
    implementation('androidx.work:work-runtime:2.7.0') {
        because '''androidx.work:work-runtime:2.1.0 pulled from play-services-ads
                   has a bug using PendingIntent without FLAG_IMMUTABLE or
                   FLAG_MUTABLE and will fail in apps targeting S+.'''
    }
  }
}

Then we need to add the follow to AndroidManifest.xml. Make sure you put in the Application ID for your app that’s in the Google AdMob dashboard. It’s not the Ad ID that you created, the app ID. I got confused, so I thought I’d specifically call it out:

<manifest>
    <application>
        <meta-data
            android:name="com.google.android.gms.ads.APPLICATION_ID"
            android:value="ca-app-pub-xxxxxxxxxxxxxxxx~yyyyyyyyyy"/>
    </application>
</manifest>

With that, the SDK is added to the project. Next step is to initialize it.

Initialize the SDK

To initialize, we need to add the import at the top of the TableActivity.kt file (we’re going to put this on the flash card screen) and run the initializer inside onCreate. We’ll also add a global variable called mAdView to connect to adView (which we’ll create next):

import com.google.android.gms.ads.MobileAds

class TableActivity : AppCompatActivity() {

    lateinit var mAdView : AdView

    override fun onCreate(savedInstanceState: Bundle?) {

        MobileAds.initialize(this) {}

        mAdView = binding.adView
        val adRequest = AdRequest.Builder().build()
        mAdView.loadAd(adRequest)

Now all we need to do is add an AdView to the layout file so there’s an actual spot for ads. In the activity_table.xml file, we’ll stick this at the bottom, it came right from the Google documentation:

<com.google.android.gms.ads.AdView
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:id="@+id/adView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_alignParentBottom="true"
    ads:adSize="BANNER"
    ads:adUnitId="ca-app-pub-3940256099942544/6300978111">
</com.google.android.gms.ads.AdView>

You’ll notice there’s a real adUnitId in there, that’s on purpose. That’s actually the Google AdMob official test ID, we’re supposed to use that for testing. You can get your account suspended if you use your actual AdMob production ad ID.

And that should do it! When we fire up the app, we should see a test banner at the bottom of the flash card screen

Happy coding!

Getting Started – Android Studio 3.2

I’m hoping my app will make a million bucks at some point. If you’re here hoping to do the same, I’d recommend this book I’m reading – App Secrets: How to Make a Million Dollar App.

I use affiliate links on this site, commissions support my app efforts!

My first goal in getting going with any coding project is to get the basic environment set up, which will be key to the next step – the “Hello World” program. This can be a little trickier than it sounds with some environments, but with Android Studio, it was actually incredibly easy, even on Ubuntu Linux.

In case you’re using Microsoft Windows, the process is the same as Linux except in usual Windows cadence. Head on over to Android Studio Downloads and you’ll find a the Windows installer there.

I currently use Ubuntu 18.04 Desktop, and the Ubuntu Store has the latest version of Android Studio, 3.2. I just searched for “Android Studio” and it came right up:

Ubuntu 18.04 Store search results for “Android Studio”

Installing was as easy as clicking “install”. After it finished, clicking “Launch” put me through some initial prompts:

The cool Android Studio splash screen.

Where I get to a welcome screen:

Select “standard”:

And after a screen on theme and settings verification, I’m done:

The installer goes through some downloading and unzipping:

And I’m finished:

I’m then prompted to start a new project or open an existing one, so I start a new one:

And select “empty activity”:

On the project configuration page the only thing I changed was the language to “Java”, per reasons I listed on my About page:

Once everything loaded (it will take a bit) my interface looked like this:

Next up, Hello World!