Showing posts with label Android. Show all posts
Showing posts with label Android. Show all posts

Download Files in Android - Kotlin & Java

Unless you are writing a Download Manager, downloading files in an Android application is never going to be the main business logic to solve but based on the requirement, you may need to download metafiles, media files, or documents over the Internet within your Android application. However, a reliable solution to download files in an Android application poses its own challenges including but not limited to the following list:


1. Thread Management

IO operations must be executed in a separate thread. Though there are plenty of options to achieve this such as now deprecated AsyncTask, Kotlin coroutines, or RxJava, still complex for a novice developer to properly handle the concurrency problems. Sending signals to the downloading thread to cancel or pause the download may introduce additional synchronization issues.


2. Error Handling

What if the Internet connection dropped while downloading the file? What if the application is closed while downloading/saving the file? How to handle all HTTP errors? the list goes on. Addressing all these scenarios is tedious and most of the time not possible.


3. Updating the UI

While downloading the file in a separate thread, updating a progress bar in the main thread is a challenge unless the concurrency framework you use provides an easy way. The same goes to update the UI after the file is downloaded.

Read More

Android: List External Storage Files

This article explains how to list files from the external storage (SD Card) in Android. Though you can list files recursively using a simple method, the new Runtime Permission Model introduced in Android 6 makes it a little difficult. Let's dive into the code and see how we can list all the files recursively.

Android: List External Storage Files

As I mentioned earlier, I am using Kotlin for Android development since it is the future of Android. If you are using Java, just copy and paste the code into your class method by method. The Android Studio will translate the method into Java for you.
Read More

Android: Custom Font in Kotlin

Sometimes you may want to use custom font in your Android application for aesthetic requirement or to show a message in a different language. I have already written an article on how to use a Custom Font in Android four years ago. Since it has been a long time and a reader wondered if that code still works, I am writing this new article using Kotlin. However, the underlying technique hasn't change over the years and you can still use my previous article.

Step 1:
Create an Android application "Custom Font" with Kotlin support.
Read More

Access MySQL from Android through RESTful Web Service

Finally, I found some time to write about accessing MySQL or any database that you can think about from an Android application. Android offers a built-in database known as SQLite which is supposed to be used for local data storage. For example, if you want to store your recent transactions locally in the device, you have to go with SQLite. I have already written a few articles on how to use SQLite database in Android. However, enterprise mobile applications often depend on client/server databases such as MySQL, Oracle DB or MongoDB. Whatever the database, you have chosen, the way to access them from an Android application is pretty same. In this article, I explain how to access a MySQL database from an Android application written in Kotlin.

I will use Kotlin for all upcoming Android tutorials because it is the future of Android programming. Kotlin is a JVM based language and you can easily convert a Kotlin project into Java and vice versa.

An Android application is not supposed to directly access a database deployed in a server. I do not recommend implementing JDBC connections in an Android application due to the tight coupling introduced between the application and the database. The industrial best practice requires you to implement a web service between the database and the Android application. Having a web service layer reduces the complexity of the Android application and also reduces the dependency on database specific operations. Therefore, the problem of accessing a client/server database like MySQL from an Android application can be defined as the problem of consuming a web service hosted somewhere.

Having said that, as an Android developer, you don't need to care about what is behind the web service. It may be a MySQL database, MongoDB database, a Social Media network or even a Weather Network API. What you need is the API endpoints exposed by the web service. In this article, I only explain how to connect to a web service hosted on your local machine from an Android application. However, the sample web service used in this article provides API endpoints to CRUD operations on a MySQL database. Please follow the RESTful CRUD With Java and MySQL in Minutes article and develop the web service to access a MySQL database. In the following section, you will learn how to access the web service you have created for accessing a database.
Read More

Android: Simple Calculator in Kotlin

It has been a long time since I wrote the tutorial: Android: Simple Calculator. However, still, that tutorial attracts more readers to my blog. Therefore, I have decided to write a new article to develop the same application using Kotlin. The previous article on developing a Calculator application using Java is still valid and feel free to compare this article with the previous one.


Android: Simple Calculator in Kotlin

Step 1:
Create a new Android application: Kotlin Calculator with an Empty activity. In the very first dialog, make sure that you have enabled the Kotlin support.

Android: Simple Calculator in Kotlin

Read More

Deploy and Upgrade Android Database From External Directory

After seeing the huge response for the Import and Use External Database in Android article, I have realized the importance of deploying Android database from external sources. The library used in the above article allows you to import database only from the assets directory. However, recently one of my readers, asked for a way to import and upgrade the database from SD card. As a solution for his use case, I have developed a new library named "externalsqliteimporter" which allows you to import database either from assets directory or from SD card. This article explains the application of this Android library using a sample application.


