Build an ASCII Art Editor: Image Export & User Configuration

The Android platform offers a wide range of storage options for use within your apps. In this tutorial series, we are going to explore some of the data storage facilities provided by the Android SDK by building a simple project: an ASCII art editor.

In the first part of this series we created our user interface elements, including a main Activity with a text-field for users to enter their characters and a configuration Activity in which the user will be able to choose color settings. In this installment, we are going to implement this user configuration choice as well as allowing users to export their artworks as PNG images, with the resulting files saved to the external Pictures directory on the SD card. In the final two parts of the series we will be working with an SQLite database to save, load, and delete the user's artwork.

The outline for this series is as follows:


Step 1: Respond to Settings Button Click

Let's start with the user configuration settings. In your app's main Activity, before the onCreate method, add a variable to represent the editable text-field:

You will need to add an import:

Inside onCreate, after you set the content view, retrieve a reference to the text-field so that we will be able to apply the display settings:

This is the ID we gave the editable text-field in the XML layout file. Next, retrieve a reference to the Settings button and detect clicks:

You will need the following import added:

Extend your Activity class declaration opening line to handle clicks as follows:

Alter the class name if you chose a different one. This requires another import:

Now your class must provide the onClick method, so add it after the onCreate method:

This method is going to handle various button clicks, so we will be adding code to it throughout the series. You will need the following import:

Inside the onClick method, we need to tailor what happens to whatever button has been clicked, as we will be handling more than one:

This is the Settings button we included in our main layout file last time.


Step 2: Start the Settings Activity

We created the Activity to handle user configuration choices last time, so let's start it running now from our main Activity, inside the onClick "if" statement block:

You will need this import:

We start an Intent for the Activity we created to handle user color scheme choice. In that Activity, we are going to let the user choose an option and return the result to the main Activity, which is why we use startActivityForResult. We will retrieve the result in the onActivityResult method which we will add next. But first, we need to be able to identify which Activity we are returning from, so we pass a constant as the second parameter to the startActivityForResult method. Add the constant at the top of your class declaration, before the onCreate method:

Now add the onActivityResult method after the onClick method:

Inside this class, we will handle data returned from the Settings chooser Activity (and later from the Activity in which the user chooses a saved picture to load). Inside the method, check that we are returning from the Color Chooser Activity and that we have a valid result:

When the user clicks the Settings button, the chooser Activity will start. The user will choose a color scheme and the chooser Activity will finish, returning data representing the user choice to the main Activity, since this is where the chooser Activity was started from. On returning to the main Activity, the onActivityResult method will execute, so we can implement the user choice here (which we will do soon).

Settings Activity

Step 3: Detect User Settings Choices

Now let's turn our attention to the chooser Activity in which the user can make a color scheme selection. Open your "ColorChooser" Activity. The onCreate method should already be complete. Remember that when we added the Image Buttons representing each color scheme to the "color_choice" XML layout file, we specified "setColors" as their onClick attribute and included a tag representing the two HEX colors for text and background - take a look at the "color_choice.xml" markup now to check this. When users click the Image Buttons, Android will execute the specified method in the Activity hosting the layout. Add the method to your "ColorChooser" Activity after onCreate:

Add the following imports to the class:

Inside the "setColors" method, first retrieve the tag from the View that has been clicked:

The tag has the following format: "#000000 #ffffff" - split the two colors into a String array:

Now we want to pass this data back to the main Activity so that we can apply the color scheme settings to the user interface elements there. To do this we use an Intent:

Add the two colors as extra data:

The first color represents the text and the second is for the background. Set the return Intent result:

Return to the Activity that called this one by finishing:

The two HEX color Strings will be passed to the onActivityResult method in the main Activity class.


Step 4: Apply the Color Scheme

Back in your main Activity onActivityResult method, inside the two "if" statement blocks we added to detect returns from the chooser Activity, retrieve the Strings we passed back:

Let's use a helper method to set the colors so that we can carry out the same process elsewhere:

Add the helper method after the onActivityResult method:

Inside this method, we can now set the colors for the editable text-field text and background:

