Building an Android Library Tutorial
See how to create an Android library using Android Studio, publish the library to a Maven repository on Bintray, and host the library in the public JCenter repository. By Nishant Srivastava.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
Building an Android Library Tutorial
30 mins
Adding your Android Library to your app
Open your app’s build.gradle file and add the following inside dependencies
after // Testing
dependencies
// added validatetor Android library module as a dependency
implementation project(':validatetor')
Now sync up your project Gradle files. That is it. You have just added the validatetor Android library module to your app.
This is one of the ways of adding an Android library to an app project. There are more ways to add an Android library to your app which will be discussed later on in the tutorial.
Now that you have the validatetor library added as a dependency, you can reference the library code in your app.
You will now put in place the validation code using the validatetor library for all three EditText fields in your app.
Note: you will be referencing the Java-based Android library inside the Kotlin MainActivity class. There is no difference in usage except for following the Kotlin syntax
Note: you will be referencing the Java-based Android library inside the Kotlin MainActivity class. There is no difference in usage except for following the Kotlin syntax
Navigate to the app module and open the MainActivity.kt file inside the root package of the project to edit.
- Create an instance of ValidateTor:
private lateinit var validateTor: ValidateTor
- Initialize the instance of ValidateTor by appending the following to onCreate():
// Initialize validatetor instance validateTor = ValidateTor()
- Inside
validateCreditCardField(editText:)
replace// TODO: Validate credit card number...
:if (validateTor.isEmpty(str)) { editText.error = "Field is empty!" } if (!validateTor.validateCreditCard(str)) { editText.error = "Invalid Credit Card number!" } else { Toast.makeText(this, "Valid Credit Card Number!", Toast.LENGTH_SHORT).show() }
- Inside
validatePasswordField(editText:)
replace// TODO: Validate password...
:if (validateTor.isEmpty(str)) { editText.error = "Field is empty!" } if (validateTor.isAtleastLength(str, 8) && validateTor.hasAtleastOneDigit(str) && validateTor.hasAtleastOneUppercaseCharacter(str) && validateTor.hasAtleastOneSpecialCharacter(str)) { Toast.makeText(this, "Valid Password!", Toast.LENGTH_SHORT).show() } else { editText.error = "Password needs to be a minimum length of 8 characters and should have at least 1 digit, 1 upppercase letter and 1 special character " }
- Inside
validateEmailField(editText:)
replace// TODO: Validate email...
:if (validateTor.isEmpty(str)) { editText.error = "Field is empty!" } if (!validateTor.isEmail(str)) { editText.error = "Invalid Email" } else { Toast.makeText(this, "Valid Email!", Toast.LENGTH_SHORT).show() }
private lateinit var validateTor: ValidateTor
// Initialize validatetor instance
validateTor = ValidateTor()
if (validateTor.isEmpty(str)) {
editText.error = "Field is empty!"
}
if (!validateTor.validateCreditCard(str)) {
editText.error = "Invalid Credit Card number!"
} else {
Toast.makeText(this, "Valid Credit Card Number!", Toast.LENGTH_SHORT).show()
}
if (validateTor.isEmpty(str)) {
editText.error = "Field is empty!"
}
if (validateTor.isAtleastLength(str, 8)
&& validateTor.hasAtleastOneDigit(str)
&& validateTor.hasAtleastOneUppercaseCharacter(str)
&& validateTor.hasAtleastOneSpecialCharacter(str)) {
Toast.makeText(this, "Valid Password!", Toast.LENGTH_SHORT).show()
} else {
editText.error = "Password needs to be a minimum length of 8 characters and should have at least 1 digit, 1 upppercase letter and 1 special character "
}
if (validateTor.isEmpty(str)) {
editText.error = "Field is empty!"
}
if (!validateTor.isEmail(str)) {
editText.error = "Invalid Email"
} else {
Toast.makeText(this, "Valid Email!", Toast.LENGTH_SHORT).show()
}
Run your app. You can now enter text in the EditText fields and hit the Validate button to run validations on the text entered. You can use the test credit card number 4111111111111111, a 4 with fifteen 1’s. :]
You have successfully used the validatetor library in your sample app.
Next up you will make your Android library available to others for use in their own apps by publishing to JCenter.
Publishing your Android library
In order to proceed with publishing your library for this tutorial, you’ll need to first put your Android project into a public repo on your GitHub account. Create a public repo in your GitHub account and push all the files to repo. If you don’t have a GitHub account, please just read along to see the steps involved with publishing the library.
You just created your shiny new validatetor Android library and used it in your own app by referencing it as a module dependency.
Right now only you can use this library because the library module is available to your project only. In order to make validatetor library available to others, you will have to publish the library as a Maven artifact on a public Maven repository. You have 3 options here
You will publish your validatetor library to JCenter as it is the most common one and a superset of MavenCentral.
Setup your Bintray Account
You first need to create an account on Bintray.
- Register for an Open Source Account at bintray.com/signup/oss:
- Click on the activation link in the activation email they sent you and login into your account.
- Click on Add New Repository:
- Fill out the form as in the following screenshot and click Create. An important thing to note is that type has to be Maven:
- You should now have a Maven repository. The URL for it should be of the form
https://bintray.com/[bintray_username]/maven
. If you’re not already on the Maven repository page, you can browse to it by clicking on it from your Bintray profile page: - Click on Edit button from inside your Maven repository:
- Enable GPG signing for artifacts uploaded to your Maven repository on Bintray:
Get API Key and Link GitHub Account
Next, you need to get your API key to push your Android library to this Maven repository later on, and also link your GitHub account to Bintray.
- Open your profile:
- Click on Edit:
- Navigate to the API Key list item and copy the API key using the button on the top right:
- Go to your Bintray profile, hit the Edit button, go to the Accounts tab, and click Link your GitHub account to link your GitHub account to Bintray.
Get your project ready for publishing
To begin, back in Android Studio, switch to the Project view:
Add API keys
Double click your local.properties file and append the below
bintray.user=[your_bintray_username] bintray.apikey=[your_bintray_apikey]
Note:[your_bintray_apikey]
is the key you copied earlier from your Bintray account. [your_bintray_username]
is your Bintray username
Note:[your_bintray_apikey]
is the key you copied earlier from your Bintray account. [your_bintray_username]
is your Bintray username
Add other details
Open your gradle.properties file and append the following:
# e.g. nisrulz POM_DEVELOPER_ID=[your_github_username] # e.g. Nishant Srivastava POM_DEVELOPER_NAME=[your_name] # e.g. youremail@gmail.com POM_DEVELOPER_EMAILID=[your_email_id] # You can modify the below based on the license you want to use. POM_LICENCE_NAME=The Apache Software License, Version 2.0 POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt POM_ALL_LICENCES='Apache-2.0' # e.g. com.github.nisrulz GROUP=[your_base_group] POM_PACKAGING=aar
Note: You should ideally put the above code block inside your global gradle.properties because these would be common to all libraries you publish
Note: You should ideally put the above code block inside your global gradle.properties because these would be common to all libraries you publish
Setup helper scripts
There is a folder named scripts under your project.
Drag and drop this folder into your validatetor module. You will see the move dialog on dropping it on the validatetor module. Click OK in the dialog.
Once moved, your project structure under validatetor module will look like
Add details specific to your Android library
Open your project’s build.gradle file and append the following to the ext
block below // ValidateTor Library Info
, updating the values based on your specifics instead of mine where needed:
libPomUrl = 'https://github.com/[github_username]/[repo_name]'
libGithubRepo = 'nisrulz/validatetor'
libModuleName = 'validatetor'
libModuleDesc = 'Android library for fast and simple string validation.'
libBintrayName = 'validatetor'
Setup publishing plugin and helper script
- Add the publishing plugins under
// NOTE: Do not place your application...
inside your project’s build.gradle file// Required plugins added to classpath to facilitate pushing to JCenter/Bintray classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.7.3' classpath 'com.github.dcendents:android-maven-gradle-plugin:2.0'
- Apply the helper script to the very bottom of the
validatetor/build.gradle file// applied specifically at the bottom apply from: './scripts/bintrayConfig.gradle'
// Required plugins added to classpath to facilitate pushing to JCenter/Bintray
classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.7.3'
classpath 'com.github.dcendents:android-maven-gradle-plugin:2.0'
// applied specifically at the bottom
apply from: './scripts/bintrayConfig.gradle'
Publish to Bintray
Next, execute the following command inside your project folder using the command line in a Terminal window:
./gradlew clean build install bintrayUpload -Ppublish=true
Let me explain what the above line does
-
./gradlew
: Execute Gradle wrapper -
clean
: Execute the clean gradle task, which cleans up the repository of unused references -
build
: Execute the build gradle task, which builds the whole project. This generates the aar file, i.e. your Android library package -
install
: Execute the install gradle task, which is used to create the Maven artifact (aar file + POM file) and then add it to the local Maven repository. This task is available from the plugin you added earlier -
bintrayUpload
: Execute the bintrayUpload gradle task, which is used to publish the installed Maven artifact to the Bintray hosted Maven repository. This task is available from the plugin you added earlier -
-Ppublish=true
: This is simply a flag used to control the publishing of the artifact to a Bintray account. This is required to push the artifact to the Bintray account and is defined in the helper script
Once your command completes successfully, head over to your Bintray account and navigate to your Maven repository. You should see the following:
Hit Publish.
Awesome. Your Android library is now published on Bintray. In order to use the library as it stands as a Maven repositiry, you would have to take the following steps:
-
In your project’s build.gradle file you will have append the below under
allprojects/repositories
// e.g. url 'https://dl.bintray.com/nisrulz/maven' maven { url 'https://dl.bintray.com/[bintray_username]/maven' }
- To add it to your app, use the below (replace the module dependency you added earlier)
// e.g. implementation 'com.github.nisrulz:validatetor:1.0' implementation '[group_name_you_defined_in_gradle_properties]:[library_name]:[library_version]'
// e.g. url 'https://dl.bintray.com/nisrulz/maven'
maven { url 'https://dl.bintray.com/[bintray_username]/maven' }
// e.g. implementation 'com.github.nisrulz:validatetor:1.0'
implementation '[group_name_you_defined_in_gradle_properties]:[library_name]:[library_version]'
But you can eliminate the first step altogether, because jcenter()
is the default repository for dependencies. So you need to publish your library to JCenter.
Publish to JCenter
- Goto binray.com and navigate to your Maven repository.
- Find your library and open it by clicking its name.
- Mouse over Maven Central tab and you should be able to see a popup like shown below
- Select Click here to get it included link. This will initiate your request to include your Android library in JCenter
After this you will have to wait for an email from JCenter confirming that your Android library is published on JCenter.
Once published, you or anyone interested can use your Android library by adding to their app/build.gradle file under the dependencies
block.
// e.g. implementation 'com.github.nisrulz:validatetor:1.0'
implementation '[group_name_you_defined_in_gradle_properties]:[library_name]:[library_version]'
You can try it out once you have the email from JCenter. When doing so, remove the import on the local validatetor module.
Note: You do not need to reference your Bintray Maven repository anymore. Your validatetor Android Library is hosted from JCenter now.
Note: You do not need to reference your Bintray Maven repository anymore. Your validatetor Android Library is hosted from JCenter now.
Sweet. You just published your Android library for everyone. Feels good, right? :]