The ExternalSQLiteImporter library allows you to build your SQLite database on your desktop computer, and to import and use it in your Android application. This library has two separate ways to maintain your database.

This library is still under development. Deploying and upgrading  the database from an external directory is not secure as it is publicly available for third party applications as well. Use that feature with caution. 

Read More

Android Studio 3.0 with Kotlin: First Look

The most awaiting release, Android Studio 3.0 has been released a few days back with exciting features including Kotlin and Java 8 support.  Even though developers were able to use Kotlin and Java 8 earlier, this time they do not need any extra configurations to enable them. This article explains how to create a hello world Android application using Kotlin.

Android Studio 3.0 with Kotlin: First Look

Wait... This is Java Helps but I am writing about another language! Am I running out of content? Of course Kotlin is a new language but still, it is running on top of Java Virtual Machine. Kotlin can be compared with Groovy in terms of how it compiles the code. Both of them produce the same binary code that every Java developer is familiar with. Therefore Kotlin is another baby joining the family of JVM languages but with different syntax and more features.

Read More

Import Database with Images in Android

The article Import and Use External Database in Android explains, how to distribute an Android application along with the data stored in SQLite database. This tutorial explains, how to store images in such a database and pack it in your application. In other words, we are going to create a database with images from our desktop computer and import it into an Android application.

Step 1:
Create a database "images.db" using your favorite SQLite database application (I use Sqliteman because it allows inserting images into the database. You can use any software or script to insert the images into the database). Create a table 'places' with a two columns 'name' and 'image'. Here the data type of 'name' is TEXT and data type of 'image' is BLOB. Insert the name and image of  some places into the database. In this example, I have inserted the names of the seven wonders of the world along with a compressed (Using TinyPng) picture of them. To download the images used in this project, Click Here.


Read More

Android 6.0 Runtime Permission Model

The new runtime permission model introduced in Android 6.0 is an important issue to be considered by Android developers. Until Android 6.0, as a developer you might defined the required permissions in the AndroidManifest.xml file and focus on your business logic. However, since Android 6.0 the story becomes more complex, but it provides more security and control over the application to the end user. Let's cover this problem using a simple application.


Read More

Android RecyclerView

The RecyclerView widget is a more advanced and flexible version of ListView. This widget is a container for displaying large data sets that can be scrolled very efficiently by maintaining a limited number of views. Use the RecyclerView widget when you have data collections whose elements change at runtime based on user action or network events. RecyclerView decouples the positioning, animating items and various event handling into different classes.
This tutorial shows you, how to develop a RecyclerView application.

Step 1:
Create a new Android project "RecyclerView" with package name: "com.javahelps.recyclerview".

Read More

Android Navigation Drawer

The navigation drawer is a panel that displays the app’s main navigation options on the left edge of the screen. It is hidden most of the time, but is revealed when the user swipes a finger from the left edge of the screen or, while at the top level of the app, the user touches the app icon in the action bar. This tutorial guides you on how to create a navigable drawer application.

Step 1:
Create a new Android application using application name: "Navigation Drawer" and package name: "com.javahelps.navigationdrawer".


Step 2:
Select the "Navigation Drawer Activity" as the default activity.


Read More

Install Android Studio in Ubuntu 14.04

Android Studio is the official development tool for Android developers. This tutorial shows you the way to install the latest Android Studio in Ubuntu 14.04. Solutions for some common problems are provided at the end of this tutorial. Android Studio requires Oracle JDK 7.0 or latest in your system. If you do not have JDK, follow this link and install the Java first.

Read More

Android: Memo Application

This article provides a step by step guidance to develop a simple Memo application. You need to have basic knowledge on Android database and ListView to understand and complete this project. If you are not familiar with them, please visit to the following tutorials:

Step 1:
Create a new Android project “Memo”  with a package name “com.javahelps.memo”

Step 2:
Right click on the Java package and create a new class 'Memo'. This class will be used as the model to represent the memos later in this project.
package com.javahelps.memo;

import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Memo implements Serializable {
    private Date date;
    private String text;
    private boolean fullDisplayed;
    private static DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyy 'at' hh:mm aaa");

    public Memo() {
        this.date = new Date();
    }

    public Memo(long time, String text) {
        this.date = new Date(time);
        this.text = text;
    }

    public String getDate() {
        return dateFormat.format(date);
    }

    public long getTime() {
        return date.getTime();
    }

    public void setTime(long time) {
        this.date = new Date(time);
    }

    public void setText(String text) {
        this.text = text;
    }

    public String getText() {
        return this.text;
    }

    public String getShortText() {
        String temp = text.replaceAll("\n", " ");
        if (temp.length() > 25) {
            return temp.substring(0, 25) + "...";
        } else {
            return temp;
        }
    }

    public void setFullDisplayed(boolean fullDisplayed) {
        this.fullDisplayed = fullDisplayed;
    }

    public boolean isFullDisplayed() {
        return this.fullDisplayed;
    }
    @Override
    public String toString() {
        return this.text;
    }
}
The DateFormat is used to format the date when displaying the time of creation of the memo in the application. The fullDisplayed flag is used to define whether the complete memo is displayed to the user or part of the memo only displayed to the user. This property will be used to shrink and expand the memo in the application.