This requires another import:

Color Scheme Applied

Step 5: Update the Shared Preferences

We've updated the appearance of the text-field to suit the user's choice, but we want to remember the choice so that each time they run the app it will be observed. Let's add an instance variable at the top of the class so that we can refer to the Shared Preferences anywhere:

Add the import if necessary:

In onCreate, after the existing code, get the Shared Preferences, using a name of your choice (you must use the same name each time you retrieve the preferences in your app):

Back in the onActivityResult method, after you call the helper method, get the Shared Preferences Editor:

Pass the data representing the user's choice and commit it to the app's preferences:

We specify a name for the preference data item and pass the two Strings concatenated into one, with a space character between them. This is a typical use of Shared Preferences, which are intended for key-value pairs of primitive type values, so are commonly used for configuration settings.


Step 6: Check the Shared Preferences

We want the user to see their chosen color scheme whenever they run the app in the future, so we need to check their choice when the Activity starts. In the onCreate method, after retrieving the Shared Preferences:

We pass the key String we used when saving the user choice. The user may not yet have saved a preference, so apply the color settings inside a conditional statement:

We split the color String again and call the helper method to apply the settings.


Step 7: Handle Export Button Clicks

Remember that we included an Export button for users to save their artworks as image files. In your main Activity's onCreate method, detect clicks on it:

Now add an "else if" inside the onClick method:

This is going to be another helper method so add it to your class file after the "updateColors" method:


Step 8: External Storage Availability

The Android system runs on many different devices, and we can't take anything for-granted about what facilities the user has. Before you attempt to write anything to external storage, you must first check that it is available. Inside the new helper method, add a check on the user's storage state using the Environment:

You need an import for this:

Now add a conditional test on the result, so that we can tailor what happens next:

The "if" block will export the image to external storage, with the "else" block handling situations in which there is no storage available. In such a case all we want to do is write an error message to the user letting them know we can't export the image - inside the "else" block:

Add the required import:


Step 9: Export the Image File

Now let's handle cases in which external storage is available. Add the following imports for the file output operation:

Back in the helper method for saving pictures, inside the "if" block, retrieve a reference to the Pictures directory:

Now we have the first part of the path we will use to create the picture file. The image is going to contain the visible content of the editable text-field, including the background color - i.e. it will display what you can see looking at the app screen when you export it. To achieve this we use the cache for the View:

This sets up the editable text-field View to be drawable, then saves its current appearance as a Bitmap using the drawing cache.

Now we need to give our file a name, so let's use the current date and time to make each one unique, appending some informative text and the image file extension:

Here we specify the filename, now let's create the file using it together with the path to the Pictures directory:

Since we are going to do some file I/O we need try and catch blocks:

This allows the program to keep running if something goes wrong with the input/ output operations. Inside the try block, create the file and pass it to an output stream:

Compress the Bitmap and write it to the output stream, saving the result as a boolean:

Output a message to the user depending on the result of the write operation:

Now close the file:

We can free the resources being used for the drawing cache, after the catch block:

That's the file output operation complete. The user can view their exported artwork as an image by browsing their device Pictures folder at any time.

Exporting the Image

Tip:If you're running your app on the emulator in Eclipse, you can set it up to contain external storage by editing the AVD and entering the amount of storage space in the SD Card "Size" field. Once you have the AVD running, run your app on it and export an image. In Eclipse, open the DDMS perspective from the Window, Open Perspective menu. Select the device and browse to the Pictures directory (mnt/sdcard/Pictures). You should see any pictures written by the app in this folder. To pull one from the virtual device, select it and click the "Pull a file from the device" button to save and view it on your computer.

Pulling a File From the Device

Conclusion

That's the user configuration and image export part of the app complete. If you run the app now you should be able to set the color scheme and export images to the SD card (as long as there is one present). Check the source code download if you're unsure about anything. We've used external storage and Shared Preferences in this tutorial. In the next parts we will build an SQLite database, using inserts, queries and updates on it to handle the user saving, loading, deleting and editing their ASCII artworks.

Tags:

Comments

Related Articles