Practical Android: 14 Complete Projects on Advanced Techniques and Approaches
By Mark Wickham
()
About this ebook
The book is an ideal resource for developers who have some development experience, but may not be Android or mobile development experts. Each chapter includes at least one complete project to show the reader how to implement the concepts.
What You'll Learn
- Apply JSON in Android
- Work with connectivity, which covers all aspects of HTTP in Android
- Determine if your server is reachable
- Use lazy loading, a common pattern for most apps and which is not trivial to implement
- Take advantage of remote crashlogs to implement a solution for your apps so you know when they crash and can provide timely fixes
- Implement push messaging to take your app to the next level
- Develop with Android Audio, which provides complete coverage of all the Android audio APIs and synthesis engines
Who This Book Is For
Those with prior experience with using Android and have a strong Java background.
Related to Practical Android
Related ebooks
Build a Whatsapp Like App in 24 Hours: Create a Cross-Platform Instant Messaging for Android Rating: 4 out of 5 stars4/5Beginning Mobile Application Development in the Cloud Rating: 0 out of 5 stars0 ratingsClean Android Architecture: Take a layered approach to writing clean, testable, and decoupled Android applications Rating: 0 out of 5 stars0 ratingsAndroid For Beginners. Developing Apps Using Android Studio Rating: 5 out of 5 stars5/5Learn Android Studio 4: Efficient Java-Based Android Apps Development Rating: 0 out of 5 stars0 ratingsAndroid Programming For Beginners: The Ultimate Android App Developer's Guide Rating: 0 out of 5 stars0 ratingsHow To Program A Mobile Game Rating: 4 out of 5 stars4/5Mastering Android Studio 3 Rating: 0 out of 5 stars0 ratingsHow To Create An App Rating: 3 out of 5 stars3/5Instant Spring for Android Starter Rating: 0 out of 5 stars0 ratingsBuilding Android Applications for Beginners Rating: 0 out of 5 stars0 ratingsBuilding Progressive Web Applications with Vue.js: Reliable, Fast, and Engaging Apps with Vue.js Rating: 0 out of 5 stars0 ratingsBeginning Xamarin Development for the Mac: Create iOS, watchOS, and Apple tvOS apps with Xamarin.iOS and Visual Studio for Mac Rating: 0 out of 5 stars0 ratingsCreating iOS apps with Xcode: Learn how to develop your own app (English Edition) Rating: 0 out of 5 stars0 ratingsTest-Driven iOS Development with Swift 3 Rating: 0 out of 5 stars0 ratingsAndroid for Absolute Beginners: Getting Started with Mobile Apps Development Using the Android Java SDK Rating: 5 out of 5 stars5/5Test-Driven iOS Development with Swift 4 - Third Edition: Write Swift code that is maintainable, flexible, and easily extensible Rating: 0 out of 5 stars0 ratingsAndroid Software Internals Quick Reference: A Field Manual and Security Reference Guide to Java-based Android Components Rating: 0 out of 5 stars0 ratingsBeginning Backbone.js Rating: 3 out of 5 stars3/5Android Studio Masterclass: Android IDE For App Developers Rating: 0 out of 5 stars0 ratingsThriving in Android Development Using Kotlin: Use the newest features of the Android framework to develop production-grade apps Rating: 0 out of 5 stars0 ratingsAndroid Design Patterns and Best Practice Rating: 5 out of 5 stars5/5Instant PhoneGap Social App Development Rating: 0 out of 5 stars0 ratingsFacebook Apps Secrets: Facebook Apps Secret For Businesses and Marketers Rating: 0 out of 5 stars0 ratings
Programming For You
Excel 101: A Beginner's & Intermediate's Guide for Mastering the Quintessence of Microsoft Excel (2010-2019 & 365) in no time! Rating: 0 out of 5 stars0 ratingsExcel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5Python Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5Spies, Lies, and Algorithms: The History and Future of American Intelligence Rating: 4 out of 5 stars4/5Linux: Learn in 24 Hours Rating: 5 out of 5 stars5/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5Learn PowerShell in a Month of Lunches, Fourth Edition: Covers Windows, Linux, and macOS Rating: 5 out of 5 stars5/5Learn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5SQL All-in-One For Dummies Rating: 3 out of 5 stars3/5C# Programming from Zero to Proficiency (Beginner): C# from Zero to Proficiency, #2 Rating: 0 out of 5 stars0 ratingsGrokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5Python QuickStart Guide: The Simplified Beginner's Guide to Python Programming Using Hands-On Projects and Real-World Applications Rating: 0 out of 5 stars0 ratingsJavaScript All-in-One For Dummies Rating: 5 out of 5 stars5/5HTML in 30 Pages Rating: 5 out of 5 stars5/5Tiny Python Projects: Learn coding and testing with puzzles and games Rating: 4 out of 5 stars4/5iPhone For Dummies Rating: 0 out of 5 stars0 ratingsHTML & CSS: Learn the Fundaments in 7 Days Rating: 4 out of 5 stars4/5Python: For Beginners A Crash Course Guide To Learn Python in 1 Week Rating: 4 out of 5 stars4/5SQL: For Beginners: Your Guide To Easily Learn SQL Programming in 7 Days Rating: 5 out of 5 stars5/5C All-in-One Desk Reference For Dummies Rating: 5 out of 5 stars5/5
Reviews for Practical Android
0 ratings0 reviews
Book preview
Practical Android - Mark Wickham
© Mark Wickham 2018
Mark WickhamPractical Androidhttps://doi.org/10.1007/978-1-4842-3333-7_1
1. Introduction to JSON
Mark Wickham¹
(1)
Dallas, Texas, USA
1.1 Introduction
It may seem unusual to start an Android book off with a chapter on JSON, but writing great apps is all about having great software architecture. Throughout the book, I will be using projects to help teach key concepts, and one function that almost all of the projects have in common is connectivity. Our apps need to connect to the Internet, and we need a simple yet sophisticated way to interchange data with the server.
This is where JSON comes in. JSON , or JavaScript Object Notation, is a lightweight data-interchange format. JSON has several important properties that have helped to make it hugely popular across the Internet and especially within mobile app development.
JSON is easy for us to read and write and is easy for machines to parse and generate.
There is a JSON library available for almost every platform and language.
JSON is based on a subset of the JavaScript programming language, hence its name.
JSON is a text format and is language independent.
JSON uses conventions that are familiar to programmers of the C- family of languages.
Many of the projects in this book will use JSON for configuration files. Using JSON as the interchange format with your application server creates a flexible and expandable architecture for your apps.
1.2 Chapter Projects
This chapter contains no projects.
However, several of the chapters in this book use the JSON code and principles described in this chapter to accomplish their server connectivity for configuration.
Table 1-1 shows the JSON usage summary for the projects in this book.
Table 1-1.
JSON Project Usage Summary
Note: The table does not include the projects that do not use JSON in their implementation.
1.3 JSON Overview
As a data-interchange format, JSON provides a method for us to communicate with the server. JSON is built on two data structures that are common in nearly all programming languages: a collection of name/value pairs, and an ordered list of values.
In JSON, there are two primitives that are used to represent these data structures. Using only these primitives, you will be able to construct complex structures that can represent almost any type of data relationship.
JSONObject: An unordered set or collection of name/value pairs
JSONArray: An ordered list of values
Both JSON objects and JSON arrays contain values. A value can be a string in double quotes, or a number, or true or false or null, or another JSON object or JSON array. These structures can be nested, which is why JSON is so powerful for data structures.
Figure 1-1 shows a graphical representation of the JSON syntax . The most important thing to notice is the usage of the [ (left bracket) and ] (right bracket), and { (left brace) and } (right brace) identifiers.
../images/460306_1_En_1_Chapter/460306_1_En_1_Fig1_HTML.jpgFigure 1-1.
JSON building blocks
A summary of the formatting:
Objects begin with { (left brace) and end with } (right brace).
Arrays begin with [ (left bracket) and end with ] (right bracket).
Values can be of multiple types and are separated by , (comma).
The power and flexibility of JSON is established by the fact that values can be comprised not only of strings, numbers, and Booleans, but also can contain arrays and objects themselves.
1.4 JSON and Android
JSON has been included in Android since the earliest release of the SDK . Table 1-2 shows a list of the Android JSON classes including the exception handler.
Table 1-2.
Android JSON Package Summary (org.json)
You shall see, in several of the projects in this book, how to use JSON to handle the app’s configuration. This makes it easy to change the app without the need to recompile the code.
The JSONArray and JSONObject objects are all you need to manage JSON encoding and decoding. The following code sample shows how these objects are defined and used in Android:
// Define a new JSON Object
// Remember that JSON Objects start with { (left brace) and end with } (right brace)
JSONObject jsonObject = new JSONObject(myJsonDataString);
// Define a new JSON Array
// Remember that JSON Arrays start with [ (left bracket) and end with ] (right bracket)
JSONArray jsonArray = new JSONArray(myJsonDataString);
The trick to using JSON effectively lies in defining a JSON data structure to represent your data.
1.5 Designing JSON
The recursive nature of the JSON syntax makes it suitable to represent almost any type of data.
Let’s take an example of a customer ordering application. When a customer orders items from a menu, a ticket is generated to represent key aspects of the transaction. Think about the receipt you get from a restaurant or coffee shop. It probably contains a number of important data related to the transaction , including
ID of the transaction
Date/time of the transaction
Name of the wait staff handling the transaction
Number of guests on the ticket (important because restaurants frequently calculate the amount spent per customer)
Sale type identifier, such as take-out, in-restaurant, or internet-order
Delivery information if the sale type is a take-out order
Order total, which is a sum of the individual totals of each item on the ticket
Details of all the individual items for the order
Let’s represent this data in JSON. JSON is ideal because once you have all the details encoded, it is easy to pass the details off to other consumers of the data. For example, you may have another internal activity that is responsible for printing out tickets, or you may wish to upload or download tickets to and from cloud storage over the network.
JSON Sample File
The code block below shows how you might wish to represent the ticket in JSON . Note that whitespace does not have meaning in JSON, but I have included indenting in this JSON example to show the nesting levels within the JSON structure.
At its simplest form, the JSON required to represent this order ticket is a single array of 11 objects. Note that the main array starts and ends with square brackets, and each of the 11 objects within the main array start and end with curly braces. Also, note that the first 10 objects are simple name/value pairs .
[ { orderid
: 151001-101300-9
},
{ customername
: },
{ tablename
: 9
},
{ waiter
: Mark
},
{ guests
: 2
},
{ saletype
: 0
},
{ time
: 101940
},
{ ticketnum
: 15297
},
{ ordertotal
: 70 },
{ deliveryaddress
: },
{ dishes
: [
[ { dishId
: 45 },
{ dishName
: Vegetarian Burger
},
{ categoryName
: Burgers
},
{ qty
: 1 },
{ price
: 35 },
{ priceDiscount
: 100 },
{ specialInstruction
: },
{ options
: [] }
],
[
{ dishId
: 61 },
{ dishName
: Spaghetti
},
{ categoryName
: Italian
},
{ qty
: 1 },
{ price
: 35 },
{ priceDiscount
: 100 },
{ specialInstruction
: },
{ options
: [
[ { optionId
: 0 },
{ optionPrice
: 0 },
{ optionName
: pesto
}
]
] }
]
] }
]
The last object, named dishes
, is different. Its value is an array of dishes because each ticket could contain multiple dishes. In this example, two dishes are included in the array.
Each dish itself has several name/value pairs, including the dish name, the dish category, the dish price, quantity, special instructions, etc.
Note that there is a third level of nesting because each dish can have options. The first dish has no options, but the second dish has one option, which defines pesto
as the type of dish and indicates that this option has no extra cost. Of course, a dish could have more than one option, so this is a very flexible structure.
Validating JSON
JSON structures can become complicated, and it is important to validate them when you are designing them for use within your apps. There are several web-based JSON validators available.
Figure 1-2 shows the JSON validator available at http://jsonlint.com . The site does a nice job of telling you if the JSON is valid. When the validator detects problems, it can highlight the problems so you can correct them.
../images/460306_1_En_1_Chapter/460306_1_En_1_Fig2_HTML.jpgFigure 1-2.
Web-based JSON validation using http://jsonlint.com
When designing JSON structures for your Android apps, it is important to validate them before writing the code that will parse them. There is nothing more frustrating than trying to debug JSON code that is trying to operate on invalid JSON structures.
Text File Encoding
JSON files are text files. They can be stored remotely on a server or internally within your apps. They often use the extensions of .txt or .json.
JSON text files can use any type of encoding. I recommend always using UTF-8 encoding . The advantage of UTF-8 is that it is a multi-byte encoding and thus can handle special characters such as Chinese, Kanji, Latin, or many others. Using UTF-8, you can easily embed these non-ASCII characters inside your JSON strings. Almost all text editors, including Windows Notepad, will allow you to specify the encoding when you save a file.
Android apps also allow you to set the default character encoding for text files. It is important to set this to UTF-8 so it will match your UTF-8 encoded JSON text files.
Depending on your IDE, the character encoding can be set in the project Properties under the Resource setting. There are typically two choices for text file encoding:
Inherited from container (Cp1252)
Other
If you select the drop-down box associated with Other,
you will be able to choose UTF-8 character encoding from the list.
1.6 Common JSON Operations
Now that you know you have a valid JSON structure, let’s take a look at how to implement a number of common JSON operations, including
Setting a JSON value in a JSON object
Getting a JSON value from a JSON object
Creating a JSON file programmatically
Reading in a JSON file and parsing it into Java ArrayLists
Printing out JSON strings
Removing a JSON array from within a JSON structure
You will see these operations used in several of the projects later in this book.
JSON is a low-level library. You will see at the end of this chapter that GSON (Google JSON) is an alternative external library used for data interchange. GSON allows us to work with Java objects rather than JSON objects.
Since you are working directly with JSON without external libraries, let’s write some simple helper functions that will allow you to access the data inside your JSON objects. You will see these helper functions used in several projects in the book that incorporate JSON. The first two operations, for setting and getting Object values, will use a helper function.
Setting a JSON Value in a JSON Object
Recall that JSON objects begin and end with curly braces: { and }. The JSON order ticket contains 11 JSON objects. You are going to define a helper function called jsonSetter to help you set a value for any of the JSON objects in the JSON order ticket.
jsonSetter Helper Function
The first helper function is called jsonSetter. It is passed a JSONArray, a key String, and a replace Object. This function iterates over the JSON string and allows you to set the value of a specific JSONObject.
private void jsonSetter(JSONArray array, String key, Object replace) {
for (int i=0; i
try {
JSONObject obj = array.getJSONObject(i);
if (obj.has(key)) {
obj.putOpt(key,replace);
}
} catch (JSONException e) {
// log(jsonSetter exception
);
}
}
}
For example, in the JSON order ticket, you may want to set the value of customername
to Hungry Person
.
This can be accomplished with the following single line of code using the helper function and passing it the object name and the new desired value:
// Assume JSONTicket is a JSONArray assigned to the sample JSON order ticket shown earlier
// Call the helper function to set the value of the customername
Object
jsonSetter(JSONTicket,customername
,Hungry Person
);
Recall that the JSON order ticket is an array that contains 11 objects. The helper function traverses over each of the objects until a key match is found. The function then replaces the value for that key with the newly specified value.
Getting a JSON Value from a JSON Object
You can also use a helper function to retrieve values from JSON objects. The jsonGetter helper function below returns an object that is the value of the corresponding key that was passed in.
jsonGetter Helper Function
This function allows you to retrieve the value of a specific JSONObject. The jsonGetter helper function is passed a JSONArray and a key