Read More

Inject Views on Android

Have you ever get irritated by the unlimited number of findViewById method calls and complex on-click-listeners? Obviously, they increase the complexity of the code and they consume more time as well. Butter Knife is a perfect solution to get out of these irritating and time-consuming code segments.

Butter Knife is an injection library used to inject views into Java classes. Using this library is not going to reduce the performance since it uses compile-time injection instead of runtime injection. Compared to some other Android libraries and frameworks, it is less featured but personally, I like this library a lot for its less configuration and high performance. This article introduces the basic functionalities of Butter Knife and more details can be found at the official website.


Let's create a simple application with a TextBox and a Button to demonstrate the application of Butter Knife.
Read More

Import and Use External Database in Android

This article explains the usage of an Android library which is helpful to import and use external SQLite database into your Android application. It has been a problem for Android developers to release an application with some existing rows of data in the database. For example if you are developing a static application which is used to display some tourist spots in your country, probably you need to release the database with predefined details about the tourist places inside it. However, there are no native ways to import external database easily into your Android application.


The Android SQLiteAssetHelper library allows you to build your SQLite database in your desktop computer, and to import and use it in your Android application. Let's create a simple application to demonstrate the application of this library.

Update: If you want to import database either from assets folder as described here or from an external location like SD card, a new approach is shared in Deploy and Upgrade Android Database From External Directory.

Step 1:
Create a database quotes.db using your favorite SQLite database application (DB Browser for SQLite is a portable cross platform freeware, which can be used to create and edit SQLite databases). Create a table 'quotes' with a single column 'quote'. Insert some random quotes into the table 'quotes'.


Step 2:
The database can be imported into project either directly as it is, or as a compressed file. The compressed file is recommended, if your database is too large in size. You can create either a ZIP compression or a GZ compression.

The file name of the compressed db file must be quotes.db.zip, if you are using ZIP compression or quotes.db.gz, if you are using GZ compression.

Step 3:
Create a new application “External Database Demo” with a package name “com.javahelps.com.javahelps.externaldatabasedemo”.

Step 4:
Open the build.gradle (Module: app) file and add the following dependency.
dependencies {
    compile 'com.readystatesoftware.sqliteasset:sqliteassethelper:+'
}


Once you have saved the build.gradle file click on the 'Sync Now' link to update the project. You can synchronize the build.gradle, by right clicking on the build.gradle file and selecting "Synchronize build.gradle' option as well.

Step 5:
Right click on the app folder and create new assets folder.


Step 6:
Create a new folder 'databases' inside the assets folder.


Step 7:
Copy and paste the  quotes.db.zip file inside the assets/databases folder.



Step 8:
Create a new class 'DatabaseOpenHelper'
package com.javahelps.externaldatabasedemo;

import android.content.Context;

import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;

public class DatabaseOpenHelper extends SQLiteAssetHelper {
    private static final String DATABASE_NAME = "quotes.db";
    private static final int DATABASE_VERSION = 1;

    public DatabaseOpenHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
}
Notice that rather than extending SQLiteOpenHelper, the DatabaseOpenHelper extends  SQLiteAssetHelper class.


Step 9:
Create a new class DatabaseAccess and enter the code as shown below. More details about this class is available at Advanced Android Database tutorial.
package com.javahelps.externaldatabasedemo;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.List;

public class DatabaseAccess {
    private SQLiteOpenHelper openHelper;
    private SQLiteDatabase database;
    private static DatabaseAccess instance;

    /**
     * Private constructor to aboid object creation from outside classes.
     *
     * @param context
     */
    private DatabaseAccess(Context context) {
        this.openHelper = new DatabaseOpenHelper(context);
    }

    /**
     * Return a singleton instance of DatabaseAccess.
     *
     * @param context the Context
     * @return the instance of DabaseAccess
     */
    public static DatabaseAccess getInstance(Context context) {
        if (instance == null) {
            instance = new DatabaseAccess(context);
        }
        return instance;
    }

    /**
     * Open the database connection.
     */
    public void open() {
        this.database = openHelper.getWritableDatabase();
    }

    /**
     * Close the database connection.
     */
    public void close() {
        if (database != null) {
            this.database.close();
        }
    }

