Monday, August 8, 2016

Android From Scratch: Understanding Adapters and Adapter Views_part1



Adapter views are so ubiquitous that you'd have a hard time finding a popular Android app that doesn't use them. The name might sound unfamiliar, but if you think you've never seen an adapter view, you are probably wrong. Every time you see an Android app display user interface elements in the form of a list, a grid, or a stack, you're seeing an adapter view in action.

An adapter view, as its name suggests, is a View object. This means, you can add it to your activities the same way you add any other user interface widget. However, it is incapable of displaying any data on its own. Its contents are always determined by another object, an adapter. In this tutorial, I show you how to create adapters and use them to feed different types of adapter views such as ListView and GridView.

1. What Is an Adapter?

An adapter is an object of a class that implements the Adapter interface. It acts as a link between a data set and an adapter view, an object of a class that extends the abstract AdapterView class. The data set can be anything that presents data in a structured manner. Arrays, List objects, and Cursor objects are commonly used data sets.

An adapter is responsible for retrieving data from the data set and for generating View objects based on that data. The generated View objects are then used to populate any adapter view that is bound to the adapter.

You can create your own adapter classes from scratch, but most developers choose to use or extend adapter classes provided by the Android SDK, such as ArrayAdapter and SimpleCursorAdapter. In this tutorial, we focus on the ArrayAdapter class.

2. How Do Adapter Views Work?

Adapter views can display large data sets very efficiently. For instance, the ListView and GridView widgets can display millions of items without any noticeable lag while keeping memory and CPU usage very low. How do they do that? Different adapter views follow different strategies. However, here's what most of them usually do.
  • They render only those View objects that are either already on-screen or that are about to move on-screen. This way, the memory consumed by an adapter view can be constant and independent of the size of the data set.
  • They also allow developers to minimize expensive layout inflate operations and recycle existing View objects that have move off-screen. This keeps CPU consumption low.
3. Creating an ArrayAdapter

To create an adapter, you need the following:
  • a data set
  • a resource file containing the layout of the generated View objects
Additionally, because the ArrayAdapter class can only work with strings, you need to make sure the layout of the generated View objects contains at least one TextView widget.

Step 1: Create the Data Set
The ArrayAdapter class can use both arrays and List objects as data sets. For now, let's use an array as the data set.
  1. String[] cheeses = {
  2.             "Parmesan",
  3.             "Ricotta",
  4.             "Fontina",
  5.             "Mozzarella",
  6.             "Cheddar"
  7.           };
Step 2: Create the Resource File
Create a new layout XML file whose root element is a LinearLayout and name it item.xml. Drag and drop a Large text widget in it and set the value of its id attribute to cheese_name. The layout XML file should look like this:
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3.     android:orientation="vertical" android:layout_width="match_parent"
  4.     android:layout_height="match_parent"
  5.     android:padding="@dimen/activity_horizontal_margin">
  6.     <TextView
  7.         android:layout_width="wrap_content"
  8.         android:layout_height="wrap_content"
  9.         android:textAppearance="?android:attr/textAppearanceLarge"
  10.         android:text="Large Text"
  11.         android:id="@+id/cheese_name" />
  12. </LinearLayout>
Step 3: Create the Adapter
In your activity, create a new instance of the ArrayAdapter class using its constructor. As its arguments, pass the name of the resource file, the identifier of the TextView, and a reference to the array. The adapter is now ready.
  1. ArrayAdapter<String> cheeseAdapter = 
  2.     new ArrayAdapter<String>(this,
  3.         R.layout.item,
  4.         R.id.cheese_name,
  5.         cheeses
  6.     );
4. Creating a List

To display a vertically scrollable list of items, you can use the ListView widget. To add the widget to your activity, you can either drag and drop it inside the activity's layout XML file or create it using its constructor in your Java code. For now, let's do the latter.
  1. ListView cheeseList = new ListView(this);
Usually, no other user interface widgets are placed inside a layout that contains a ListView. Therefore, pass the ListView to the setContentView() method of your activity so that it takes up the entire screen.
  1. setContentView(cheeseList);
To bind the ListView to the adapter we created in the previous step, call the setAdapter() method as shown below.
  1. cheeseList.setAdapter(cheeseAdapter);
If you run your app now, you should be able to see the contents of the array in the form of a list.

5. Creating a Grid

To display a vertically scrollable two-dimensional grid of items, you can use the GridView widget. Both ListView and GridView are subclasses of the abstract AbsListView class and they share many similarities. Therefore, if you know how to use one, you know how to use the other as well.

Use the constructor of the GridView class to create a new instance and pass it to the setContentView() method of your activity.
  1. GridView cheeseGrid = new GridView(this);
  2. setContentView(cheeseGrid);
To set the number of columns in the grid, call its setNumColumns() method. I'm going to make this a two-column grid.
  1. cheeseGrid.setNumColumns(2);
Usually, you'd want to adjust the width of the columns and the spacing between them using the setColumnWidth()setVerticalSpacing(), and setHorizontalSpacing() methods. Note that these methods use pixels as their units.
  1. cheeseGrid.setColumnWidth(60);
  2. cheeseGrid.setVerticalSpacing(20);
  3. cheeseGrid.setHorizontalSpacing(20);
You can now bind the GridView to the adapter we created earlier using the setAdapter() method.
  1. cheeseGrid.setAdapter(cheeseAdapter);
Run your app again to see what the GridView looks like.