    /**
     * Read all quotes from the database.
     *
     * @return a List of quotes
     */
    public List<String> getQuotes() {
        List<String> list = new ArrayList<>();
        Cursor cursor = database.rawQuery("SELECT * FROM quotes", null);
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            list.add(cursor.getString(0));
            cursor.moveToNext();
        }
        cursor.close();
        return list;
    }
}
In this class only the getQuotes method is implemented to read the data from the database. You have the full freedom to insert, update and delete any rows in the database as usual. For more details, follow this link Advanced Android Database.

All the database related setups are completed and now we need to create a ListView to display the quotes.

Step 10:
Add a ListView in your activity_main.xml.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center" />
</FrameLayout>

Step 11:
Find the object of ListView in the onCreate method of MainActivity and feed the quotes which are read form the database.
package com.javahelps.externaldatabasedemo;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.List;


public class MainActivity extends ActionBarActivity {
    private ListView listView;

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

        this.listView = (ListView) findViewById(R.id.listView);
        DatabaseAccess databaseAccess = DatabaseAccess.getInstance(this);
        databaseAccess.open();
        List<String> quotes = databaseAccess.getQuotes();
        databaseAccess.close();

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, quotes);
        this.listView.setAdapter(adapter);
    }
}

Step 12:
Save all the changes and run the application.


This library also allows you to upgrade the database using an external SQL script. For more details about this library, visit to its official page.

Find the project at Git Hub.

Update: To store images in this database, read Import Database with Images in Android
Read More

Advanced Android Database

Even though this tutorial is named as Advanced Android Database, there is nothing advanced in Android database. The last Basic Android Database tutorial explains the quick and dirty way of using SQLite database in your application. This tutorial uses the same problem discussed in the last article, but to explain the recommended way of database access in Android.


The Create, Read, Update and Delete (CRUD) related methods are not explained in this article since those are already explained in the Basic Android tutorial. If you are new to Android Database, please read the Basic Android Database article first and then continue this article in order to learn the best practices.
Read More

Android Spinner

In Android combo box is called as Spinner. This tutorial shows you, how to use Spinner in your application.

Step 1:
Create an Android project with a project name “Spinner Sample” and a package name “com.javahelps.sample.spinner”.

Step 2:
Modify the activity_main.xml as shown below. Notice that there is a UI component Spinner which is the combo box used to display some names of animals.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/txtInfo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:text="Select an animal"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <Spinner
        android:id="@+id/cmbAnimals"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/txtInfo" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/cmbAnimals">
        <ImageView
            android:id="@+id/imgAnimal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"/>
    </RelativeLayout>

</RelativeLayout>
Step 3:
The images I have used in this project can be downloaded from this link. Download the images and copy them.

Right click on the drawable folder and select “Paste”.


Read More

Custom Font in Android

This tutorial shows you, how to develop an application in your local language. Since some Android phones have problems with Unicode, you can use custom true-type fonts for your application. The same technique can be used to decorate your application using stylish English fonts as well. This tutorial develops an application to display a welcome message in Tamil. You can use your own font to display whatever you want.

Step 1:
Create an Android application “Custom Font” with a package name “com.javahelps.customfont”.

Step 2:
Add a TextView to the activity_main.xml as shown below.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/txtMessage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>

Step 3:
Right click on the “res” folder and select New → Folder → Assets Folder.


Read More

Android: Simple Calculator

This tutorial guide you to develop a basic Calculator Android application in Android Studio.

NOTE: There is a new article written on How to develop an Android calculator application using Kotlin: Android: Simple Calculator in Kotlin. The new article is the Kotlin version of this article. If you like to start with Kotlin, the recent article is recommended for you.

Step 1:
Create a new Android application project with an application name: “Calculator” and package name: “com.javahelps.calculator”.

Step 2:
By default, Android uses a green Android robot icon. In this project, we are going to use a custom application icon. Therefore, delete the default ic_launcher icon set from the “mipmap” folder.


Step 3:
Get any PNG image file for the application icon. (It is recommended to have a minimum size 256x256 pixels). This icon is used to display in the Google Play as well as in the applications menu of Android devices.

Step 4:
Right click on the “mipmap” folder and select New → Image Asset


Step 5:
Browse and select your icon as the image file and click on Next → Finish buttons. (Make sure that the resource name is: ic_launcher)


Step 6:
Replace the content of the activity_main.xml file by the following code. This code creates a TextView as the calculator number screen and some necessary buttons. TextView is used instead of EditText, in order to prevent manual user input using the default keypad of Android. In this code, some common properties of Buttons are not provided to reduce the length of this tutorial. In your code make sure that you have included these four attributes for all the Buttons.
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:textSize="30sp"
Read More

Contact Form

Name

Email *

Message *