Written by Ashraff Hathibelagal
If you found this post interesting, follow and support us.
Suggest for you:

Sunday, August 7, 2016

How to Enable Deep Links On Android

What Are Deep Links?

Android deep links open a specific page within an app and optionally pass data to it. Developers may find deep links particularly useful for actions, such as clicking a notification or sending an app link via email.

Let's take an email client as an example. When the user clicks the notification of an email she received, it opens a deep link that takes her to the email in the app. Last but not least, deep links also allow Google to index your app and link to specific sections of your app in searches. The deep link appears as a search result in Google and can take the user to a particular section of your app.

Implementing Deep Links

To add a deep link to your app, you must add it to your android manifest file as an intent filter. Take a look at the following example.

  1. <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name"
  2.     android:supportsRtl="true" android:theme="@style/AppTheme">
  3.     <activity android:name=".MainActivity" android:label="@string/app_name" android:theme="@style/AppTheme.NoActionBar">
  4.         <intent-filter>
  5.             <!-- Notice that the MAIN activity already has an intent-filter. This is not
  6.             A deep link because its action is not a VIEW-->
  7.             <action android:name="android.intent.action.MAIN" />
  8.             <category android:name="android.intent.category.LAUNCHER" />
  9.         </intent-filter>
  10.     </activity>
  11.     <activity android:name="com.example.matthew.deeplinks.LinkActivity" android:label="@string/title_activity_link"
  12.         android:theme="@style/AppTheme.NoActionBar">
  13.         <intent-filter>
  14.             <!-- Sets the intent action to view the activity -->
  15.             <action android:name="android.intent.action.VIEW" />
  16.             <!-- Allows the link to be opened from a web browser -->
  17.             <category android:name="android.intent.category.BROWSABLE" />
  18.             <!-- Allows the deep link to be used without specifying the app name -->
  19.             <category android:name="android.intent.category.DEFAULT" />
  20.             <!-- URI tutsplus://deeplink -->
  21.             <data android:scheme="tutsplus" android:host="deeplink"/>
  22.             <!-- URI http://www.mydeeplink.com -->
  23.             <data android:scheme="http" android:host="www.mydeeplink.com"/>
  24.         </intent-filter>
  25.     </activity>
  26. </application>

The <action> and <data> tags are required. The <action> tag chooses what happens in the app when the link is clicked. The <data> tag specifies what URIs are acceptable as deep links to the page.

In the above example, navigating to either http://www.mydeeplink.com  takes the user to the LinkActivity activity. The <category> tags specify the properties of the deep link. Notice that you need to create a separate intent filter  for each URI scheme and each activity.

You can create multiple links to the same activity. To differentiate these, you need to parse the intent's data in your code to differentiate the links. This is usually done in the onCreate() method by reading in the data and acting accordingly.

  1. protected void onCreate(Bundle savedInstanceState) {
  2.         super.onCreate(savedInstanceState);
  3.         setContentView(R.layout.activity_link);
  4.         Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
  5.         setSupportActionBar(toolbar);
  6.  
  7.         Intent in = getIntent();
  8.         Uri data = in.getData();
  9.         // Do something with data. For example, open certain email in view.
  10.     }

Testing Deep Links

Android Studio makes it very easy to test deep links. Click Run > Edit Configurations to edit the configuration of the project.



Open the General tab at the top and enter the URI in the Deep Link field in the Launch Options section. When you launch your app using Android Studio, it will attempt to open the specified URI.

Conclusion

Now that you know how to create and use deep links, you can open up new entry points for users to interact with your app. Users may use Google search on their phones to find pages within your app and you can create notifications that open a specific page in your app when clicked.
Written by Matthew Kim

If you found this post interesting, follow and support us.
Suggest for you:

The Complete Android & Java Course - Build 21 Android Apps

Android Application Programming - Build 20+ Android Apps

The Complete Android Developer Course: Beginner To Advanced!

Android: From Beginner to Paid Professional

The Complete Android Developer Course - Build 14 Apps


Friday, August 5, 2016

6 Android Tools Every Android Developer Should Know About


##1 Genymotion

Anyone who is familiar with the default Android Emulator will know that starting the emulator and running an app can be an extremely slow and tedious process. Genymotion solves this problem by providing a free (for personal uses) hardware accelerated Android emulator which is screaming fast.
Genymotion virtual devices support various Android API levels and work seamlessly with Android Studio. Download it ASAP, it will save you a lot of time.

##2 Fluid UI App Prototyping


Fluid UI is a neat web-based mobile storyboarding and prototyping tool which allows you to rapidly assemble native-looking mock-ups. The paid version starts at around $10 / month and unlocks the ability to share clickable prototypes and PDFs of your creations with others. It's free to try and is an affordable, mobile-specific alternative to many of the other prototyping tools out there. Check it out today.

##3 AppIconSizes.com


At some point during your mobile application development process you are going to need icons, splash screens and other default Android graphics. AppIconSizes.com will help you auto-magically generate all of your needed files (including landscape and portrait versions) from a single image as well as produce the correct folder structure Android requires. Once created, you can download, unzip and copy the resulting icons and splash images into your Android Studio project. Simple, easy, free and time saving.

##4 Acorn 4 from Flying Meat Software


Skip if you aren't developing on a Mac.
It is not uncommon for mobile developer to need to modify images and PNG files. Acorn 4 is the best, most affordable way I have yet found to do that.
Alternative image editors cost hundreds of dollars and may require yearly paid subscriptions. Acorn 4 costs ~$50 and you own it forever.
So support indie developers (and save a lot of money on image editing software): download the Acorn 4 trial today.

##5 Ubertesters.com


Does your mobile application have usability bugs? Does it use location based services? Do you work on a team that has many developers where you need to manage app versions? You will need some kind of app testing and distribution service...Ubertesters.com can help out.
The thing that makes Ubertesters stand out from industry competitors like TestFlight is their handy in-app "feedback widget." Once you integrate the Ubertesters SDK, a pair of floating buttons will appear inside your app which, when tapped on, reveal controls for performing a variety of tasks including: Annotating screen shots, writing bug reports and running tests from INSIDE your running mobile app. Go check it out, its free to try.

##6 Help From An Android Expert

Last but not least, get help from an AirPair expert who has developed and launched Android applications in the past! Obviously, we are a bit biased, but some things are just hard to find on Google, and AirPair, in turn, can really help you out.
Written by Rex St. John

If you found this post interesting, follow and support us.
Suggest for you:

The Complete Android & Java Course - Build 21 Android Apps

Android Application Programming - Build 20+ Android Apps

The Complete Android Developer Course: Beginner To Advanced!

Android: From Beginner to Paid Professional

The Complete Android Developer Course - Build 14 Apps

Ionic by Example: Create Mobile Apps in HTML5



An Introduction to Android Firmware

Android phones and tablets are generally a lot more open than their counterparts running operating systems such as iOS, Tizen, or Windows 10 Mobile. If you don't like the firmware the device manufacturer has installed on your Android device, you are free to replace it with your own custom firmware. CyanogenMod, Paranoid Android, and the Pure Nexus Project are examples of custom firmware that enjoy a lot of popularity among Android users.

Custom firmware is also the only way you can install newer versions of Android on devices that are no longer supported by their manufacturers. Unless you own a device that belongs to the Nexus or Android One series, I'm sure you knew that already.

In this article, I help you understand what Android firmware really is and how an Android device uses it. I also introduce you to the tools you can use to replace a device's firmware.

A Word of Caution

Replacing firmware is a risky operation that can potentially make your device unusable. In most cases it also voids your device's warranty. Make sure that you have a backup of your data and a copy of your device's factory image handy before you go ahead and experiment with flashing custom firmware.

1. What Is Android Firmware?

Originally, firmware was a term used to refer to tiny, mission-critical programs installed in the read-only memory, or ROM, of an electronic device. Modifying firmware was either impossible or required special equipment that was usually out of the reach of ordinary end users.

Android firmware, however, is very different. It includes the entire Android operating system and it is stored in a writable form of memory called NAND flash memory, the same type of memory that is used in storage devices, such as USB sticks and SD cards. The word firmware is used only because device manufacturers didn't bother to come up with a new word for it.

Android firmware is also often referred to as Android ROM because, by default, it is not possible for users to directly write to it.

2. What Does Android Firmware Contain?

Firmware installed on an Android device by its manufacturer contains a build of the Android operating system and two additional closed source programs that are usually irreplaceable, a bootloader and radio firmware.

Understanding Bootloaders
An Android bootloader is a small piece of proprietary code that is responsible for starting the Android operating system when an Android device is powered on. However, the bootloader almost always performs one more task. It checks if the operating system it is starting is authentic.

How does it decide what is authentic? It checks if the boot partition has been signed using a unique OEM key, which is short for Original Equipment Manufacturer key. The OEM key, of course, belongs to the device manufacturer, is private, and there is no way you can know what it is.

Because of the authenticity check, you cannot directly install a custom ROM on an Android device. Thankfully, these days, most device manufacturers allow users to disable the check. In Android jargon, they allow users to unlock the bootloader.

The exact procedure you need to follow in order to unlock the bootloader depends on your device. Some manufacturers, such as Sony and HTC, expect you to provide a secret unlock token. Others just expect you to run a fixed set of commands using a terminal.

Usually, a tool called fastboot, which is a part of the Android SDK, is used to run the unlock commands. For example, if you own a Nexus device, you can unlock its bootloader by running the following command:
  1. fastboot flashing unlock
You learn more about fastboot later in this article. Note that, if you own a device that has a bootloader that cannot be unlocked, there is no easy way for you to modify or replace its firmware.

Understanding Radio Firmware
It might come as a surprise to you, but your Android smartphone actually runs another operating system on an independent processor called a baseband processor. Radio firmware refers to the operating system that runs on the baseband processor.

Usually, it is an RTOS, which short for real-time operating system, and is responsible for managing the cellular radio capabilities of the device. In other words, it is what allows your device to make calls and connect to the internet using wireless technologies such 2G, 3G, and 4G LTE.

The RTOS is a proprietary piece of code and popular baseband processor manufacturers, such as Qualcomm, MediaTek, and Spreadtrum, make sure that its internal workings stay a secret. The Android operating system usually communicates with the RTOS using sockets and callbacks.

Generally, it is not a good idea to replace the radio firmware of your device.

Understanding Android Builds
The Android build is the only part of the firmware that is created from open source code. Consequently, this is the only part that you can modify and extend. When you hear Android enthusiasts say "I flashed a new ROM on my device", you can be sure that they are talking about a new Android build.

An Android build is usually shared in the form of a ZIP file that can be used by fastboot. It has the following contents:
update.zip
  1. |-- android-info.txt
  2. |-- boot.img
  3. |-- recovery.img
  4. |-- system.img
  5. `-- userdata.img
android-info.txt is a text file specifying the prerequisites of the build. For example, it could specify the version numbers of the bootloader and the radio firmware that the build needs. Here is a sample android-info.txt file:
  1. require board=herring
  2. require version-bootloader=I9020XXJK1
  3. require version-baseband=I9020XXKD1
boot.img is a binary file that contains both a Linux kernel and a ramdisk in the form of a GZIP archive. The kernel is a boot executable zImage that can be used by the bootloader.

The ramdisk, on the other hand, is a read-only filesystem that is mounted by the kernel during the boot process. It contains the well known init process, the first process started by any Linux-based operating system. It also contains various daemons such as adbd and healthd, which are started by the init process. Here is what the directory tree of the ramdisk looks like:
  1. ramdisk/
  2. |-- charger -> /sbin/healthd
  3. |-- data
  4. |-- default.prop
  5. |-- dev
  6. |-- file_contexts
  7. |-- fstab.grouper
  8. |-- init
  9. |-- init.environ.rc
  10. |-- init.grouper.rc
  11. |-- init.grouper.usb.rc
  12. |-- init.rc
  13. |-- init.recovery.grouper.rc
  14. |-- init.trace.rc
  15. |-- init.usb.rc
  16. |-- init.zygote32.rc
  17. |-- proc
  18. |-- property_contexts
  19. |-- sbin
  20. |   |-- adbd
  21. |   |-- healthd
  22. |   |-- ueventd -> ../init
  23. |   `-- watchdogd -> ../init
  24. |-- seapp_contexts
  25. |-- selinux_version
  26. |-- sepolicy
  27. |-- service_contexts
  28. |-- sys
  29. |-- system
  30. |-- ueventd.grouper.rc
  31. `-- ueventd.rc
system.img is the partition image that will be mounted on the empty system directory you can see in the above tree. It contains the binaries required for the Android operating system to run. It includes the system apps, fonts, framework JAR files, libraries, media codecs, and more. Obviously, this is the file Android users are most interested in when they flash a new ROM.

The system image is also the file that makes most Android users develop an interest in flashing custom firmware. System image files provided by device manufacturers are often full of unnecessary apps and customizations, informally called bloatware. The only way to remove the bloatware is to replace the manufacturer's system image with a more desirable system image.

userdata.img is a partition image that will be mounted on the empty data directory you can see in the ramdisk directory tree. When you download a custom ROM, this image is usually blank and it is used to reset the contents of the data directory.

recovery.img is very similar to boot.img. It has a boot executable kernel file the bootloader can use and a ramdisk. Consequently, the recovery image too can be used to start an Android device. When it is used, instead of Android, a very limited operating system is started that allows the user to perform administrative operations, such as resetting the device's user data, installing new firmware, and creating backups.

The procedure you need to follow in order to boot up using the recovery image is device specific. Usually, it involves entering the bootloader mode, also called fastboot mode, by pressing a combination of hardware keys present on the device, and then selecting the Recovery option. For example, on a Nexus device you need to press and hold the power button in combination with the volume down button.

Alternatively, you can use adb, a tool included in the Android SDK, to directly enter recovery mode.
  1. adb reboot recovery
3. Using fastboot

The easiest way to flash new firmware on your device is to use the fastboot tool. fastboot follows the fastboot protocol to communicate with an Android device. However, it can only do this when the device has been started in fastboot mode. The quickest way to enter fastboot mode is by using adb:
  1. adb reboot bootloader
To flash a custom ROM that is available in the form of a ZIP file containing all the image files I mentioned in the previous section, you can use the fastboot update command. For example, here is how you would flash a ROM present in a file called update.zip:
  1. fastboot update update.zip
If you want to flash only a specific image, you can do so using the fastboot flash command. For example, here is how you would flash only the system image:
  1. fastboot flash system system.img
Similarly, if you want to replace only the boot image, you would use the following command:
  1. fastboot flash boot boot.img
It is always a good idea to test if a boot or recovery image is working before actually flashing it to your device. To do so, you can use the fastboot boot command. For example, here is how you would check if a custom recovery image called twrp.img is compatible with your device:
  1. fastboot boot twrp.img
Note that none of the fastboot commands I mentioned in this section will work if the bootloader of your device has not been unlocked.

Conclusion

You now know what Android firmware is and how to replace it. I want you to understand that replacing firmware is a risky operation that can potentially make your device unusable. In most cases it also voids your device's warranty. Make sure that you have a backup of your data and a copy of your device's factory image handy before you go ahead and experiment with flashing custom firmware.
Written by Ashraff Hathibelagal

If you found this post interesting, follow and support us.
Suggest for you:

Android Application Programming - Build 20+ Android Apps

The Complete Android Developer Course: Beginner To Advanced!

Android: From Beginner to Paid Professional

The Complete Android Developer Course - Build 14 Apps

Ionic by Example: Create Mobile Apps in HTML5

Thursday, August 4, 2016

Android From Scratch: How to Store Application Data Locally

When it comes to persisting application data locally, Android developers are definitely spoiled for choice. In addition to direct access to both the internal and external storage areas of an Android device, the Android platform offers SQLite databases for storing relational data, and special files for storing key-value pairs. What's more, Android apps can also use third-party databases that offer NoSQL support.

In this tutorial, I'll show you how to make use of all those storage options in your Android apps. I'll also help you understand how to pick the most appropriate storage option for your data.


1. Storing Key-Value Pairs

If you are looking for a quick way to store a few strings or numbers, you should consider using a preferences file. Android activities and services can use the  getDefaultSharedPreferences()  method of the PreferenceManager class to get a reference to a SharedPreferences object that can be used to both read from and write to the default preferences file.
  1. SharedPreferences myPreferences
  2.     = PreferenceManager.getDefaultSharedPreferences(MyActivity.this);
To start writing to the preferences file, you must call the edit() method of the SharedPreferences object, which returns a SharedPreferences.Editor object.
  1. SharedPreferences.Editor myEditor = myPreferences.edit();
The SharedPreferences.Editor object has several intuitive methods you can use to store new key-value pairs to the preferences file. For example, you could use the putString() method to put a key-value pair whose value is of type String. Similarly, you could use the putFloat() method to put a key-value pair whose value is of type float. The following code snippet creates three key-value pairs:
  1. myEditor.putString("NAME", "Alice");
  2. myEditor.putInt("AGE", 25);
  3. myEditor.putBoolean("SINGLE?", true);
Once you've added all the pairs, you must call the commit() method of the SharedPreferences.Editor object to make them persist.
  1. myEditor.commit();
Reading from a SharedPreferences object is a lot easier. All you need to do is call the appropriate get*() method. For example, to get a key-value pair whose value is of type String, you must call the getString() method. Here's a code snippet that retrieves all the values we added earlier:
  1. String name = myPreferences.getString("NAME", "unknown");
  2. int age = myPreferences.getInt("AGE", 0);
  3. boolean isSingle = myPreferences.getBoolean("SINGLE?", false);
As you can see in the above code, as the second parameter, all the get*() methods expect a default value, which is the value that must be returned if the key is not present in the preferences file.

Note that preferences files are limited to strings and primitive data types only. If you wish to store more complex data types or binary data, you must choose a different storage option.

2. Using an SQLite Database

Every Android app can create and make use of SQLite databases to store large amounts of structured data. As you might already know, SQLite is not only light-weight, but also very fast. If you have experience working with relational database management systems and are familiar with both SQL, which is short for Structured Query Language, and JDBC, which is short for Java Database Connectivity, this might be your preferred storage option.

To create a new SQLite database, or to open one that already exists, you can use the openOrCreateDatabase() method inside your activity or service. As its arguments, you must pass the name of your database and the mode in which you want to open it. The most used mode is MODE_PRIVATE, which makes sure that the database is accessible only to your application. For example, here's how you would open or create a database called my.db:
  1. SQLiteDatabase myDB = 
  2.     openOrCreateDatabase("my.db", MODE_PRIVATE, null);
Once the database has been created, you can use the execSQL() method to run SQL statements on it. The following code shows you how to use the CREATE TABLE SQL statement to create a table called user, which has three columns:
  1. myDB.execSQL(
  2.     "CREATE TABLE IF NOT EXISTS user (name VARCHAR(200), age INT, is_single INT)"
  3. );
Although it's possible to insert new rows into the table using the execSQL() method, it's better to use the insert() method instead. The insert() method expects a ContentValues object containing the values for each column of the table. A ContentValues object is very similar to a Map object and contains key-value pairs.

Here are two ContentValues objects you can use with the user table:
  1. ContentValues row1 = new ContentValues();
  2. row1.put("name", "Alice");
  3. row1.put("age", 25);
  4. row1.put("is_single", 1);
  5.  
  6. ContentValues row2 = new ContentValues();
  7. row2.put("name", "Bob");
  8. row2.put("age", 20);
  9. row2.put("is_single", 0);
As you might have guessed, the keys you pass to the put() method must match the names of the columns in the table.

Once your ContentValues objects are ready, you can pass them to the insert() method along with the name of the table.
  1. myDB.insert("user", null, row1);
  2. myDB.insert("user", null, row2);
To query the database, you can use the rawQuery() method, which returns a Cursor object containing the results of the query.
  1. Cursor myCursor = 
  2.     myDB.rawQuery("select name, age, is_single from user", null);
Cursor object can contain zero or more rows. The easiest way to loop through all its rows is to call its moveToNext() method inside a while loop.

To fetch the value of an individual column, you must use methods such as getString() and getInt(),  which expect the index of the column. For example, here's how you would retrieve all the values you inserted in the user table:
  1. while(myCursor.moveToNext()) {
  2.     String name = myCursor.getString(0);
  3.     int age = myCursor.getInt(1);
  4.     boolean isSingle = (myCursor.getInt(2)) == 1 ? true:false;
  5. }
Once you have fetched all the results of your query, make sure that you call the close() method of the Cursor object in order to release all the resources it holds.
  1. myCursor.close();
Similarly, when you have finished all your database operations, don't forget to call the close()  method of the SQLiteDatabase object.
  1. myDB.close();
3. Using the Internal Storage

Every Android app has a private internal storage directory associated with it, in which the app can store text and binary files. Files inside this directory are not accessible to the user or to other apps installed on the user's device. They are also automatically removed when the user uninstalls the app.

Before you can use the internal storage directory, you must determine its location. In order to do so, you can call the ggetFilesDir() method, which is available in both activities and services.
  1. File internalStorageDir = getFilesDir();
To get a reference to a file inside the directory, you can pass the name of the file along with the location you determined. For example, here's how you would get a reference to a file called alice.csv:
  1. File alice = new File(internalStorageDir, "alice.csv");
From this point on, you can use your knowledge of Java I/O classes and methods to read from or write to the file. The following code snippet shows you how to use a FileOutputStream object and its write() method to write to the file:
  1. // Create file output stream
  2. fos = new FileOutputStream(alice);
  3. // Write a line to the file
  4. fos.write("Alice,25,1".getBytes());
  5. // Close the file output stream
  6. fos.close();
4. Using the External Storage

Because the internal storage capacity of Android devices is usually fixed, and often quite limited, several Android devices support external storage media such as removable micro-SD cards. I recommend that you use this storage option for large files, such as photos and videos.

Unlike internal storage, external storage might not always be available. Therefore, you must always check if it's mounted before using it. To do so, use the getExternalStorageState() method of the Environment class.
  1. if(Environment.getExternalStorageState()
  2.               .equals(Environment.MEDIA_MOUNTED)) {
  3.     // External storage is usable
  4. } else {
  5.     // External storage is not usable
  6.     // Try again later
  7. }
Once you are sure that the external storage is available, you can get the path of the external storage directory for your app by calling the getExternalFilesDir() method and passing null as an argument to it. You can then use the path to reference files inside the directory. For example, here's how you would reference a file called bob.jpg in your app's external storage directory:
  1. File bob = new File(getExternalFilesDir(null), "bob.jpg");
By asking the user to grant you the WRITE_EXTERNAL_STORAGE permission, you can gain read/write access to the entire file system on the external storage. You can then use well-known public directories to store your photos, movies, and other media files. The Environment class offers a method called getExternalStoragePublicDirectory() to determine the paths of those public directories.

For example, by passing the value Environment.DIRECTORY_PICTURES to the method, you can determine the path of the public directory in which you can store photos. Similarly, if you pass the value Environment.DIRECTORY_MOVIES to the method, you get the path of the public directory in which movies can be stored.

Here's how you would reference a file called bob.jpg in the public pictures directory:
  1. File bobInPictures = new File(
  2.     Environment.getExternalStoragePublicDirectory(
  3.         Environment.DIRECTORY_PICTURES),
  4.     "bob.jpg"
  5. );
Once you have the File object, you can again use the FileInputStream and FileOutputStream  classes to read from or write to it.

Conclusion

You now know how to make the most of the local storage options provided by the Android SDK. Regardless of the storage option you choose, read/write operations can be time-consuming if large amounts of data are involved. Therefore, to make sure that the main UI thread always stays responsive, you must consider running the operations in a different thread.
Written by Ashraff Hathibelagal

If you found this post interesting, please follow and support us.
Suggest for you:

The Complete Android & Java Course - Build 21 Android Apps

Android Application Programming - Build 20+ Android Apps

The Complete Android Developer Course: Beginner To Advanced!

Android: From Beginner to Paid Professional

The Complete Android Developer Course - Build 14 Apps


Tuesday, August 2, 2016

Designing, Wireframing & Prototyping an Android App_part1

If you dream of creating the next big thing in Android apps, then I'm not going to lie: you’ve got your work cut out for you!

You only need to take a quick peek at the Google Play store to see that pretty much every app you can think of has already been created—usually, multiple times and with varying degrees of success.

In such a competitive market, your app has to offer the full package—simply having a great set of features isn’t going to cut it! Your app also has to be responsive, easy to use, completely free of bugs, and (as shallow as it may seem) it has to look nice, too.

So when you jolt awake in the middle of the night with a brilliant idea for an Android app, resist the temptation to leap out of bed, boot up Android Studio and start bringing your vision to life. If you’re going to do your idea justice, then you need to put some thought into your application’s design.

In this two-part series, I’m going to show you how to turn a great idea into a great app. You’ll learn how to plan, test and perfect every part of your app’s design, and how to iron out as many issues as possible before you even write a single line of code.

In this first installment, we’re going to look at how to answer all of those big, burning questions every developer has to tackle whenever they start a new Android project. Then, we’ll create a list of all the screens we need to build, plus a screen map that shows exactly how all these screens fit together.

In part 2, you’ll master some powerful, designed-minded techniques, including wireframing and prototyping. By the end of part 2 you’ll have created a digital prototype that you can install and test on your Android smartphone, tablet, or emulator.

To help you see exactly how you’d take an idea from ‘spark of inspiration’ to working digital prototype, I’m going to imagine I’ve come up with an idea for an Android app that I want to create, and then develop this idea throughout the series.

Since we're (supposedly) heading into summer, I’m going to design an app that’ll help people plan and book the ultimate summer holiday with all their friends.

So we have our idea—what’s the first thing we need to do?

1. Write a Product Statement

Your typical app has lots of nice-to-have added extras, but it also has a clearly defined primary task. For example, our finished travel app might include social media functionality so users can share a snap of that awesome cocktail they had on the beach, or the cat they petted outside their hotel, but these features aren’t the app’s primary task.

A good trick for getting to the core of what your app is really about is to write a product statement. This is a single sentence that communicates what your app is, what it does, and why it’s imperative that the user boots up Google Play and downloads your app right now. It might help to imagine you’re pitching your app to a potential user, and you only have a single sentence to get your message across.

After much deliberation, I’ve decided on the following product statement:

An app that takes the stress out of planning and booking the ultimate summer vacation.

It’s crucial that you never lose sight of this product statement, so you may want to scribble it on a post-it note and stick it above your desk.


2. Identify Your Target Audience

The next big question you need to tackle is: who exactly am I building this thing for?

Hopefully you already have a rough idea of the kind of person who might want to use your app, but for the best results you need to design your app with a very specific target audience in mind. The old saying is true: try to please everyone, and you’ll end up pleasing no one.

Who you’re trying to appeal to should influence every part of your app—from the features you include to the look and feel of your UI, right through to the tone of your application’s text. That’s why it’s crucial you identify your target audience as early in the design process as possible.

I already have a rough idea of who I’m targeting: young adults aged 18-25 who are either on summer break from college or university, taking a full-blown gap year, or are planning one final adventure before it’s time to start looking for that first full-time job. This is a good start, but we can get more specific than that!

One simple but effective trick for zeroing in on your audience is to create a user persona.

A user persona is a single user who epitomizes the kind of person you’re targeting. What characteristics would this person have? Although the exact characteristics will vary depending on the kind of app you have in mind, you can start by answering the following questions:
  • How old is your user persona? This could be an exact age or an age bracket such as people over 60, or young adults.  
  • Where do they live? This might be a specific country or city, or a type of place such as by the sea or in the big city.
  • Do they have any children?
  • What are their hobbies?
  • Do they have a job? And if so, what is it?
  • Are they currently in education?
  • What is their favourite type of application?
  • What is their least favourite type of application?
  • What factors motivate them to download an app?
  • Do they ever pay for mobile apps?
  • How experienced are they with mobile apps? Are they a power user, or a beginner?  
  • How experienced are they with technology in general?
Let’s create a user persona for our travel app. For the best results, it helps to think of your persona as a real person. You might even want to give your user persona a name, which is exactly what I'm going to do: meet Sasha!
  • She’s 20.
  • She’s a university student on summer break.
  • She’s living with her parents over the summer, but will be returning to student halls at the start of the academic year.
  • She’s single, with no children.
  • She doesn’t have a job, so her student loan is her sole source of income.
  • As someone who has grown up with social media, her favourite apps are anything and everything that lets her share photos and status updates with her friends, family, and the World Wide Web in general.
  • She’s a pro with technology, especially mobile apps.
Since my app is all about organising a holiday, I also need to define Sasha’s experiences surrounding travel. Is my “typical” user likely to be well-travelled? Have they been responsible for planning their own holidays before, or is this all new to them?

I’m going to add the following characteristics to my user persona:
  • Sasha has been abroad several times, but only ever with her family.
  • This is the first time she’s planned her own holiday.
  • Sasha can be fairly organised when she wants to be, but since this is the first time she’s been involved in planning and booking a holiday, she'd definitely appreciate a helping hand!
Use Cases

So now we have the who, but what about the when? Under what circumstances might Sasha feel compelled to whip out her phone and boot up our app?

Here are a few that spring to my mind:
  • Sasha is hanging out with university pals, and inevitability the conversation turns to how much fun they're going to have over the summer. Everyone gets over-excited, and before you know it Sasha has opened our app, and she and her friends are eagerly planning what is sure to be the trip of a lifetime.
  • Sasha has just popped into the group chat she and her friends leave running in their favourite instant messaging app, and she sees that—finally!—everyone has agreed on a destination. Excited, Sasha boots up our app and starts researching fun things to do in that area.
  • Sasha is feeling frustrated. She and her friends seem to spend hours talking about how great their trip is going to be, but never actually get around to booking anything. Someone needs to take charge, and it looks like that person is going to have to be her. The only problem is she’s never arranged anything like this before. What she needs is some kind of app that can take the stress out of planning and booking the perfect summer vacation….
3. Create a Features List

It’s time to have some fun: let your imagination run wild and write down every feature you would include in your app if you had infinite time, money and a whole army of developers ready and raring to help you out. For now, don’t worry about whether these features are practical—think of this as your ultimate features list.

If you're struggling for inspiration, then head over to the Google Play store and download a few examples of Android applications that cover similar content, or have the same target audience as your application.


Spend some time exploring these apps and make a note of what the app does well, and any areas you feel you could improve upon.

Here are a few of the features I’ve jotted down:
  • The ability to book everything the user could ever need for their trip, from plane, train and bus tickets, to hotel reservations, and even miscellaneous things like reserving a table at that local restaurant that has particularly great reviews on TripAdvisor.
  • Read reviews left by other users, and post your own reviews.
  • The user defines their budget in advance, and the app subsequently filters all its suggestions based on this budget.
  • Be spontaneous! Planning a holiday is supposed to be fun, so why not leave everything up to fate by sticking a virtual pin in a virtual map?  
  • Okay, so planning a holiday is supposed to be fun, but it can also be hard work—especially if this is the first trip you’ve ever booked. Our app should provide a checklist of everything the user needs to book and arrange, in order to plan the perfect vacation. 
  • Social media functionality, so users can make all their friends and family jealous by posting photos and status updates about how much fun they’re having on holiday.
  • A travel journal for those users who want to share more than simple photos and status updates.
  • Since my target audience is young adults, this may be the first time many of them have been responsible for booking their own holiday. They might appreciate some general advice aimed at the first-time traveller, such as how to apply for a passport, or the kind of things you can and can’t carry in your hand luggage.
  • A countdown, so users can track the weeks, day, hours and minutes until it’s holiday o’clock.
Now it’s time for a reality check: there’s no way anyone can cram all their ideas into a single app. Even if all your ideas are sensible, well thought out and would appeal to your target audience, throwing everything but the kitchen sink into an app would be a nightmare for you as a developer, and would likely lead to a terrible user experience.

Imagine launching an app for the first time and instantly being confronted by a huge, complicated menu packed with a tonne of options. Choice is a good thing, but too much choice just becomes confusing! Since the last thing you want to do is confuse your users, we need to whittle our ultimate features list down to the bare essentials.

So how do we decide which features live, and which features die?

For the initial release, you should concentrate on features that are essential for delivering your app’s core functionality. And remember that just because a feature doesn’t make it into Version 1.0, doesn’t mean it won’t find its way into a subsequent update. If you come across a feature in your list that has potential, but isn’t essential for fulfilling your app’s primary task, then make a note of it as something that’s worth revisiting once you’ve got your app’s fundamentals down.

Your user persona and use cases should also play a role in determining what features you include in Version 1.0 (and in subsequent releases). What features are most likely to appeal to Sasha?

After re-reading the user persona, use cases and product statement, I’ve settled on the following features:

  • Booking travel and accommodation. This is an absolute must—if Sasha doesn’t at least arrange transport and a place to sleep, then she’s going nowhere.
  • Setting a budget. Sasha is funding the entire trip on the dregs of her student loan, so setting a budget is a top priority for our money-conscious student.
  • Sticking a virtual pin in a virtual map. Sasha is a young student looking to book a summer adventure with all her friends, so the thought of doing something a bit crazy and spontaneous might appeal to her. Also, remember our use case where Sasha is hanging out with her friends and they’re all egging each other on about how much fun they’re going to have this summer? This is the perfect opportunity for Sasha to really get the ball rolling by booting up our app and sticking a virtual pin in a virtual map.
  • A checklist. Since this is the first time Sasha has been involved in planning her own holiday, having a clear checklist to work through would make the whole thing much less intimidating.

Our list contains other features that would appeal to Sasha, such as being able to post photos from her trip, as we already know that Sasha is a fan of all things social media. However, for this initial release I’m going to keep things simple and remain focused on the app’s primary goal. Once you’ve delivered your app’s core functionality and fulfilled your product statement, you can turn your attention to all those nice-to-have added extras.

4. Sketch Out the High-Level Flow

You next task is to start thinking about the screens that you’ll need to create, in order to deliver this list of features, so grab a piece of paper and a pen or pencil. Sketch some rough flowcharts of the routes your users might take through your app, in order to accomplish core tasks.

For my travel app, the core tasks are:
  1. Booking a trip.
  2. Reviewing details about any trips the user has already planned.
You’ll typically represent screens with shapes, and express navigation using lines or arrows.


This exercise is mainly intended to get you thinking about the different screens you’ll need to create, in order to deliver the features you cherry-picked from your ultimate features list. Don’t spend too much time on your flowchart, as you’ll refine this flow when you come to create your screen map.

5. Create a Screen List

Next, come up with a list of all the screens you’ll need to create, based on your flowchart.

Here’s my screen list, plus a brief overview of what I plan to include in each screen:
  • Homescreen. This screen contains a menu of any trips the user has already planned via our app. The user can tap any item in this menu, to view the checklist for that particular trip. Alternatively, they can give the ‘Plan A New Adventure!’ link a tap.
  • Map. This screen contains a map and a virtual pin. The user can tap a section of the map, or if they’re feeling spontaneous they can grab the virtual pin, close their eyes and leave it all up to fate.
  • Select a city. Once the user has selected the country they want to visit, this screen suggests some cities where they might want to stay. This screen also contains a slider where the user can let the app know what kind of budget they’re working with. 
  • Checklist. This screen contains a checklist for the user to work through. Tapping any item in this list launches a screen where the user can complete this task, including:
  • Book transport.
  • Book a hotel.
6. Create a Screen Map

Now it’s time to combine our flowchart and screen list into a screen map that expresses the navigational relationship between all of these screens.

Start with the first screen the user sees when they launch your app, and work outwards.


It’s never too early to start looking for ways to improve the user experience, so once you’ve created your screen map, take a moment to look at it with a critical eye. One factor that has a huge impact on the user experience is the number of screens the user needs to navigate in order to complete the app’s core tasks.

Generally speaking, the fewer steps, the better the user experience. This map is the perfect opportunity to identify places where you can reduce the number of screens the user needs to navigate. This may involve removing screens, combining screens, reordering screens, or identifying places where it would make sense to add a navigational ‘shortcut’ so the user can jump straight from screen A to screen E.

Conclusion

So far, we've made some big decisions about the app we’re going to create, including who our target audience is, and what features we’re going to include in Version 1.0 (with some features left over for subsequent releases). We’ve also made a list of all the screens we need to design, and sketched out how these screens are going to be arranged in our finished app.

At this point we have our app all planned out, albeit at a very high level. In part 2 I’m going to dig deeper and design the individual screens that make up this screen map, before putting these screens to the test by building a digital prototype.
Written by:  Jessica Thornsby

If you found this post interesting, follow and support us.
Suggest for you:

The Complete Android & Java Course - Build 21 Android Apps

Android Application Programming - Build 20+ Android Apps

The Complete Android Developer Course: Beginner To Advanced!

Android: From Beginner to Paid Professional

The Complete Android Developer Course - Build 14 Apps