0% found this document useful (0 votes)
88 views141 pages

Android O & Java Course Notes

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
88 views141 pages

Android O & Java Course Notes

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 141

Android O & Java Notes

Abdul Qayoom
Java Developer Android & Spring Boot
Android O & Java Notes

Table of Contents
Set up for Android Development:.................................................................................................................................1
How the Course is Structured....................................................................................................................................1
How to Get All the Free Stuff....................................................................................................................................1
Download Your Massive Bundle Here.......................................................................................................................1
Developing for Android - Tools for this Course:.........................................................................................................1
Setup on Mac Android Studio, the JDK & Connecting a Physical Device:....................................................................1
Download Android Studio:....................................................................................................................................1
Download the Java Development Kit:....................................................................................................................1
Setup on Windows Android Studio, the JDK & Connecting a Physical Device:............................................................1
Download Android Studio:....................................................................................................................................1
List of OEM Device Drivers:.........................................................................................Error! Bookmark not defined.
Download the Java Development Kit:....................................................................................................................1
Troubleshooting Android Device Not Recognized:.....................................................................................................1
Configure Android Studio for Productivity Themes, Auto-Import & SDKs:.................................................................1
How to Set Up an Android Emulator with Hardware Acceleration:............................................................................1
Intel's HAXM Install Instructions:..........................................................................................................................1
Official Android Guide to Configuring Hardware Acceleration:...............................................................................1
Genymotion - an alternative Android emulator:....................................................................................................1
Slow PC Make it Run Faster with these Performance Tricks [Windows].....................................................................1
Build the I am Rich App to learn about project structure and XML [Tutorial].................................................................1
What Will We Make:.................................................................................................................................................1
Creating a New Android Studio Project and Choosing the API Level:.........................................................................1
Working with the Layout Editor, Strings, and App Themes:.......................................................................................1
Adding Graphics to a Project and using ImageViews:................................................................................................1
What is XML and How Does it Work:.........................................................................................................................1
XML Code Demystified..............................................................................................................................................1
Setting a Custom Launcher Icon:...............................................................................................................................1
Running the App to Test it Out:.................................................................................................................................1
Design the App's Screen in the Layout XML:..............................................................................................................1
Understand the Android Project Structure:...............................................................................................................1
The Wonderful World of Version Control Installing Git:.............................................................................................1
Installing Git for Mac:............................................................................................................................................1
Installing Git for Windows:....................................................................................................................................1

Abdul Qayoom 1
Android O & Java Notes
Git Installation Links.................................................................................................................................................1
Coding Challenge #1 - Using the Layout Editor in Android Studio and Github:...............................................................1
What are the Coding Challenges?..............................................................................................................................1
What You Will Create:..............................................................................................................................................1
Step 1 Importing Projects from GitHub and Opening them in Android Studio:...........................................................1
Create a Github Account:......................................................................................................................................1
Invitation link for the I am Poor assignment..........................................................................................................1
Step 2 Add a TextView:.............................................................................................................................................1
Step 3 Add an ImageView:........................................................................................................................................1
Step 4 Run the App...................................................................................................................................................1
Step 5 How to Submit Your Assignment on Github [Optional]:..................................................................................1
I am Poor Challenge Solution:...................................................................................................................................1
Build a Dice App to Learn Java & XML Fundamentals [Tutorial]:....................................................................................1
What Will We Make:.................................................................................................................................................1
Start a New Project and Style the App with the Theme Editor:..................................................................................1
Generating App Icons and Adding Graphics to a Project:...........................................................................................1
Official Guide to Android Launcher Icons...............................................................................................................1
Designing a Screen with Nested Layouts:..................................................................................................................1
Using Variables and Linking Layout Elements to Java Code:.......................................................................................1
Use the Logcat and a Listener to Check if a Button is Pressed:...................................................................................1
Create Random Numbers in Java:.............................................................................................................................1
Java Arrays and How to Use Them:...........................................................................................................................1
Why did the programmer quit his job?......................................................................................................................1
Debugging Practice Compilation and Build Errors:.....................................................................................................1
Debugging Practice, the App Has Stopped. What to do after a Crash:........................................................................1
Debugging Practice Github Repo...........................................................................................................................1
Show Off Your Work:................................................................................................................................................1
The Code for the Complete Dice Project....................................................................................................................1
Coding Challenge #2 - Data Types, Variables and Arrays:..............................................................................................1
What You Will Create:..............................................................................................................................................1
Debugging Cannot Resolve symbol 'AppCompatActivity'...........................................................................................1
Step 1 Import the Skeleton Project from Github:.......................................................................................................1
Invitation link for the Magic 8 Ball assignment:.....................................................................................................1
Step 2 Change the App's Theme:...............................................................................................................................1

Abdul Qayoom 2
Android O & Java Notes
Step 3 Download the Graphics for the App:..............................................................................................................1
Step 4 Generate New App Icons:...............................................................................................................................1
Step 5 Add the Graphics to the Project:.....................................................................................................................1
Step 6 Design the App in the Layout XML:.................................................................................................................1
Step 7 Link the Layout to Java Code:.........................................................................................................................1
Step 8 Check for Bugs and Predict the Future............................................................................................................1
Step 9 Submit Your Coursework [Optional]:..............................................................................................................1
Magic 8 Ball Challenge Solution................................................................................................................................1
Java Programming for Beginners:.................................................................................................................................1
Introduction to the Programming Modules:..............................................................................................................1
Setting up a Pure Java Project in Android Studio:......................................................................................................1
Code Blocks, the main() Method, and Code Compilation Explained:..........................................................................1
Comments, Variables and Types:..............................................................................................................................1
Why you'll want to comment your code:...................................................................................................................1
Methods Part 1 - Defining and Calling a Method.......................................................................................................1
Methods Part 2 - Adding Parameters:.......................................................................................................................1
Methods Part 3 - Multiple Parameters and Returning a Value:..................................................................................1
Control Flow Conditional Statements (IFELSE):..........................................................................................................1
Make a BMI Calculator [Challenge]:..........................................................................................................................1
Build a Music App [Tutorial]:........................................................................................................................................1
What Will We Make:.................................................................................................................................................1
Setting Up the Project & Using Colours as Resources:................................................................................................1
Download the Skeleton Project:............................................................................................................................1
How to Use Android Documentation and Other Resources:......................................................................................1
Google Samples on Github:...................................................................................................................................1
Android API Guide:...............................................................................................................................................1
Android API Reference:.........................................................................................................................................1
Stack Overflow - Q&A Site for Programming Problems:.........................................................................................1
Calling the Constructor to Create a SoundPool:.........................................................................................................1
Member Variables and the Importance of Scope:......................................................................................................1
Using the onClick Property instead of a Listener:.......................................................................................................1
How to Play a Sound in Your App using the SoundPool:............................................................................................1
The Code for the Complete Xylophone Project:.........................................................................................................1
Build a Quiz App and Learn about the MVC Design Pattern [Tutorial]:...........................................................................1

Abdul Qayoom 3
Android O & Java Notes
What Will We Make:.................................................................................................................................................1
Import & Familiarise Yourself with the Skeleton Project:..........................................................................................1
Download the Skeleton Project:............................................................................................................................1
Understand Casting & Link the Layout to the Java Code:...........................................................................................1
Set an OnClickListener & Implement a Toast Message:.............................................................................................1
Create the Model Class & Generate Code with Android Studio:.................................................................................1
Boolean - A Data Type that Holds One of Two Values:...............................................................................................1
The Model View Controller (MVC) Design Pattern and Why We Use It:.....................................................................1
Retrieve Quiz Questions from an Array and Display them on Screen:........................................................................1
Update Questions on Screen and Interpret Errors in the Logcat:...............................................................................1
Check the User's Answer and Give Feedback:............................................................................................................1
Working with the Progress Bar and Tracking Score:...................................................................................................1
Fixing the Screen Orientation and Displaying an AlertDialog:....................................................................................1
An Overview of How an Android App Works:............................................................................................................1
The Activity Lifecycle:...............................................................................................................................................1
Saving State using the Bundle and Null Pointer Exceptions:......................................................................................1
The Difference between Zero and Null:.....................................................................................................................1
Do You Want This:....................................................................................................................................................1
The Code for the Complete Quizzler Project:.............................................................................................................1
Coding Challenge #3 - Control Flow - Build a Story App Like Lifeline:.............................................................................1
What You'll Create:...................................................................................................................................................1
Step 1 Setup the Project:..........................................................................................................................................1
Step 2 Examine the activity_main.xml and the strings.xml:.......................................................................................1
Step 3 Create the Variables for the Views:................................................................................................................1
Step 4 Wire up the Views to the Java Code:..............................................................................................................1
Step 5 Detect Clicks on the Buttons:..........................................................................................................................1
Step 6 Take the Adventure One Step Further:...........................................................................................................1
Step 7 Create a Variable to Track the Player's Path:..................................................................................................1
Step 8 Complete the Game Using Conditionals to Check the State:............................................................................1
Step 9 Submit Your Project [Optional]:......................................................................................................................1
Destini Challenge Solution:.......................................................................................................................................1
Working with the Constraint Layout & Creating Multiple Layouts:................................................................................1
Converting to a Constraint Layout & Designing for Multiple Screens:........................................................................1
Setting Constraints and Using Built-In Styles:............................................................................................................1
Linking Views to Each Other:.....................................................................................................................................1

Abdul Qayoom 4
Android O & Java Notes
Using Guidelines to Position Layout Elements:..........................................................................................................1
Automatically Inferring Constraints with Android Studio:.........................................................................................1
Resource Qualifiers and Layouts for Landscape Mode:..............................................................................................1
Internationalization, Resource Qualifiers and the Translations Editor:......................................................................1
Creating a Landscape Layout and Adding Content Descriptions for Accessibility:.......................................................1
Complete Layout Source Code:.................................................................................................................................1
Java Programming for Intermediates:...........................................................................................................................1
Set up a Standard Java Project in Android Studio:.....................................................................................................1
Virtual Machines & Program Entry Points main() vs the Android Intent Filter:...........................................................1
Classes and Objects Demystified:..............................................................................................................................1
Fields, the Dot Notation, and an Object's State:........................................................................................................1
Using GettersSetters & Access Modifiers Public v.s. Private:......................................................................................1
No-Argument Constructors v.s. Parameterised Constructors:....................................................................................1
Object Behaviour & Using Methods:.........................................................................................................................1
The static Keyword Class Variables & Class Methods:................................................................................................1
The Toast Class Source Code:................................................................................................................................1
Toast Class Documentation:..................................................................................................................................1
Inheritance, the protected Modifier & the @Override Annotation:...........................................................................1
Bonus Question........................................................................................................................................................1
Build a Weather App - Use GPS and APIs to Get Data from the Web [Tutorial]:.............................................................1
What Will We Make:.................................................................................................................................................1
Project Setup & Overview:........................................................................................................................................1
Download the Skeleton Project:............................................................................................................................1
Get your Own free API Key (App ID):........................................................................................................................1
Gradle Project & Module Scripts and Android SDK Compatibility:.............................................................................1
Adding External Libraries as Dependencies with Gradle:...........................................................................................1
James Smith's site for the Android Async Http Client Library:................................................................................1
Manage App Permissions in the Android Manifest:...................................................................................................1
Runtime Permissions & Using the LocationManager to Get Your Location:................................................................1
Networking, HTTP Requests, Status Codes & APIs:....................................................................................................1
List of HTTP Status Codes:.....................................................................................................................................1
OpenWeatherMap API Documentation:................................................................................................................1
Transport for London API Documentation:............................................................................................................1
Markit On Demand API Documentation:...............................................................................................................1
Twitter API Documentation:..................................................................................................................................1

Abdul Qayoom 5
Android O & Java Notes
HTTP Response Cheat Sheet:.....................................................................................................................................1
Making the HTTP Request for Weather Data:............................................................................................................1
The JSON Format Explained:.....................................................................................................................................1
JSON Homepage:..................................................................................................................................................1
JSON Visualiser JSON Editor Online:......................................................................................................................1
JSON Visualiser JSON Mate:..................................................................................................................................1
Do you know JSON:...................................................................................................................................................1
Parse the JSON and Handle Exceptions with a Try-Catch Block:.................................................................................1
Full List of Weather Conditions:................................................................................................................................1
Update the UI and Show the Weather to the User:...................................................................................................1
Create a New Activity and Link Activity & Layout:.....................................................................................................1
Using Intents to Navigate Between Activities:...........................................................................................................1
Android Intent Documentation:............................................................................................................................1
Intent Extras and EditText onEditorAction() Callbacks:..............................................................................................1
API Call with a City Name, the Logical NOT and Freeing Up Resources:......................................................................1
The Complete Code for the Clima App:.....................................................................................................................1
Coding Challenge #4 - REST & APIs - Build a Bitcoin Price Tracker:.................................................................................1
What You Will Create:..............................................................................................................................................1
Step 1 Import the Project:.........................................................................................................................................1
Step 2 Check out the Files in the Stub Project:...........................................................................................................1
Step 3 Add App Permissions to Access the Internet:..................................................................................................1
Step 4 Add the Android Asynchronous Http Client Dependency:...............................................................................1
Step 5 Set up the Spinner View:................................................................................................................................1
Step 6 Interpret the API Docs and Request a JSON:...................................................................................................1
Step 7 Make a GET Request Using the Networking Code:..........................................................................................1
Step 8 Parse the JSON and update the User Interface:...............................................................................................1
Step 9 Submit Your Assignment on Github [Optional]:..............................................................................................1
Bitcoin Ticker Challenge Solution:.............................................................................................................................1
Build a WhatsApp Clone and learn to use Cloud Data Storage [Tutorial]:......................................................................1
What Will We Make:.................................................................................................................................................1
Project Tour and Overview of Existing Code:.............................................................................................................1
Download the Project Stub:..................................................................................................................................1
What is Firebase:......................................................................................................................................................1
Firebase website:..................................................................................................................................................1
Firebase & Big Brother:.........................................................................................................................................1

Abdul Qayoom 6
Android O & Java Notes
Create a New Project on Firebase and Configure the Android App:...........................................................................1
Full List of Firebase Dependencies:........................................................................................................................1
Access the Firebase Console:.................................................................................................................................1
Registering New Users, Validating Data & the Builder Design Pattern:......................................................................1
String Documentation:..........................................................................................................................................1
EditText getText() Method:...................................................................................................................................1
Android Dialog Guide:...........................................................................................................................................1
Task Class Documentation:...................................................................................................................................1
AlertDialog.Builder Class Documentation:.............................................................................................................1
FirebaseAuth Documentation:..............................................................................................................................1
Storing Data Locally (on Device) using SharedPreferences:........................................................................................1
SharedPreferences Class Documentation:.............................................................................................................1
getSharedPreferences() Method Documentation:.................................................................................................1
Guide on using SharedPreferences:.......................................................................................................................1
Handling User Login with FirebaseAuth:....................................................................................................................1
Retrieve the Locally Stored Data:..............................................................................................................................1
Create the Model Class & Save Data to the Cloud:....................................................................................................1
DatabaseReference Class Documentation:............................................................................................................1
FirebaseDatabase Class Documentation:...............................................................................................................1
ListViews, Adapters & ArrayLists:..............................................................................................................................1
Building Layouts with an Adapter:.........................................................................................................................1
Firebase DataSnapshot Class Documentation:.......................................................................................................1
BaseAdapter Class Documentation:.......................................................................................................................1
Oracle ArrayList Class Documentation:..................................................................................................................1
Implementing the ViewHolder Pattern:.....................................................................................................................1
Smooth Scrolling in Android:.................................................................................................................................1
Retrieve Data from Firebase with a ChildEventListener:............................................................................................1
Firebase ChildEventListener Documentation:........................................................................................................1
Oracle ArrayList Class Documentation:..................................................................................................................1
Styling Views with 9 Patch Images:...........................................................................................................................1
Creating a 9-Patch (Resizable Bitmap):..................................................................................................................1
Guide to 9-Patch Graphics:....................................................................................................................................1
Download the Complete Code for the FlashChat App:...............................................................................................1
Challenge Persist the Username in Firebase instead of Local Storage:.......................................................................1
Solution Persisting a username in Firebase:..............................................................................................................1

Abdul Qayoom 7
Android O & Java Notes
App Design Course Introduction:..................................................................................................................................1
Introduction to the App Design Course:....................................................................................................................1
Why is Design Important for an App Entrepreneur:...................................................................................................1
Designer versus Non-Designer Thinking:...................................................................................................................1
Colour Theory:..............................................................................................................................................................1
Understanding the Mood of Your Colour Palette:......................................................................................................1
How to Combine Colours and Formulate Colour Palettes:.........................................................................................1
Tools for Designing with Colour:...............................................................................................................................1
Color Hunt:...........................................................................................................................................................1
Material Palette:...................................................................................................................................................1
Color Zilla:.............................................................................................................................................................1
Flat UI Colors:.......................................................................................................................................................1
Further Reading on Designing with Colour:...............................................................................................................1
Typography:.................................................................................................................................................................1
Introduction to Typography:.....................................................................................................................................1
The Serif Font Family - Origins and Use:....................................................................................................................1
The Sans Serif Font Family - Origins and Use:............................................................................................................1
How Typography Determines Readability:................................................................................................................1
How to Combine Fonts Like Pro:...............................................................................................................................1
Further Reading about Typography:..........................................................................................................................1
The Fundamentals of User Interface (UI) Design for Mobile:.........................................................................................1
Introduction to User Interface Design:......................................................................................................................1
The Tour Guide Approach to UI Design:....................................................................................................................1
Web Design in 4 Minutes:.....................................................................................................................................1
The Importance of Alignment:..................................................................................................................................1
What is Good Practice in Interaction Design:.............................................................................................................1
Colour in User Interface Design:................................................................................................................................1
Link to the Dribbble search by colour tool:............................................................................................................1
The Many Ways of Designing Text Overlays:.............................................................................................................1
How to Be an Attention Architect:............................................................................................................................1
What Clients Say and What Clients Mean - Translating Client Speak:.....................................................................1
Further Reading on User Interface Design:................................................................................................................1
The Fundamentals of User Experience (UX) Design for Mobile:.....................................................................................1
Introduction to User Experience Design:...................................................................................................................1
Usability:..................................................................................................................................................................1

Abdul Qayoom 8
Android O & Java Notes
Asking for Permissions:.............................................................................................................................................1
User Profiling:...........................................................................................................................................................1
Form vs. Function:....................................................................................................................................................1
Consistency:.............................................................................................................................................................1
Simplicity:.................................................................................................................................................................1
Don't Make Me Think:..............................................................................................................................................1
Onboarding:.............................................................................................................................................................1
Idiot Boxes:...............................................................................................................................................................1
Further Reading on User Experience Design:.............................................................................................................1
Designing for iOS vs. Android - What are the Important Differences:............................................................................1
Android vs. iOS Design:.............................................................................................................................................1
Navigation:...............................................................................................................................................................1
The Devil is in the Details:.........................................................................................................................................1
Differences in Icon Design:........................................................................................................................................1
Flat vs. Material Design:............................................................................................................................................1
Differences in Establishing Visual Hierarchy:.............................................................................................................1
iOS and Android Design Guidelines:..........................................................................................................................1
Material Design Guidelines:......................................................................................................................................1
iOS Human Interface Design Guidelines:...................................................................................................................1
Putting it All Together - A Step-By-Step Guide to the Mobile Design Workflow:............................................................1
Step 1 Design Patterns and Colour Palettes:..............................................................................................................1
Mobile Patterns:...................................................................................................................................................1
Flat UI Colors:.......................................................................................................................................................1
Patterns:...............................................................................................................................................................1
Material Design Palette for Android:.....................................................................................................................1
Color Hunt:...........................................................................................................................................................1
Step 2 How to Design User Flow Diagrams:...............................................................................................................1
Step 3 How to Create Wireframes:............................................................................................................................1
Free Download of Pop App by WooMoo (Google Play Store):................................................................................1
Free Download of Pop App by WooMoo (Windows Tablet):..................................................................................1
Free Download of Pop App by WooMoo (iOS App Store):......................................................................................1
Wireframe cc:......................................................................................................................................................1
UI Stencils' Free Downloadable Design Templates:................................................................................................1
Step 4 How to Create Professional Mockups:............................................................................................................1
Sketch 3:...............................................................................................................................................................1

Abdul Qayoom 9
Android O & Java Notes
PhotoshopIllustrator:............................................................................................................................................1
Canva:...................................................................................................................................................................1
Marvel:.................................................................................................................................................................1
How to Use Sketch (4.1) to Create Mockups for Mobile:...........................................................................................1
Mockup for the example workout app:.................................................................................................................1
How to Use Canva to Create Mockups:.....................................................................................................................1
Canva:...................................................................................................................................................................1
Your Turn to Create Your Own Mockups:..................................................................................................................1
Alternatives to Sketch - UX Pin:.............................................................................................................................1
Tools for Creating Mockups - Smart Mockups:.......................................................................................................1
Tools for Creating Mockups - Magic Mockups:.......................................................................................................1
Tools for Creating Mockups – Placeit:....................................................................................................................1
Alternatives to Sketch – Invisionapp:....................................................................................................................1
Alternatives to Sketch – Marvel:...........................................................................................................................1
Alternatives to Sketch – Moqups:..........................................................................................................................1
Step 5 How to Create Animated App Prototypes:......................................................................................................1
Principle:...............................................................................................................................................................1
Marvel App:..........................................................................................................................................................1
InVision App:........................................................................................................................................................1
Proto.io:...............................................................................................................................................................1
Mac Keynote App:.................................................................................................................................................1
How to Create Animated Prototypes with Keynote:..................................................................................................1
How to Create Prototypes with Marvel App:.............................................................................................................1
Check Out My Example Prototype Create with Sketch and Marvel:.......................................................................1
Get Access to Mavel App Here:.............................................................................................................................1
Your Turn to Create a Prototype:..............................................................................................................................1
My Example Prototype Created with Marvel App:.................................................................................................1
Download the Free Android Marvel App to See Your App on Your Phone:.............................................................1
Download the Free iOS Marvel App to See Your App on Your Phone:....................................................................1
Resources:....................................................................................................................................................................1
Where to Find Free-For-Commercial Use Image Assets:............................................................................................1
Where to Find Free-For-Commercial Use Icons:.........................................................................................................1
Keep Learning and Improving:..................................................................................................................................1
Sign up to the LAB Report here:............................................................................................................................1
The Complete App Marketing Course:..........................................................................................................................1

Abdul Qayoom 10
Android O & Java Notes
The Importance of App Marketing:...........................................................................................................................1
The Fallacy of Build it and They Will Come:...............................................................................................................1
Idea Validation - Save Yourself Time and Money:.........................................................................................................1
The Importance of Idea Validation:...........................................................................................................................1
The Simplest Way of Validating Your Idea - The Starbucks Method:..........................................................................1
Using Google Trends to Estimate the Size of Your Market:........................................................................................1
Google Adwords Keyword Planner:.......................................................................................................................1
Google Trends:......................................................................................................................................................1
The Landing Page Validation Method:.......................................................................................................................1
How to Create a Landing Page Website in Less than an Hour:....................................................................................1
Wordpress:...........................................................................................................................................................1
Start Bootstrap:....................................................................................................................................................1
Unbounce:............................................................................................................................................................1
Leadpages:............................................................................................................................................................1
Square Space:.......................................................................................................................................................1
Creating a Minimum Viable Product:........................................................................................................................1
Gimlet Media - MVP Story:....................................................................................................................................1
Gimlet Media - Startup Stories (Grooveshark Story):.............................................................................................1
Quick MVP:...........................................................................................................................................................1
Using Crowd-funding to Validate and Fund Your Idea:..............................................................................................1
The Complete Crowdfunding Course. Get it for $19 with this Code!.......................................................................1
App Monetization Methods - How to Make Money from Your App:..............................................................................1
How to Monetise Your App on iOS vs. Android:........................................................................................................1
When You Should Create a Paid App:........................................................................................................................1
When to use In-App Advertisements:........................................................................................................................1
How You Thought About These Alternative Monetisation Models:...........................................................................1
How to Optimize Your App Store Listing:......................................................................................................................1
How to Get an App icon Designed without Breaking the Bank:..................................................................................1
Fiverr:...................................................................................................................................................................1
99 Designs:...........................................................................................................................................................1
Split Testing for Super Success:.................................................................................................................................1
Store Maven:........................................................................................................................................................1
What Makes a Good App Icon:..................................................................................................................................1
The Dos and Don'ts of Making App Screenshots:.......................................................................................................1
MockUPhone:.......................................................................................................................................................1

Abdul Qayoom 11
Android O & Java Notes
LaunchKit (now open source):...............................................................................................................................1
Tools for Building Screenshots:.................................................................................................................................1
Growth Hacking Techniques for App Downloads:..........................................................................................................1
Your First 1000 Customers:.......................................................................................................................................1
1000 True Fans:.....................................................................................................................................................1
Building an Email List:...............................................................................................................................................1
The All-Important Landing Page:...............................................................................................................................1
The Psychology of Influence - Robert Cialdini:.......................................................................................................1
Thinking, Fast and Slow = Daniel Kahneman:.........................................................................................................1
Blogging Your Way to Success:..................................................................................................................................1
Loose Leaf:............................................................................................................................................................1
A Blogging Example:..............................................................................................................................................1
Content Marketing for App Downloads:....................................................................................................................1
Fit Men Cook:.......................................................................................................................................................1
7 Minute Workout:...............................................................................................................................................1
How to Successfully Launch on Product Hunt:...........................................................................................................1
PH Leaderboard:...................................................................................................................................................1
Product Hunt:.......................................................................................................................................................1
How to Launch on Beta List:......................................................................................................................................1
BetaList:................................................................................................................................................................1
How to Launch on Hacker News:...............................................................................................................................1
Hacker News:........................................................................................................................................................1
If At First You Don't Succeed...:.................................................................................................................................1
Cross Promotion:......................................................................................................................................................1
Social Referrals and Social Queuing:.........................................................................................................................1
Maître:.................................................................................................................................................................1
How to Make Social Media Work for You:.................................................................................................................1
How to Get Press Coverage for Your App:.....................................................................................................................1
Do I need a PR Agency:.............................................................................................................................................1
Not All Press is Created Equal:..................................................................................................................................1
How to Craft Your Story:...........................................................................................................................................1
How to Craft Your Pitch:...........................................................................................................................................1
How to Figure Out Which Journalists to Pitch:...........................................................................................................1
Buzzsumo:............................................................................................................................................................1
How to Find Anyone's Email Address:.......................................................................................................................1

Abdul Qayoom 12
Android O & Java Notes
Voila Norbert:.......................................................................................................................................................1
How to Pitch a Journalist:.........................................................................................................................................1
Boomerang for Gmail:...........................................................................................................................................1
HubSpot Sales (previously known as SideKick):.....................................................................................................1
Just-Add-Water Journalist Pitch Email:......................................................................................................................1
Establishing a Relationship with a Journalist:............................................................................................................1
100 Journalists you should follow on Twitter:........................................................................................................1
What if You Still Can't Get Anyone to Write About You:............................................................................................1
Journo Requests:..................................................................................................................................................1
Response Source:..................................................................................................................................................1
HARO:...................................................................................................................................................................1
Final Tips on Getting Press:.......................................................................................................................................1
The Press Release is Dead (Mike Butcher):............................................................................................................1
Trust me, I'm lying (Ryan Holiday):........................................................................................................................1
How to Get Your App Featured on the App Store:.........................................................................................................1
How to Get Featured on the App Store:....................................................................................................................1
Only on the App Store:.............................................................................................................................................1
Work with the Corporate Mindset:...........................................................................................................................1
Native vs. Cross-Platform Apps:................................................................................................................................1
Tips and Tricks for Getting Featured:.........................................................................................................................1
App Store Optimization - How to Rank Higher on the App Store Search Algorithm:.......................................................1
What is App Store Optimisation (ASO)?....................................................................................................................1
Top Tips to Optimise Your App Store Listing:.............................................................................................................1
My Complete ASO Workflow:...................................................................................................................................1
Using Apple Search Ads as a Research Tool:..............................................................................................................1
Early vs. Late Game Strategies:.................................................................................................................................1
Differences Between Google Play and Apple App Store:............................................................................................1
The Right Way of Using Paid Advertising to Drive App Downloads:...............................................................................1
When to use Paid Advertising or App Marketing:......................................................................................................1
Always Test Before You Advertise:............................................................................................................................1
Which Platform to Advertise On:..............................................................................................................................1
How Much Does it Cost:............................................................................................................................................1
How to Setup Your Facebook Ad:..............................................................................................................................1
Use Your Competitors' Ad Budget:............................................................................................................................1
Where Can I Find More Customers:...........................................................................................................................1

Abdul Qayoom 13
Android O & Java Notes
One Weird Trick to Get More Money from Apple:.....................................................................................................1
App Store Reviews and Ratings:....................................................................................................................................1
How to Get More 5 Star Ratings and Reviews:..........................................................................................................1
Use This Free Tools to Monitor Your App Reviews:...................................................................................................1
How to Use App Analytics to Increase User Retention:.................................................................................................1
How to use App Analytics to Increase User Retention:..............................................................................................1
White Hat vs. Black Hat Methods of Getting More App Downloads and Revenue:.........................................................1
White Hat Techniques:..............................................................................................................................................1
Black Hat Techniques:...............................................................................................................................................1
Bonus How to Build Your App Showcase Website:........................................................................................................1
A 5 Second Way of Building a Web Page for Your iOS App:........................................................................................1
How to Use Bootstrap to Build Your App Showcase Website:....................................................................................1
Guidance on Setting up a Custom Domain and Hosting on Github:........................................................................1
Your Turn:....................................................................................................................................................................1
It's Time to Work Out Your Marketing Strategy:........................................................................................................1
Monthly Student Built App Showcase:......................................................................................................................1

Abdul Qayoom 14
Android O & Java Notes

Set up for Android Development:


How the Course is Structured:
 This course is structured to create multiple google play store apps.
 We learn here from zero to marketing of our applications & monetization.
 We will learn to develop app & developing best practices & apply in real android apps by following
documentations & online resources.

Meet Instructor:

 We will build sun shine app together.


o It will use most of useable APIs.

What is android studio?


 Official IDE (Integrated Development Environment) for android development.
 Based on Intel IJ platform.
 IDE helps to enhance the productivity of developer & get most of in little time.
 Android have flexible gradle system & it support instant run (Run without closing app with
new changes) & support debugging.
 Android is 4 level stack:
o Linux kernel:
 Linux kernel is base & it handles low level tasks like hardware drivers &
power management.
o C,C++ libraries & android Run time:
 ART help to run app own its own instance.
o Application framework:
o Application Layer:
 Gradle:
o Gradle helps in building project, handle dependencies & custom build logic.
 Application building steps:

Abdul Qayoom 15
Android O & Java Notes

 Project build by gradle & convert into app.


 Than android signs that app & ADB (Android Debug bridge) installs app on device.

How to Get All the Free Stuff:


 With this course we get much of assets cost up to 5 thousands US Dollars.
 Assets includes gradients for backgrounds, icons & icons creating tools.
 And a great book 12 rules to code.

Download Your Massive Bundle Here


 Download all resources from this links.

Developing for Android - Tools for this Course:


 We need & minimum 8GB of RAM & 500GB HD but SSD will enhance android studio performance very
much.
 We have to install Android Studio (Official development environment) on our PC.
 Android studio is supported by google, by which we can develop apps for android.
 Android studio provide us environment to write apps logic as well as design of our applications.
 We can run our apps on physical android device (Recommended) & also by Virtual device or emulator.

Setup on Mac Android Studio, the JDK & Connecting a Physical Device:
 We need a JDK (Java development kit), JDK includes JRE (Java runtime environment) & Javac (Java
Compiler).
 We can check about JDk installation by typing command in terminal (Java -version), if we get version
number of JDk then it is already available in our system & we don’t need.
 If you don’t get version number then download it & install it.

Download the Java Development Kit:


 Download JDK from this link.
 Download latest development kit (dmg format)from provided link & install by regular
installation way.

Download Android Studio:


 Links for download Android Studio.
 Download android studio according to your OS.
 Start installation & it will be ready soon to install.

Connect with physical phone:


 Take your physical phone & go to your settings.
 Look for build number & start developers’ mode for your phone by some clicks on it.

Abdul Qayoom 16
Android O & Java Notes
 After some of you will be part of secret developer’s club & it will show a new menu for you in
phone (Developers Option).
 Go to the developer’s option menu & see for USB debugging & make it enable & allow.
 Grab USB data cable and connect with system & system will recognize you phone for testing
you project or app in android studio.
 We can see our plugged phone & its related information in Android Logcat (Android Monitor
in older version of android studio then 3.0)tab.
 Our android device & system communicate through ADB (Android Debug Bridge)

Setup on Windows Android Studio, the JDK & Connecting a Physical Device:
 We need to check our system type (64 bit or 32 bit) so we need JDK according to that.
 We need a JDK (Java development kit), JDK includes JRE (Java runtime environment) & Javac (Java
Compiler).
 We can check about JDk installation by typing command in terminal (Java -version), if we get version
number of JDk then it is already available in our system & we don’t need.
 If you don’t get version number then download it & install it.

Download the Java Development Kit:


 Download JDK from this link.
 Download latest development kit in (64- or 32-bit version according system type) (EXE or ZIP
format)from provided link & install by regular installation way.

Download Android Studio:


 Links for download Android Studio.
 Download android studio according to your OS.
 Start installation & it will be ready soon to install.

Install USB OEM device:


 download OEM:
 OEM (Original Equipment Manufacturers) is used for testing the device of windows’
 For MAC or Linux, we don’t need OEM drivers.
 Steps for getting & installing OEM drivers available in links.
 Follow steps to install android studio.

Connect with physical phone:


 Take your physical phone & go to your settings.
 Look for build number & start developers’ mode for your phone by some clicks on it.
 After some of you will be part of secret developer club & it will show a new menu for you in
phone (Developers Option).
 Go to the developer’s option menu & see for USB debugging & make it enable & allow.
 Grab USB data cable and connect with system & system will recognize you phone for testing
you project or app in android studio.
 We can see our plugged phone & its related information in Android Logcat (Android Monitor
in older version of android studio then 3.0)tab.
 Our android device & system communicate through ADB (Android Debug Bridge).

Troubleshooting Android Device Not Recognized:


 There are some problems which make our device unrecognized by system:

Abdul Qayoom 17
Android O & Java Notes
o Data cable is not good or loose.
o Cable is just charging the phone so make sure you have a data cable.
o ADB or OEM is not installed if you are using windows (If windows does not download that
driver, then go to that links & download according to your device configurations).

Configure Android Studio for Productivity Themes, Auto-Import & SDKs:


 These are good practices & make us more productive.
o Create a dedicated folder for saving your work.
o Open Android studio & go to preferences or setting:
 Set to dark theme.
 Go to editor & increase font size so code is easier to read.
 Set enable to auto import.
 Set naming convention which android can follow when we generate code by android
studio (Set m for fields & s for static fields).
 Go to android SDK platforms & download one latest version & other as same as your
phone.
 If you want to run app on emulator then also download any system image.

How to Set Up an Android Emulator with Hardware Acceleration:


 Android emulator is a virtual device which runs on system or computer.
 Emulator is a software which works same as hardware device.
 Reasons behind using android emulator:
o We don’t have physical phone to test our apps.
o We can test our apps on multiple devices (without buying those).
 We have to install Intel System image for intel processors & ARM for AMD processors.
 After this all go to AVD Manager for creating virtual device.

Intel's HAXM Install Instructions:


 Hardware Accelerator Execution Manager helps to run faster to our emulator & comes only
with Intel processor.
 Install HAXM for your emulator if you are using intel processor.

Official Android Guide to Configuring Hardware Acceleration:


 Link.

Genymotion - an alternative Android emulator:


 Genymotion is an emulator alternative solution.
 These are faster than built in emulators but we have to buy them.
 Explore all plans for using gene motions link & other information about those.

Slow PC Make it Run Faster with these Performance Tricks [Windows]


 Close all other programs.
 Give android studio priority.
 Disable or temporary suspend your antivirus.
 Optimize windows to enhance performance (Animations, wallpapers & fancy graphics) by just adjust
to best performance from system settings.

Abdul Qayoom 18
Android O & Java Notes

Abdul Qayoom 19
Android O & Java Notes

Build the I am Rich App to learn about project structure and XML [Tutorial]
What Will We Make:
 We are going to create an app named “I am Rich”.
 During this project we will learn about work flow of android studio.
 We will also learn how to arrange apps of screen.
 We will get introduced by XML (Extensible Markup Language) & we will use XML to design our
layouts.

Android Activity:
 Application ?
o Application is collection of components which work with each other.
o Four types of components which make a app:
 Activity:
 Activity is a single focused thing that the user can do.
 Activity is responsible for most of user interaction.
 Activity is responsible for creating the window that our application uses
to draw and receive events from the system.
 An application can contain a single activity of series of connected
activities.
 System maintains the stack for all activities of app.
 Each activity contains a layout, where we defined our information & tell
system that what to display and how to display.
 Service:
 Broadcast receivers:
 Content Providers:
o Android knows about each of the component’s b/c they all should be registered in android
manifest.xml file.

Exercise 1.1:
 Change the constraint layout to frame layout:
<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"
tools:context=".MainActivity">
 Remove old constraint layout attributes:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:padding="16dp"
android:textSize="20sp"
android:id="@+id/tv_toy_names"
/>
 Give text view 16dp of padding & set text size to 20sp:

Abdul Qayoom 20
Android O & Java Notes
android:padding="16dp"
android:textSize="20sp"

Creating a New Android Studio Project and Choosing the API Level:
 Create a new project by clicking on new project button & select empty activity.
 Provide name of app (I am Rich) with API level 19 (Minimum version to run our app) & hit finish.
 Project name is the combination of company domain & app name, it help google play store to identify
application uniquely.
 Our project will be built by Gradle (A tool which help our project be build)

Working with the Layout Editor, Strings, and App Themes:


 We will use layout file (XML file) to design our layout.
 Layout file will be available in (res -> layout) folder.
 XML layout file have preview & it can be edit by just drag & drop & also by code.
 Now open this file & copy all code & paste it in main layout xml file.
o Here is this file we have updated the layout with relative layout which is an easier way to
start.
o Now go to (values -> theme) & select a no action bar theme.
parent="Theme.MaterialComponents.DayNight.NoActionBar"
o Component tree shows the components which we have used in our layout.
o Attributed of Properties pane contains the properties of our selected widget.
o TextView has a attributed named “text” by which we can change the text of text view.
o TextView use to show the text on screen.
o We can change the text size by attribute text size.
o SP (Scale able pixels) is the unit for text size.
o Hardcoded string is not good practice we should store string in string resource & then use &
we add can in our text in string resource folder after adding view also.
o All the text used in app should be ideally in a separate file (res -> values -> strings), which can
help us in localization & changing when we want.

<string name="rich">I am Rich!</string>


Adding Graphics to a Project and using ImageViews:
 Download the graphics file.
 Graphics can be (Pieces of text (Strings, layouts, values), app icons).
 Drawable folder will contains the graphics which will show on the screen so, we have to copy files
inside it.
 ImageView is a widget, in which we can add our image to show on screen.
 Background color will add the background color of that widget.
android:background="@color/it"
 Text color attributes is text attribute which provide color to text.
android:textColor="#ffffff"
 Text style attribute change the style (bold, italic, normal).
android:textStyle="bold|italic"
 Layout center horizontal is a relative layout attribute which center widget horizontally in relative
layout.
android:layout_centerHorizontal="true"
Abdul Qayoom 21
Android O & Java Notes
What is XML and How Does it Work:
 In late 1970s GML (Generalized markup language), Charles came up with notation of tags.

 After usage of GML in all field and industries to provide layout structure then Charles give another
version of GML, SGML (Standard Generalized Markup Language) & wrote the book for document
professionals.
 Tim Berners lee, in 1990s set a bunch of tags & create a layout of website, which is currently known as
HTML (Hyper Text Markup language).
 XML (Extensible Markup Language) is meta notation & set of rules like punctuation & it allow
software engineers to create their own tag sets to describe their data.
 Component comes in XML for easily search about specific components.

XML Code Demystified


Setting a Custom Launcher Icon:
 Now we will set launcher icon for our app, which will appear in our device with name.
 Launcher icons have multiple sizes which set on app automatically according to device specification.
 Now open mipmap folder in explorer & set your icons assets in specified folders.
 Go to the android manifest file & update the value of icon & round icon.
android:icon="@mipmap/diamond_launcher"
android:roundIcon="@mipmap/diamond_launcher_round"
Running the App to Test it Out:
 We can run our app on virtual device and physical android device(Connect by cable if you have
android device).
 Click play button, It will build project -> Install app in device & launch app.

Design the App's Screen in the Layout XML:


 In android studio we have a code of our layout & also we can manage our layout in graphical mode.
 Graphical mode support drag & drop widgets on canvas & show all attributes by side.
 XML code show the code of those widgets or layout.
 When we add anything in graphical mode android generate the code for it in XML file.

Understand the Android Project Structure:


 Android Project is a collection of files which create a complete project.
 Android project has four main parts (Manifest files, Java code files, res files, gradle scripts).
 Manifest files have information for whole project about (About App, how to communicate with OS or
Google play store, app components, app permissions).
Abdul Qayoom 22
Android O & Java Notes
 Java files contains the all-programming logic.
 Res fields contains all the elements about design of app & elements which are visible on screens.
 Drawable folders contains the graphics like images & much more.
 Layout folder contains the layouts of application.
 Mipmap folder contains icons of application.
 Values folder contains values of (Strings, Colors, Styles, dimens).
 String folder contains the string values or content of application which help in localization &
translation of app to another language.
 Colors folders contains the color values of application or colors of application.
 Styles folder contains the themes of application & styles defined for any widget.
 Dimens folders contains the dimension values.
 Gradle is the builder which builds all files & converts them to apk file which can install on android
device.

The Wonderful World of Version Control Installing Git:


 Git is version control system, which controls and manages the versions of our project so we revert
back to specified version if we stuck on any stage.

Installing Git for Mac:


o Go to this link then download & install git.

Installing Git for Windows:


o Go to this link then download & install git.
o Set git in version control of android studio settings.
o Set the environment variable with location of git bin folder.

Git Installation Links

Abdul Qayoom 23
Android O & Java Notes

Coding Challenge #1 - Using the Layout Editor in Android Studio and


Github:
What are the Coding Challenges?
 Challenges during our practices will start from easy to hard in the sense of difficulty.
 B/c learning coding is all about learning by doing.
 We will see about product which will look at the end & make some to reach that destination.

What You Will Create:


 Create I am poor app.
 During this challenge we will learn to download code from git hub & use in our project.
 During this challenge we have setup the custom app icon & design the app layout.

 Final app will look like that, but we change color & arrangement of layout widget as we want.
 Steps to success:
o Successfully import our project from git hub.
o Arrange the TextView and ImageView user interface elements on screen.
o Set Custom app icon.
o Build & run app on the device.

Step 1 Importing Projects from GitHub and Opening them in Android Studio:
 Open git hub site on browser & got the link.
 Clone that skeleton code of assignment.
 If download & do not want to use same config then extract & copy code to your configured project.

Create a Github Account:


o Git hub account is free & we can use it for saving our work.

Abdul Qayoom 24
Android O & Java Notes
Invitation link for the I am Poor assignment
Step 2 Add a TextView:
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="I am Poor!"
android:textColor="#FFFFFF"
android:textSize="72sp"
android:textStyle="bold|italic" />
Step 3 Add an ImageView:
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_centerVertical="true"
app:srcCompat="@drawable/coal" />
Step 4 Set App icon
 Take sane coal image.
 Make its image assets
 Assign round & icon in Manifest file.
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
Step 4 Run the App
 Run on emulator of physical device.

Step 5 How to Submit Your Assignment on Github [Optional]:


 Push your assignment to your git hub account.

I am Poor Challenge Solution:


 Done by own self.

Abdul Qayoom 25
Android O & Java Notes

Build a Dice App to Learn Java & XML Fundamentals [Tutorial]:


What Will We Make:
 During this lesson we will learn & develop dice app.
 We learn to design some complex layout & write java code to handle that.
 How to detect clicks.
 How to use arrays to hold the data.

Start a New Project and Style the App with the Theme Editor:
 Create project with empty activity & 19 minimum API level.
 Get rid of action bar from (values -> theme).
parent="Theme.MaterialComponents.DayNight.NoActionBar"
Generating App Icons and Adding Graphics to a Project:
 Download Assets.
 Now change the icon of image by generating image assets.
 Generate icons for application by generating asset & override previous icons.

Official Guide to Android Launcher Icons


o Multiple types of icons android studio normally generate b/c they will fit according to device
configs on which they will run.
o We can generate those all-different size icons just by generating the image assets.
 Now add the drawables for project from assets which we download.

Designing a Screen with Nested Layouts:


 Download this layout file & paste its code in activity main xml file.
 Select the preview device for designing layout (Like your physical phone) b/c currently we want to
only work with this layout.
 We will add a button in our layout so we can roll our dice after clicking on it.
 Adding all text content of app to string values file is good practice.
<string name="roll_btn">Roll</string>
 Provide descriptive id to every element on screen is very good practice b/c we have to use all
components by that id.
android:id="@+id/id_btn_roll"
 Background Tint is the property for changing the background of the button.
app:backgroundTint="#827717"
 We can add layout inside another layout to make nested hierarchy of layout & we can just drag &
drop any widget from one layout to other.
 LinearLayout is type of layout in which we can arrange our widgets linearly in horizontal (Left to
Right) or vertical (Top to Bottom) direction.
 Orientation is the property of linear layout for setting the direction.
android:orientation="vertical"
 Match parent property set the widget size as its parent.
 Wrap content property set the widget size as its content.
 We can also provide hardcoded value to our widgets & its measurement unit is DP (Density
Independent pixel).
android:layout_marginBottom="50dp"
 All margin properties set the space from the margins of that widget.

Abdul Qayoom 26
Android O & Java Notes
android:layout_marginBottom="50dp"
 All padding properties will set the space inside the widget to its corners to childs corner or
content.
 Childs are those widgets which is inside any container or parent.
 Parent container which containers Childs inside it.
 All aspects of Gravity of parent container will set its all childs to its parent.
 Gravity on widgets will set its content.

Using Variables and Linking Layout Elements to Java Code:


 Java files contains the logic to control the layout or design.
 We can connect the widgets with java code by creating its variable & then provide its value by
finding it by id.
 FindViewById is the method which help us to get our widgets by their ids.
 Variable is just a container or box, which can be empty or it can contain data.
 Variable is a container & it has (datatype, name & value).
o Data type, size & description:

 Variable have definition or defined, which means button variable is created or defined but it is still
not assigned with any of value (Variable always have a datatype) which defines the data which
will be stored by that variable.
Button mRollBtn;
 Variable have initialization or initialized, which means variable is assigned by any value of its type:
mRollBtn = findViewById(R.id.id_btn_roll);
 Single Equal sign “=” is use to assign values to variable.

Use the Logcat and a Listener to Check if a Button is Pressed:


 By setting listeners on widgets, we can generate any event when they clicked.
rollBtn.setOnClickListener(V ->{
//logcat message
Log.i("Click", "Button is clicked...");
});
 Log cate is a tool which help us to debug our code & it monitor our device.
 Logcat is a command-line tool that dumps a log of system messages, including stack traces when
the device throws an error and messages that.
 Logcat messages have severity levels (verbose , debug, info, warn, error, asset).

Abdul Qayoom 27
Android O & Java Notes
Create Random Numbers in Java:
 Random is a class by which we can created random number by creating its instance.
 An instance is simply defined as a case or occurrence of anything, which is created by new key word.
 New keyword is used to create object or instance of any class.
 Every class comes with a constructor, A special type of methods, which calls with every instance
initialization.
Random randomNumberGenerator = new Random();
Java Arrays and How to Use Them:
 Arrays is a collection of objects, which stores same types of objects.
 We can access object of array by index number start from 0.
int[] diceArray = {
R.drawable.dice1,
R.drawable.dice2,
R.drawable.dice3,
R.drawable.dice4,
R.drawable.dice5,
R.drawable.dice6
};
 Final is a key word, if we declare any variable as final then we cannot change its value but we can just
refer to it.
 setImageResource() is a method in java by which we can change the source of image view at runtime
or set a new image on image view.
leftDiceImg.setImageResource(diceArray[randomNumber]);
Why did the programmer quit his job?
Debugging Practice Compilation and Build Errors:
 Gradle is a tool & part of android studio, which is responsible for building the project.
 Gradle has to follow series of steps to build a project & run our code as an app.
 Build errors or build failed message occurs during project building & checking process of code & files
in project.
 Build errors occurs b/c of problem in code or any missing file.
 Build & compile time errors prevent code to run.
 Build & compile errors are easy to identify then errors which occurs at runtime, b/c build & compile
errors always highlighted by android studio or any IDE but run time errors not.

Debugging Practice, the App Has Stopped. What to do after a Crash:


 App crash is situation which occurs normally during android development b/c of runtime errors.
 We can find crash reports or crash reason in android logcat.
 We can apply filter for logcat to error severity to find errors easily.
 We have some good site like stack over flow , where we can find the solution for previously
occurred problems & solutions.

Debugging Practice Github Repo


Show Off Your Work:
The Code for the Complete Dice Project

Abdul Qayoom 28
Android O & Java Notes

Abdul Qayoom 29
Android O & Java Notes

Coding Challenge #2 - Data Types, Variables and Arrays:


What You Will Create:
 Still now we have learned to manage complex & nested layout, working with arrays, variables,
generate random numbers & also learn to debug our app.
 Now we have to make a magic 8 ball app.
 It will have 3 view (TextView, ImageView, Button)
 When we click on button then it will return an images from available 5 images.

Debugging Cannot Resolve symbol 'AppCompatActivity'


Step 1 Import the Skeleton Project from Github:
 Download these files, then copy & paste in res folder of project.

Invitation link for the Magic 8 Ball assignment:


Step 2 Change the App's Theme:
 Set theme form theme file to no action bar.
parent="Theme.MaterialComponents.DayNight.NoActionBar"
Step 3 Download the Graphics for the App:
 Graphics are already download & updated

Step 4 Generate New App Icons:


 This step is already done during skeleton setting.

Step 5 Add the Graphics to the Project:


 Graphics are added during skeleton setting.

Step 6 Design the App in the Layout XML:


 Layout is copied already & set.
 Set descriptive ids for view of layout to these ids.
android:id="@+id/id_img_eightBall"

Abdul Qayoom 30
Android O & Java Notes
android:id="@+id/id_btn_ask"
Step 7 Link the Layout to Java Code:
 Create variables & find image & button view in main activity java file.
final ImageView eightBall = findViewById(R.id.id_img_eightBall);
final Button askButton = findViewById(R.id.id_btn_ask);
Step 8 Check for Bugs and Predict the Future
 Create array of images which we want to show during prediction.
final int[] predictionArray = {
R.drawable.ball1,
R.drawable.ball2,
R.drawable.ball3,
R.drawable.ball4,
R.drawable.ball5
};
 Create a listener on ask button.
askButton.setOnClickListener(V ->{

});
 Generate numbers from 0 to 4 b/c we have to show five elements & array size is five.
int randomNum = new Random().nextInt(4);
 Set images according to generated number from prediction array when is ask button is clicked.
eightBall.setImageResource(predictionArray[randomNum]);
Step 9 Submit Your Coursework [Optional]:
 Done.

Magic 8 Ball Challenge Solution


 Done it by own.

Abdul Qayoom 31
Android O & Java Notes

Java Programming for Beginners:


Introduction to the Programming Modules:
 During this lesson we will learn about purely java & its concepts.

Setting up a Pure Java Project in Android Studio:


 Start a new project, Name it & select add not activity.
 After building your project change to project view.
 Create a new library from (file -> new -> new module -> pick java library -> name it, name your main
class -> finish), this will create a folder in our project.
 Write this code in main class.

public class Main {


public static void main(String[] args) {
System.out.println("Hello to java from android");
}
}
 Now config the android to run java class in terminal or console goto (run -> edit configurations -> hit
“+” icon -> select application -> name it -> select your main class -> select java module which we have
created -> hit ok -> run -> run your program).
 After that all we will get our output in run window.

Code Blocks, the main() Method, and Code Compilation Explained:


 Java code is always organized in block & each block has opening curly brace “{” & closing curly
brace “}”.
 If we provide good indentation in any IDE then we can visualize code blocks easily.
 All java code comes in a class, which is outer most block of any code.
 Class keyword is used to create classes in java.
 Methods is set of instruction with a specified unique name in class.
 Main methods is the standard entry or starting point of java project.
 Compiler compile the code into machine understandable format & also check for errors.
public class Main {
public static void main(String[] args) {
System.out.println("Hello to java from android");
}
}

Comments, Variables and Types:


 Comments are simple explanations of code & comments always ignored by compiler.
//This code will print on console
System.out.println("Hello to java from android");
 Println statement prints next print statement on next line.
System.out.println(" Hello with println");
 Print statement prints next print statement of same line.
System.out.print("hello with print");
 There are multiple types of comments in java.

Abdul Qayoom 32
Android O & Java Notes
// this is single line comment
/**
* this is java doc comment
*/
/*
this is multiline comment or block comment
*/
 Writing easily understandable is a very good skill of a developer & comment help us in that area.
 Variables are just as boxes are container which can contain any type of data.
 Variable always have a name & data type during defining it & we assign value to it by equal
“=”sign during initialization.
 Java follows camel case convention for naming to variables.
int mCash; //Definition of mCash variable which has integer type
mCash = 10; // Initialization of mCash variable by assigning to value 10.
 Constants are special type of variables, to which we can assign value only once.
 Constants are those values which will not change in future like birthday, CNIC number, account
number etc.
 Value which do not change in future should be constants by keyword final.
 Final keyword help us to create constants.
final Date TODAY_DATE = new Date();
 Constants name in capital letters is java convention.

Why you'll want to comment your code:


Methods Part 1 - Defining and Calling a Method
 Methods are just collection of commonly used instructions in program so we pack them in
methods & used them when we need.
 We have to define methods with set of instruction which we want to perform.
public static void getMilk(){
System.out.println("Open the door");
System.out.println("close the door");
System.out.println("go to straight for 1km");
System.out.println("turn right");
System.out.println("go for 100 meter");
System.out.println("get milk");
System.out.println("turn around");
System.out.println("go for 100 meter");
System.out.println("turn let");
System.out.println("go to straight for 1km");
System.out.println("Open the door");
System.out.println("close the door");
}
 Without calling this methods will not perform anything so we have to call this method to perform
tasks.
getMilk();
 Method also return a value when we do not make them void.
 Void specify that this methods will not return anything but this just run instruction inside its
blocks.

Abdul Qayoom 33
Android O & Java Notes
 Methods have body with braces {}.
 Public specifying that this method is public access & it can be called in whole project or globally.
 Static keyword specifying that this method will be called without its class object.

Methods Part 2 - Adding Parameters:


 Methods also take inputs as parameters.
 Parameters are simple input according to those method will perform tasks.
 We provide inputs for methods in “()”
private static void getMilk(int noOfPackets) {
goForMilk();
System.out.println("get "+noOfPackets +" cartons of milks");
returnBack();
}
 We can also call other methods inside method.
 We have to call parametrized methods with their parameters.
getMilk(2);
 We can perform calculations inside methods.
 Provide parameters or inputs to methods make them customizable of versatile & we can always
called it with different input & methods will provide us result as the input .
 We can call our same methods as many time as we want without writing same instruction again.
getMilk(2);
getMilk(20);
getMilk(3);
 We get some common errors when we call ay methods without its definition or parametrized
methods without parameters.

Methods Part 3 - Multiple Parameters and Returning a Value:


 Methods also provide us output or return value.
 We can replace void keyword with any datatype to provide value which method has to return &
return value before the end of method body by return keyword.
 Method will not go further after return statement.
public static int milkPrice (int noOfPackets){
return noOfPackets * 10;
}
 We call this method to get price.
int price = milkPrice(noOfPackets);
 We separate our parameters by “,” if methods need more than one inputs or provide more than
one inputs.
 Every methods have return value other than void than that methods should have return
statement.

Control Flow Conditional Statements (IFELSE):


 If Else statement or control floe statement help us to take decision based on circumstance or
condition.
int loveScore = new Random().nextInt(101);
String statement = "No love possible you will be forever alone...!!!";
if (loveScore > 80){
System.out.println("Love score is "+loveScore+" You love very much each other & you
Abdul Qayoom 34
Android O & Java Notes
will be always with each other");
}else if (loveScore > 60){
System.out.println("Love score is "+loveScore+"");
}else {
System.out.println(statement);
}
return loveScore;
 When we use methods to get value from it then it return value after doing all its tasks first.
System.out.println("your love score is "+calculateLove("Abdul Qayoom", "Nihan"));
 Now here method will execute its inner statements first & then return value to print method so it
will return result as.

Make a BMI Calculator [Challenge]:


 Create A ne module & set its configs for run.
 Create a simple welcome screen by print statements.
public static void welcome (){
System.out.println("Hello to the BMI Calculator");
System.out.println("<<<<<<<<<<<<<---------------->>>>>>>>>>>>>>>");
}
 Get height in feet & convert them into centi meters.
public static double getHeight(){
System.out.println();
System.out.print("Enter you height in feet : ");
double height = new Scanner(System.in).nextDouble();
return height * 30.48;
}
 We can use Scanner utility class to get input at console.
 Get weight.
public static double getWeight (){
System.out.print("Enter you wight in kg : ");
double weight = new Scanner(System.in).nextDouble();
return weight;
}
 Calculate BMI & return messages according to satisfying condition.
public static double calculateBMI(double yourHeight, double yourWeight){
double bmi = (yourWeight / yourHeight / yourHeight ) * 10000;
if (bmi >= 30.0){
System.out.println("You are obese");
}else if(bmi >= 25.0){
System.out.println("You are over weight");
}else if(bmi >= 18.5){
System.out.println("You are healthy");
}else {
System.out.println("You are under weight");
}

Abdul Qayoom 35
Android O & Java Notes
return bmi;
}
 Call welcome & BMI Calculator method.
welcome();
System.out.println("Your BMI score is "+calculateBMI(getHeight(),getWeight()));
 Congrats we have created successfully now calculate your BMI.

Abdul Qayoom 36
Android O & Java Notes

Build a Music App [Tutorial]:


What Will We Make:
 We are going to make a music app with 7 keys & every key will have different sound.
 Here we will learn how to read official documentation & get help from it.
 Finding out how to use new components which we have never used before.
 We will learn how we can play sound on android device.

Setting Up the Project & Using Colours as Resources:


Download the Skeleton Project:
 Download the skeleton of this project then clone project from git hub or create new own project
and replace skeleton with copy & paste.
 Test your app & make sure it matches with my layout & project.
 Setting up all the colors & color schemes for app in colors file is good practice b/c we can change it
easily any time.
 RAW directory is good place to place all things which can’t fit in other directories like audio files,
video files, csv files etc.

How to Use Android Documentation and Other Resources:


 First Step to find about any android components of functionality, which we are using first time or
don’t know is Android official documentation & search for API guides & find about your API on
which you want to work.
 Find key components for doing that task.
 Other best resource for finding information is site stack over flow, search here about your
problem& look for high number of votes & high number of accepted answers.
 Github is the best place to find sample projects.

Google Samples on Github:


Android API Guide:
Android API Reference:
Stack Overflow - Q&A Site for Programming Problems:
Calling the Constructor to Create a SoundPool:
 Member variables are those which comes inside class & variables in methods are local variables.
 Class variables can be used in methods but method or local variables can’t be used as class.
Variables.
 Class variables should have private visibility (Only visible inside that class).
 Data type of variables can be type of class object when we have to put class inside those.
private SoundPool mSoundPool;
 If we use a class data type for nay variable then we have to assign it variable by it public
constructor so we can find it in documentation.
mSoundPool = new SoundPool(7, AudioManager.STREAM_MUSIC, 1);
 This sound pool class constructor have three integer inputs or parameters (maxSteram,
streamType, streamQuality).

Member Variables and the Importance of Scope:


 Member variables are class variables which has scope is whole class.

Abdul Qayoom 37
Android O & Java Notes
 Scope refers to the availability of variable for use.
 Local variable are methods variables, defined inside methods & scope for local variables is
restricted only to that method.
 Class or member variables can be used in methods but local or method variables cannot used in
class outside of that method.
 Limit the scope of variables is better practice b/c variable value is during using & find where it
occurs if we have member variable used in many of lines.
 We can reduce the complexity of program by reducing the scope of variables.
 We can also reduce the memory usage by limiting the scope of variables b/c when any variable is
not in use then it’s used resources are reclaimed.
 We cannot create two variables with same scope, they should be unique.

Using the onClick Property instead of a Listener:


 We can also directly set onClick on view by setting onClick property of view.
android:onClick="aIsClicked"
 We have to specify the method name which will called when this view will clicked.
public void fIsClicked(View view) {

}
How to Play a Sound in Your App using the SoundPool:
 We can play the sound by the play method of SoundPool class.
 We need load methods of SoundPool to get id of sound. It has different shapes but we are using
load method which take 3 parameters:
o Context context: context of application or state of application
o Int resId : this is the id of resource like (R.raw.abc).
o Int priority: priority of sound
mASoundId = mSoundPool.load(this, R.raw.note6_a,1);
 Play method od SoundPool class have 5 parameters & return non zero id if successful.
o Int soundId: this is id by which our sound will be play & this id will be return by load
method.
o Float leftVolume : range from 0.0 to 1.0
o Float rightVolume: range from 0.0 to 1.0
o Int Priority: stream priority (0 is the lowest)
o Int loop : loop mode (0 = no loop, -1 = loop forever)
o Float rate: play back rate (1.0 = normal & range from 0.5 to 2.0)

The Code for the Complete Xylophone Project:

Abdul Qayoom 38
Android O & Java Notes

Build a Quiz App and Learn about the MVC Design Pattern [Tutorial]:
What Will We Make:
 Now we will make an app little bit complex than others named as quiz app.
 During this lesson we will learn about android activity life cycle.
 We will also learn how to design complex app with design pattern MVM (Model View Controller).

Import & Familiarize Yourself with the Skeleton Project:


 Download this project skeleton & setup your new project according to it.
 We have use escape sequence characters in strings to read those escape sequence characters as
string like (‘ “ “ \) etc.
 These escape sequence characters have special meaning in code so we have to write them in
string by “\”.

Download the Skeleton Project:


Understand Casting & Link the Layout to the Java Code:
 For connecting the layout with java code, we have to create variables for those widgets & find
them by ids.
 findViewById is belongs to Activity class, which gets an id & return a view.
 Casting is a process or technique, by which we convert one datatype into other data type.
mFalseBtn = (Button) findViewById(R.id.false_button);
 Here findViewById is returning a view & we are converting it to Button.
 For casting we should make sure that both types belongs to one family or hierarchy like int &
double.
 We can the official google API guides to identify the hierarchy of views or data types.

Set an OnClickListener & Implement a Toast Message:


 Listeners are components which report back, if a certain event is happen like button click.
 We can set onclick listener on any view.
 We have to specify listener for applying on any of view.
View.OnClickListener clickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {

}
};
 After creating listener, we set that listener on any of view.
mFalseBtn.setOnClickListener(clickListener);
 We can also create above onClick listener by providing whole listener in parameter on
OnClickListener method & this listener will be known as anonymous listener.
mTrueBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

}
});
 Toast is the way of proving user feedback. We can create Like that:

Abdul Qayoom 39
Android O & Java Notes
Toast.makeText(MainActivity.this, "Button is clicked", Toast.LENGTH_SHORT).show();
 We create a toast by make text methods which take inputs (Context, text, time) & then we call
show method on that to show that toast.
 Anonymous components are very use ful b/c they are useable on the fly without storing them in
variables.

Create the Model Class & Generate Code with Android Studio:
 Model class or template is a class which provide template for code inside controller.
 Model class is a class which contain the way to set data & blue print for creating a question.
 We set member variables inside model & a constructor to initialize all variables.
 Constructor is a special type of methods, whose name is same as the class name & it calls when a
instance is created for that class.
public TrueFalse(int questionID, boolean answer) {
mQuestionID = questionID;
mAnswer = answer;
}
 We have to call constructor with its inputs when we have to create object or create a question.
TrueFasle Q1 = new TrueFalse(R.string.question_1, true);
 Android creates an special class known as R, which updated during ids creation & resources.
 Getter & setters are methods which we use to get & set any value of class variables.
public int getQuestionID() {
return mQuestionID;
}

public void setQuestionID(int questionID) {


mQuestionID = questionID;
}
Boolean - A Data Type that Holds One of Two Values:
The Model View Controller (MVC) Design Pattern and Why We Use It:
 Design pattern is a proven solution to a common problem.
 In Software engineering design pattern exists as a template to solve a common problems.
 MVC is a code design pattern for structuring the code & stay organized.
 MVC help us to remove overall complexity & stay organized by structure the code into three
separate parts (Model, View & Controller).
 MVC was introduced by Trygve Reemskaug in 1970s.
 Model manages the data, creates new entries in the database, deleting things from database,
reading from the database.
 View is UI which we see on screen.
 Controller livers b/w model & view for provide the communication.

Abdul Qayoom 40
Android O & Java Notes

 Model do not have data but it manages the data (Save data to database & retrieve data from data
base).

 If we see our android project, we have created a Model, UI lives in layout & MainActivity java file
is our controller.
 MVC provides:
o Provide structure
o Recognizable by third parties b/c this is very common one.
o Code reuse.
o Multitasking, we can work on one part of the project with affecting other.

Retrieve Quiz Questions from an Array and Display them on Screen:


 For this simple app we are using an array to store our data but this is not good practice to store
data in array or controller.

Abdul Qayoom 41
Android O & Java Notes
private TrueFalse[] mQuestionBank = new TrueFalse[] {
new TrueFalse(R.string.question_1, true;)}
 After saving data we have to show on our widgets.
o Get from data storage or array by get methods of data.
int question = mQuestionBank[mIndex].getQuestionID();
Update Questions on Screen and Interpret Errors in the Logcat:
 Now we have to update our question when we click on button so we can update it by increasing
the value.
mIndex++;
 Get question on that index & set on view.
mQuestion = mQuestionBank[mIndex].getQuestionID();
mQuestionTv.setText(mQuestion);
 Call that method in listener.
updateQuestion();
 Get rid of array index out of bound exception of reminder concept, we can set reminder for array
length (this will set index value to 0 if index value reach at last index).
mIndex = (mIndex + 1) % mQuestionBank.length;
Check the User's Answer and Give Feedback:
 Now we can find the question correct answer of current index by just getting the answer of
current index of array.
boolean correctAnswer = mQuestionBank[mIndex].isAnswer();
 Check answer by comparing the answer with selected answer.
if (correctAnswer == answerSelected)
 Call that methods:
checkAnswer(true);
Working with the Progress Bar and Tracking Score:
 Create member variable for bar & find it by id.
 Create a member variable which will increase with every correct answer.
 Create a constant for Progress bar increment.
private final int PROGRESS_BAR_INC = (int) Math.ceil(100.0 / mQuestionBank.length);
 Math.ceil is a method which get floating point number & return floating point number & return
round of.
 Increase the progress bar by progress bar increment constant when user clicks.
mProgressBar.incrementProgressBy(PROGRESS_BAR_INC);
 Update the score variable, when user clicks on correct answer (Update the score variable in check
answer methods & update the text view in update question method).

Fixing the Screen Orientation and Displaying an AlertDialog:


 When device rotate then configuration of devices changes that why our app recreated & our
questions comes to the index one.
 We can fix this issue by disabling the rotation of app (for those apps which do not need landscape
mode from manifest file):
<activity android:name=".MainActivity"
android:screenOrientation="portrait"
>

Abdul Qayoom 42
Android O & Java Notes
 We can also fix this issue by storing the state of application & restore that when app recreate
himself.
 Alert dialogue is graphical element which comes or appears at some event like starting something
or ending something like (retry, end).
 Alert dialogue can have buttons like start, retry, exit etc.
 For creating the alert dialogue, we have to first configure it & then show it with any event of
condition fulfils.
 This key word also get the current object or current application & we can use it to provide
context.
if (mIndex == 0){
//Todo show alert dialogue
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Quiz Completed...");
alert.setCancelable(false);
alert.setMessage("You scored "+mScore+" points!");
alert.setPositiveButton("Exit", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alert.show();
}
An Overview of How an Android App Works:
 Here we will discuss about android application working mechanism or app components work with
each other.
 Any software or system is made up of smaller components which talk to each other to perform
any specific task.
 When we click a button it sends a message to activity that I have receive a click & activity will
decide what it has to do when that event occurs.
 When we press app icon then OS send a message to application, you are launched & then app call
the onCreate method.
 Android application is event driven & it waits for events to be happen.

The Activity Lifecycle:


 OS in mobile phones cleverly allocate limited resource b/c it have less resources than computer or
laptop, so these operating system designed very differently than pc OS.
 Mobile OS system shutdown the unused apps or app running in background & resources
reclaimed.
 App life cycle start from (launching to shut down)
 If we launch an app & perform our task & leave app in background & start using other application,
if that application needs lot of resources, then background app will be killed by OD & resources
reclaimed.

Abdul Qayoom 43
Android O & Java Notes

 Our application normally have four stages non-Existing (App does not exists),Stopped (Not visible
to user but live-in phones memory), Paused (Activity is visible of partially visible) & Running
(Activity is in foreground & user is interacting with it).
 Only one activity in entire android system can run at one time.
 OS called (Call back) methods automatically when state changes:
o onCreate method (From non-existing -> stopped state).
o onStart method (Stopped -> paused state).
o onResume method (Paused -> Running state)
o onPause method (Running -> paused state)
o onStope method (Paused -> Stopped)
o onDestroy method (Stopped -> Shut down or non- existing)
 When screen rotates than android OS re-creates app :
o onSaveInstanceState -> onStop -> onDestroy
o onCreate -> onStart -> onResume

Abdul Qayoom 44
Android O & Java Notes
Saving State using the Bundle and Null Pointer Exceptions:
 We can also save the state of application in onSaveInstanceState with disabling the landscape
orientation from manifest.
 Override the onSaveInstanceState in activity.
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);

}
 We have to save our data in key value pairs (key can be any word or constant & value will be that
current value of that variable).
outState.putInt("IndexKey", mIndex);
outState.putInt("ScoreKey", mScore);
 Now we have to reset the state of activity, when activity is created, if any previous state is
available.

if (savedInstanceState != null){
mIndex = savedInstanceState.getInt("IndexKey");
mScore = savedInstanceState.getInt("ScoreKey");
}else {
// means app is started from the scratch
mIndex = 0;
mScore = 0;
}


 Bug is an unintended behavior or defect in a program that causes it to crash or malfunction.

The Difference between Zero and Null:


Do You Want This:
The Code for the Complete Quizzler Project:

Abdul Qayoom 45
Android O & Java Notes

Coding Challenge #3 - Control Flow - Build a Story App Like Lifeline:


What You'll Create:
 We have to build destiny app.
 We have to provide a text view for situation & two more views for choosing one answer.
 Here we will learn how to use conditional statement, how to track the app state

Step 1 Setup the Project:


 Download the project code.
 Do what we are doing before for creating the same type of project (Copy resources & paste)
 Create image asset & override same name as laun && cher icon so our new created icons can
replace them (If you are not copying icons of skeleton project).

Step 2 Examine the activity_main.xml and the strings.xml:


 Go & check that our questions looks same & our layout also.
 Now checking after all run app & see the skeleton looks as my skeleton (ignore color difference).

Step 3 Create the Variables for the Views:


 Create variables for only those widgets by which we will interact.
private TextView mStoryTv;
private Button mRedBtn;
private Button mBlueBtn;
private int mRedInBlue;
private int mBlueInRed;
Step 4 Wire up the Views to the Java Code:
 Find views by id in java file.
mStoryTv = findViewById(R.id.storyTextView);
mRedBtn = findViewById(R.id.buttonTop);
mBlueBtn = findViewById(R.id.buttonBottom);
Abdul Qayoom 46
Android O & Java Notes

Step 5 Detect Clicks on the Buttons:


 Set listeners for button.
mRedBtn.setOnClickListener(v ->{

});
mBlueBtn.setOnClickListener(v ->{

});

Step 6 Take the Adventure One Step Further:


 Set conditions for step one & move one step.
 OnRed:

mRedBtn.setOnClickListener(v ->{
if (mRedJourney == 0){
mStoryTv.setText(R.string.T3_Story);
mRedBtn.setText(R.string.T3_Ans1);
mBlueBtn.setText(R.string.T3_Ans2);
mRedJourney++;
mStory++;

}});
 OnBlue:
mBlueBtn.setOnClickListener(v ->{
if (mBlueJourney == 0){
mStoryTv.setText(R.string.T2_Story);
mRedBtn.setText(R.string.T2_Ans1);
mBlueBtn.setText(R.string.T2_Ans2);
mBlueJourney++;
mStory++;

}
});
Step 7 Create a Variable to Track the Player's Path:
 Now we can see that both button are interactive but back & forth & now we have to set a variable
so we can set the progress of buttons & take decisions according to the position.
private int mRedJourney;
private int mBlueJourney;
 Red clicks:
mRedBtn.setOnClickListener(v ->{
if (mRedJourney == 0 && mStory == 0){
mStoryTv.setText(R.string.T3_Story);
mRedBtn.setText(R.string.T3_Ans1);
mBlueBtn.setText(R.string.T3_Ans2);
Abdul Qayoom 47
Android O & Java Notes
mRedJourney++;
mStory++;
}else if (mRedJourney == 1 && mStory == 1){
mStoryTv.setText(R.string.T6_End);
mBlueBtn.setVisibility(View.INVISIBLE);
mRedBtn.setVisibility(View.INVISIBLE);
mRedJourney++;
mStory++;
}else if(mStory == 1 && mBlueJourney == 1 && mRedJourney == 0){
mStoryTv.setText(R.string.T3_Story);
mRedBtn.setText(R.string.T3_Ans1);
mBlueBtn.setText(R.string.T3_Ans2);
mRedJourney++;
mRedInBlue++;
mStory++;
}else if(mStory == 2 && mBlueJourney == 1 && mRedJourney == 1){
mStoryTv.setText(R.string.T6_End);
mBlueBtn.setVisibility(View.INVISIBLE);
mRedBtn.setVisibility(View.INVISIBLE);
mRedJourney++;
mRedInBlue++;
mStory++;
}
});
 Blue Click:
mBlueBtn.setOnClickListener(v ->{
if (mBlueJourney == 0 && mStory == 0){
mStoryTv.setText(R.string.T2_Story);
mRedBtn.setText(R.string.T2_Ans1);
mBlueBtn.setText(R.string.T2_Ans2);
mBlueJourney++;
mStory++;
}else if (mBlueJourney == 1 && mStory == 1) {
mStoryTv.setText(R.string.T4_End);
mBlueBtn.setVisibility(View.INVISIBLE);
mRedBtn.setVisibility(View.INVISIBLE);
mBlueJourney++;
mStory++;
}else if (mRedJourney == 1 && mStory == 2 && mBlueJourney == 1) {
mStoryTv.setText(R.string.T5_End);
mBlueBtn.setVisibility(View.INVISIBLE);
mRedBtn.setVisibility(View.INVISIBLE);
mBlueJourney++;
mBlueInRed++;

mStory++;
}else if (mStory == 1 && mRedJourney == 1 && mBlueJourney == 0){
mStoryTv.setText(R.string.T5_End);
mBlueBtn.setVisibility(View.INVISIBLE);

Abdul Qayoom 48
Android O & Java Notes
mRedBtn.setVisibility(View.INVISIBLE);
mBlueJourney++;
mStory++;
}
});
Step 8 Complete the Game Using Conditionals to Check the State:
 Override onSaveInstanceState:
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
}
 Create constants for keys:
private final String RED_KEY = "RedKey";
private final String BLUE_KEY = "BlueKey";
private final String STORY_KEY = "StoryKey";
private final String RED_IN_BLUE_KEY= "RedInBlueKey";
 Put values in bundle:
outState.putInt(RED_KEY, mRedJourney);
outState.putInt(BLUE_KEY, mBlueJourney);
outState.putInt(STORY_KEY, mStory);
outState.putInt(RED_IN_BLUE_KEY, mRedInBlue);
 Check current state of activity is null of not:
if (savedInstanceState != null){

}
 If not null Then add values for variables or last state:
mStory = savedInstanceState.getInt(STORY_KEY);
mRedJourney = savedInstanceState.getInt(RED_KEY);
mBlueJourney = savedInstanceState.getInt(BLUE_KEY);
mRedInBlue = savedInstanceState.getInt(RED_IN_BLUE_KEY);
 Set the views according to values of variables.
if (mStory == 0 && mRedJourney == 0 && mBlueJourney == 0){
mStoryTv.setText(R.string.T1_Story);
mBlueBtn.setText(R.string.T1_Ans2);
mRedBtn.setText(R.string.T1_Ans1);
}else if (mStory == 1 && mRedJourney == 1 && mBlueJourney == 0){
mStoryTv.setText(R.string.T3_Story);
mRedBtn.setText(R.string.T3_Ans1);
mBlueBtn.setText(R.string.T3_Ans2);
}else if (mStory == 2 && mRedJourney == 2 && mBlueJourney == 0){
mStoryTv.setText(R.string.T6_End);
mBlueBtn.setVisibility(View.INVISIBLE);
mRedBtn.setVisibility(View.INVISIBLE);
}else if (mStory == 2 && mRedJourney == 1 && mBlueJourney == 1 && mBlueInRed ==
1){
mStoryTv.setText(R.string.T5_End);
mBlueBtn.setVisibility(View.INVISIBLE);
mRedBtn.setVisibility(View.INVISIBLE);

Abdul Qayoom 49
Android O & Java Notes
}else if (mStory == 1 && mRedJourney == 0 && mBlueJourney == 1){
mStoryTv.setText(R.string.T2_Story);
mRedBtn.setText(R.string.T2_Ans1);
mBlueBtn.setText(R.string.T2_Ans2);
}else if (mStory == 2 && mRedJourney == 0 && mBlueJourney == 2){
mStoryTv.setText(R.string.T4_End);
mBlueBtn.setVisibility(View.INVISIBLE);
mRedBtn.setVisibility(View.INVISIBLE);
}else if (mStory == 2 && mRedJourney == 1 && mBlueJourney == 1 && mRedInBlue ==
1){
mStoryTv.setText(R.string.T3_Story);
mRedBtn.setText(R.string.T3_Ans1);
mBlueBtn.setText(R.string.T3_Ans2);
}else if (mStory == 3 && mRedJourney == 2 && mBlueJourney == 1){
mStoryTv.setText(R.string.T6_End);
mBlueBtn.setVisibility(View.INVISIBLE);
mRedBtn.setVisibility(View.INVISIBLE);
}else if (mStory == 3 && mRedJourney == 1 && mBlueJourney == 2){
mStoryTv.setText(R.string.T5_End);
mBlueBtn.setVisibility(View.INVISIBLE);
mRedBtn.setVisibility(View.INVISIBLE);
}
Step 9 Submit Your Project [Optional]:
Destini Challenge Solution:

Abdul Qayoom 50
Android O & Java Notes

Working with the Constraint Layout & Creating Multiple Layouts:


Converting to a Constraint Layout & Designing for Multiple Screens:
 Constraint Layout help us to design layouts which looks great in and size of screen & in landscape
as well as portrait mode.
 We can also create different layouts for different phones.
 We should always use wrap-content & match parent value to provide good look on mush of
devices.
 Because if we try to design layouts by hardcoded values then we have to create approximately
(5400 possible screens) b/c we have (90 screen sizes * 30 Languages * 2 orientation).
 By using Constraint layout, we will get rid of using nested view hierarchy & we can all set in one
constraint layout.
 Constraint layout provide us possibility for Flat View Hierarchy.

Setting Constraints and Using Built-In Styles:


 Content Description attributed provide description of content to partially sight persons.
 Provide description of content, images , button etc is good practice.
android:contentDescription="@string/logo_description"
 We can also make use of build-in styles for widgets.
style="@style/Widget.AppCompat.Button.Colored"
 Go to site for take your color scheme & design according to it.

Linking Views to Each Other:


 We can connect the widgets with each other & parent in constraint layout to create our layout
design.

Using Guidelines to Position Layout Elements:


 Create a guide line & set views according to that.
 Guide lines work as boundaries & we can connect with those.
androidx.constraintlayout.widget.Guideline
 Guide lines can be set by DP as well as percentage:
app:layout_constraintGuide_end="51dp"
app:layout_constraintGuide_percent="0.90"
 We should set guidelines from all sides & set according to those.

Automatically Inferring Constraints with Android Studio:


 Infer constraints is tool or engine, which help us to provide constrains according their position,
where we leave them by dragging.
 Infer engine automates our work flow & we do not need to provide constraints manually.
 Infer engine provide constraints to widget according to probability of what we are trying to do.
 Infer constraints do not move our widget but provide constraint according to their current
position.

Resource Qualifiers and Layouts for Landscape Mode:


 We can create two layout for one activity (portrait & landscape) by just clicking on landscape
variation option in orientation option.
 Resource qualifiers (Shown in grey with resource) which help android OS to choose resource as
screen size or device needs (which suits best).
Abdul Qayoom 51
Android O & Java Notes

 Resources qualifiers also specified by suffix in explorer or directories.


 We can specify any type of resources qualifier from available menu in (res -> Android Resource
file).

Internationalization, Resource Qualifiers and the Translations Editor:


 We specify the locale for our resources like text by string value Translation editor by specifying
any of locale.
 Translation editor is a tool which help us to set the locales for our app & provide values in our
string file.
 We can also add values for other locals in our file with our translation editor but Translations
editor comes with different locals and help to create that locale easily.
 We have to translate manually Assign values in our specified locale & studio will create another
file with our specified locale.
 App will also detect the locale configuration & provide that locale or language to device.
 We can use resource qualifiers for internationalization (by setting the locale on the string xml),
create different graphic resources (icons, images) for different screen sizes.
 Studio also provide us editor life translation editor for editing our layout which can be open
directly from the layout file.

Creating a Landscape Layout and Adding Content Descriptions for Accessibility:


 We can specify layout for landscape mode by resources qualifiers (res -> android res file) & select
orientation from available list of resources qualifiers.
 We can also create landscape layout from Orientation form preview tool (Orientation preview
tool -> Create landscape variation).
 We can create tablet variation of our layout by selecting the create table variation.
 When we design our layout, we should check with al available previews & it should be good on all.
 Content description is the description of available widget or graphics (Image, video, icon) or any
graphics on screen.
 Content description will help screen reader to identify the object by this description.
 Content description is very use full for peoples who do not identify any graphics on screen & use
screen reader.
 We should provide content description in string xml file.

Abdul Qayoom 52
Android O & Java Notes
Complete Layout Source Code:

Abdul Qayoom 53
Android O & Java Notes

Java Programming for Intermediates:


Set up a Standard Java Project in Android Studio:
 We will create a new project with empty activity b/c we will create a java module inside it to use
or write java code & set configuration to run java project.

Virtual Machines & Program Entry Points main() vs the Android Intent Filter:
 Main methods is entry point for java project & Intent filters are entry point for android
application.
 Java project or program runs on JVM & JVM look for method which contains main method for
launching the program.
 Android have own Virtual machine (ART = Android Runtime) which looks for intent filter &
identify launcher filter & start application from that activity which contain that filter.
 In both (Android application or Java program) can only have one entry point.
 ART is responsible for launching the application & managing android application life cycle.
 ART look for entry point in android manifest file & start from activity which contains launcher
intent filter.
 Java main method:
public static void main(String[] args)
 Launcher intent filter:
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>
 Virtual machine is an emulated Computer, which is only exists as a software.
 JVM is an intermediate software which help to execute java programs on any type of the system.
 JVM can run on any device & it work as translator of java code into machine understandable code.
 Currently java is running on more than 3 billion devices.

Classes and Objects Demystified:


 Java class is an blue print (attributes of object & methods of object).
 Java class contain methods & attributes for creating object.
 Java object is an instance of class (Car or any real-world object).
 Java Class can have multiple objects or instances.
 Class:
public class Car {
private String mModel;
private int mEngineHp;
private String mColor;
private int mSpeed;
private boolean mAccelerator;
private boolean mBrake;
private int mGear;
private boolean mAutomatic;

Abdul Qayoom 54
Android O & Java Notes
private int mSeats;

/**
* Todo This is constructor
* & it will call every time when we create any
* object of that class
* @param model of car
* @param engineHp of engine
* @param color of car
* @param speed of car
* @param accelerator in car or not
* @param brake in car or not
* @param gear how many in car
* @param automatic yes or not
* @param seats how many in car
*/
public Car(String model, int engineHp, String color
, int speed, boolean accelerator, boolean brake
, int gear, boolean automatic, int seats) {
mModel = model;
mEngineHp = engineHp;
mColor = color;
mSpeed = speed;
mAccelerator = accelerator;
mBrake = brake;
mGear = gear;
mAutomatic = automatic;
mSeats = seats;
}

/**Todo this method will return normal speed


* @return normal speed of car
*/
public int drive(){
return mSpeed/2;
}
}
 Object:

 Java keyword new is used to create object & objects initialized by class constructor.
 Data type of the object is the class name or class of which we are creating object.

Abdul Qayoom 55
Android O & Java Notes
Fields, the Dot Notation, and an Object's State:
 Field are properties of object defined in class:
private String mModel;
 Do-Notation or dot operator “.” Also known as connecting operator, it connects things like:
myCar.getModel()
Using GettersSetters & Access Modifiers Public v.s. Private:
 Access modifiers are keywords (Public , private, protected) which used to assign the visibility of
method, classes or fields.
 Protected (fields, classes or methods) will be available in class &child classes.
 Public (fields, classes or methods) will be available globally.
public String getModel() {
return mModel;
}
 Private (fields, classes or methods) will be available only in class (in which defined).
private String mModel;
 Private attributes of class can only be accessed with in class so we create setters & getter to play
with private attributes.
 Java class can have methods of setting the value of object & getting the value of object known as
setters & getters.
/**
* @return model of car
*/
public String getModel() {
return mModel;
}

/**
* @param model set the model of car
*/
public void setModel(String model) {
mModel = model;
}

/**
* @return hp of engine
*/
public int getEngineHp() {
return mEngineHp;
}

/**
* @param engineHp set the hp of engine
*/
public void setEngineHp(int engineHp) {
mEngineHp = engineHp;
}

Abdul Qayoom 56
Android O & Java Notes
/**
* @return get the color of engine
*/
public String getColor() {
return mColor;
}

/**
* @param color set the color of car
*/
public void setColor(String color) {
mColor = color;
}

/**
* @return speed of car
*/
public int getSpeed() {
return mSpeed;
}

/**
* @param speed set the speed of the car
*/
public void setSpeed(int speed) {
mSpeed = speed;
}

/**
* @return accelerator is available of not
*/
public boolean isAccelerator() {
return mAccelerator;
}

/**
* @param accelerator set the accelerator
*/
public void setAccelerator(boolean accelerator) {
mAccelerator = accelerator;
}

/**
* @return break is available of not
*/
public boolean isBrake() {
return mBrake;
}

Abdul Qayoom 57
Android O & Java Notes
/**
* @param brake set the break of car
*/
public void setBrake(boolean brake) {
mBrake = brake;
}

/**
* @return how many gears are available is the car
*/
public int getGear() {
return mGear;
}

/**
* @param gear set the gears of the car
*/
public void setGear(int gear) {
mGear = gear;
}

/**
* @return car ir automatic of not
*/
public boolean isAutomatic() {
return mAutomatic;
}

/**
* @param automatic set the automation of car
*/
public void setAutomatic(boolean automatic) {
mAutomatic = automatic;
}

/**
* @return how many seats are available in the class
*/
public int getSeats() {
return mSeats;
}

/**
* @param seats set the seats of car
*/
public void setSeats(int seats) {
mSeats = seats;
}

Abdul Qayoom 58
Android O & Java Notes
 Rules of access or visibility:
o Limit access & visibility.
o Expose only what you really need.
o Access private fields through getters & setters.

No-Argument Constructors vs Parameterized Constructors:


 Constructor is special type of methods, which same name as class name & it used to define initial
state or create object.
 A constructor can have parameters & it can be empty.
 If we do not define any other constructor then an empty constructor will be called when we
create any of object of class.
 Parametrized Constructor can also have inputs or parameter which it will get for creating any
object of class.
 If we defines a constructor with inputs of parameters then we have to call that constructor for
creating objects.
 A class can have multiple constructor & they will be identified by their (type of arguments &
number of arguments) which known as constructor overloading.
 Constructor also do not have any return type.
 Constructor:
public Car(String model, int engineHp, String color
, int speed, boolean accelerator, boolean brake
, int gear, boolean automatic, int seats) {
mModel = model;
mEngineHp = engineHp;
mColor = color;
mSpeed = speed;
mAccelerator = accelerator;
mBrake = brake;
mGear = gear;
mAutomatic = automatic;
mSeats = seats;
}
 Get the values provided in constructor:
System.out.println(
"My Car model is "+myCar.getModel()+
" , has "+myCar.getEngineHp()+" horse power engine "+
", Color is "+myCar.getColor()+
" , it comes with high speed of "+myCar.getSpeed()+
" , It has accelerator ("+myCar.isAccelerator()+")"+
" , it has break ("+myCar.isBrake()+")"+
" ,it has "+myCar.getGear()+" gears"+
" , it is automatic ("+myCar.isAutomatic()+")"+
" & it has "+myCar.getSeats()+" number of seats."
);
 Its output:

Abdul Qayoom 59
Android O & Java Notes

Object Behavior & Using Methods:


 Object state is defined by its field or properties.
 Behaviors (methods) defines what objects can do.
public int drive(){
System.out.println("Car is moving...");
return mSpeed/2;
}
 We have to call this method on object to do these tasks specified in method body.
myCar.drive();
 Class or Interface expected error occurs on methods when any methods if not in class or defined
outside of the class.
 Two methods cannot have same signature.
 We can define methods with same name but we have to define different number of parameters or
different parameters known as method overloading.
 In some programming languages, function overloading or method overloading is the ability to
create multiple functions of the same name with different implementations.
 Java will identify methods call based on provided parameters not name.

The static Keyword Class Variables & Class Methods:


 Static variables of constants will be share with all created object of class.
private static String mColor;
 Static variables have only one copy & it will be inside class & object only can use it, so static
variables also known as class variables.
 Static variable can only have one copy & if any change occurs in static variable value than it will be
assign to all objects.
//Todo use of static variables
Car honda = new Car("Blue");
Car toyota = new Car();

//Now these both have same color


System.out.println("Honda color is "+honda.getColor());
System.out.println("Toyota color is "+toyota.getColor());
 Output:

The Toast Class Source Code:


Toast Class Documentation:
Inheritance, the protected Modifier & the @Override Annotation:
 Inheritance is used to reuse the code which is already written.

Abdul Qayoom 60
Android O & Java Notes
 We use inheritance to reuse the properties of parent in child class.
 Inheritance used to get some or all properties of parent into new child.
 Extends keyword is used for extending the properties & behaviors of super class (parent) to sub
class (Child).
public class SelfDrivingCar extends Car
o Here is car is super class & SelfDrivingCar is sub class.
 Sub class can have more properties than its parent b/c it will extend parent properties & also it
will define own properties also.
 When we create constructor is will extend the properties of super class, if we want to provide it in
constructor.
public SelfDrivingCar(String color, String interior) {
super(color, interior);
}
 Create child class object:
SelfDrivingCar myAutoBoot = new SelfDrivingCar("Yellow", "Plastic");
 Sub class can access the public & protected filed & behaviors or super class but not private.

 If we create a method with same signature then call with sub class object then method of sub
class will be called not method of super class.
 But we can call super class method in sub class method & it will run both methods.
public void drive(){
super.drive();
System.out.println("Self driving car is driving");
}
 Override annotation inform child & parent class about changes in overridden methods.
 If we provide override annotation to method then compiler will search that method in super class
& if it does not find than it will inform us about that.
@Override
public void drive(){
super.drive();
System.out.println("Self driving car is driving");
}

Abdul Qayoom 61
Android O & Java Notes
 Annotation prevent us from doing silly mistakes & if we do than they inform us about it.

Bonus Question

Abdul Qayoom 62
Android O & Java Notes

Build a Weather App - Use GPS and APIs to Get Data from the Web
[Tutorial]:
What Will We Make:
 We will create a weather app & use our all which learned before.
 We also learn dependency management using gradle (Use of other library which develop by other
developers).
 We will learn to work with networking & work with APIs (Application Programming interface).
 We will learn to fetch data of site using API (OpenWeatherMap).
 We will learn to use multiple activities & interact with those.

Project Setup & Overview:


 Download Skeleton of project & Config same project as mine.
 You ca customize the design as your choice.

Download the Skeleton Project:


Get your Own free API Key (App ID):
Gradle Project & Module Scripts and Android SDK Compatibility:
 Gradle is a tool which used to configure & build the project.
 Project gradle file contains the top-level information about the project.
 Module gradle file contains the information about module (Mobile, wear, tv etc) for which we are
building apps.
 Minimum SDK is lower bound & Target SDK is upper bound to run our apps.
 Compile SDK version defines in which version our app is going to compile.
 Compile SDK & target SDK should be same.

Adding External Libraries as Dependencies with Gradle:


 We can extend the functionality of application by using already build libraries by other developers
by adding its dependency in our dependency body in module gradle file.
 Dependencies are incoming files, on which our app is depends.
 Add Dependencies in project:
o Manual:
 If we add any full library in our project then we can create an directory & download a
JAR(Java Archive) file.
 This tell gradle the include all files on this path & compile it:
comile fileTree(dir: 'lib', include: ['*.jar'])
o Automatic:
 Libraries updates over time so using manual approach is not good practice so we
should use automatic approach by using a central repository.
 J center is large repository ware house for java & android libraries.
 This tell the android to look here for central repositories:
repositories {
google()
jcenter()
}

Abdul Qayoom 63
Android O & Java Notes
 We have to add the exact name for the library to use it.
 This will use to fetch the data from internet:
implementation 'com.loopj.android:andoid-async-http:1.4.9'
 This implementation will provide us methods to provide params & get response in
JSON.
 Then sync project (Download repository files from specified location)
 We can see all our project external libraries used in External libraries (project view).
 We should use libraries for make our work simple.

James Smith's site for the Android Async Http Client Library:
Manage App Permissions in the Android Manifest:
 Permission are things which we allow our app to do in our device like accessing location, contacts,
camera etc.
 All permission of application lives in android manifest file.
 Access internet permission:
<uses-permission android:name="android.permission.INTERNET"/>
 Access device location permission:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
 If we want to get location from wifi networks & cell towers then we have to use coarse location &
if we to get location from GPS than we have to use fine access location.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
 Access fine location provide us precise location by getting from GPS.
 Our application need permission to use any device resources b/c with it android will not allow for
that.
 Application use each other resources but only those for which android device give them
permission & without that application can access each other resources.

Runtime Permissions & Using the LocationManager to Get Your Location:


 Create a constant for location provide:
String LOCATION_PROVIDER = LocationManager.NETWORK_PROVIDER;
 Create location manager for start & stop the location.
LocationManager mLocationManager;// start & stop location updated
 Create a listener for location.
LocationListener mLocationListener;// notify if location is changed
 Create code in onResume so it can be executed before interacting with it:
 For getting permissions on runtime, we need to :
o Request the permission:
 Add a req code:
final int REQ_CODE = 123;
 Check the location permission in if-else:
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
REQ_CODE);
 Get the result by checking the request code on onRequestPermissionResult:
o Acts on users’ response.
 onResume Code:

Abdul Qayoom 64
Android O & Java Notes
@Override
protected void onResume() {
super.onResume();
getWeatherForCurrentLocation();
}
private void getWeatherForCurrentLocation() {
mLocationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
mLocationListener = new LocationListener() {
@Override
public void onLocationChanged(@NonNull Location location) {
Log.d("weather", "onLocationChanged received");
String latitude = String.valueOf(location.getLatitude());
String longitude = String.valueOf(location.getLongitude());
Log.d("weather", "Longitude is "+longitude+
" & latitude is "+latitude);
}

@Override
public void onProviderDisabled(@NonNull String provider) {
Log.i("weather", "onProviderDisabled received");
}

@Override
public void onProviderEnabled(@NonNull String provider) {
Log.i("weather", "onProviderEnabled received");
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.i("weather", "onStatusChanged received");
}
};
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
REQ_CODE);

Abdul Qayoom 65
Android O & Java Notes
return;
}
mLocationManager.requestLocationUpdates(LOCATION_PROVIDER, MIN_TIME,
MIN_DISTANCE, mLocationListener);
}
 Get permission result on runtime:
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQ_CODE){

if (grantResults.length > 0 && grantResults[0] ==


PackageManager.PERMISSION_GRANTED){
Log.i ("Weather", "Permission granted...");
getWeatherForCurrentLocation();
}else {
Log.i("weather", "Permission denied");
}
}
}
Networking, HTTP Requests, Status Codes & APIs:
 HTTP (Hyper- text Transfer protocol) is used to request web services.
 Get HTTP request used to read the data from the server.
 Post HTTP request used to add (create) data on server.
 DELETE HTTP request used to delete the data from server.

 Server response with status code(404 = not found, 200 = ok, 401 = unauthorized, 502 = bad
gateway) & provide file if exist.
 API is a contact or set of rules which our program has to follow for getting the data.
 API will get a type of input & results the something on that behalf.
 Two types of API calls:

Abdul Qayoom 66
Android O & Java Notes

 We can get API from many of services on the official site of that service.

List of HTTP Status Codes:


OpenWeatherMap API Documentation:
Transport for London API Documentation:
Markit On Demand API Documentation:
Twitter API Documentation:
HTTP Response Cheat Sheet:
Making the HTTP Request for Weather Data:
 We can get the response by providing params (longitude, latitude, app id):
RequestParams params = new RequestParams();
params.put("lat", latitude);
params.put("long", longitude);
params.put("app_id", APP_ID);

letsDoSomeNetworking(params);

Abdul Qayoom 67
Android O & Java Notes
/**
* @param params These are parameters of API (longitude, latitude & app id)
*/
// TODO: Add letsDoSomeNetworking(RequestParams params) here:
private void letsDoSomeNetworking(RequestParams params) {
AsyncHttpClient client = new AsyncHttpClient();
client.get(WEATHER_URL, params, new JsonHttpResponseHandler(){
/**
* @param statusCode Status code for the success operation
* @param headers Header of request
* @param response If success then response will contain result
*/
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
Toast.makeText(WeatherController.this, "Success: ",
Toast.LENGTH_SHORT).show();
Log.d(TAG, "Weather data + "+response.toString());
}

/**
* @param statusCode Status code of error
* @param headers Header of request
* @param throwable Throwable is error which cause failure
* @param errorResponse Error response is the data which return when error is
occurred
*/
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable,
JSONObject errorResponse) {
super.onFailure(statusCode, headers, throwable, errorResponse);
Toast.makeText(WeatherController.this, "Request Failed\nError : "+throwable,
Toast.LENGTH_SHORT).show();
Log.d(TAG, "Status Code : "+statusCode);
}
});
}

The JSON Format Explained:


 JSON (Java Script Object Notation) is a most common ways to organizing & transmitting data across
web.
 We can get simple data from top by get type of data:
 weatherData.mCity = jsonObject.getString("name");
 We can see our JSON data over online JSON editors to see it in organized way.
weatherData.mCondition =
jsonObject.getJSONArray("weather").getJSONObject(0).getInt("id");
 We have to match the code from different conditions available about anything in API.

Abdul Qayoom 68
Android O & Java Notes
private static String updateWeatherIcon(int condition) {

if (condition >= 0 && condition < 300) {


return "tstorm1";
} else if (condition >= 300 && condition < 500) {
return "light_rain";
} else if (condition >= 500 && condition < 600) {
return "shower3";
} else if (condition >= 600 && condition <= 700) {
return "snow4";
} else if (condition >= 701 && condition <= 771) {
return "fog";
} else if (condition >= 772 && condition < 800) {
return "tstorm3";
} else if (condition == 800) {
return "sunny";
} else if (condition >= 801 && condition <= 804) {
return "cloudy2";
} else if (condition >= 900 && condition <= 902) {
return "tstorm3";
} else if (condition == 903) {
return "snow5";
} else if (condition == 904) {
return "sunny";
} else if (condition >= 905 && condition <= 1000) {
return "tstorm3";
}

return "dunno";
}
 Than we have update our icon of any provided resource according to that param result.
weatherData.mIconName = updateWeatherIcon(weatherData.mCondition);
 Generate methods in data model class we can use the private variables values.
 Now create a data model object in onSucces call back & get the response.
WeatherDataModel weatherDataModel = WeatherDataModel.fromJson(response);

JSON Homepage:
JSON Visualiser JSON Editor Online:
JSON Visualiser JSON Mate:
Do you know JSON:
Parse the JSON and Handle Exceptions with a Try-Catch Block:
 We have to parse the JSON data into Java object to use it.
 Declare all variables of data in model class.
 Create a methods which return data model object.
 We can get the nested value by array & object methods.

Abdul Qayoom 69
Android O & Java Notes
Full List of Weather Conditions:
Update the UI and Show the Weather to the User:
 Methos code:
public void updateUI (WeatherDataModel weatherData){
mTemperatureLabel.setText(weatherData.getTemperature());
mCityLabel.setText(weatherData.getCity());
int resourceId = getResources().getIdentifier(weatherData.getIconName(), "drawable",
getPackageName());
mWeatherImage.setImageResource(resourceId);
}

 We can the drawable image id aby getIdentifier method:
int resourceId = getResources().getIdentifier(weatherData.getIconName(), "drawable",
getPackageName());
 Now update the UI in onSuccess call back

Create a New Activity and Link Activity & Layout:


Using Intents to Navigate Between Activities:
Android Intent Documentation:
Intent Extras and EditText onEditorAction() Callbacks:
API Call with a City Name, the Logical NOT and Freeing Up Resources:
The Complete Code for the Clima App:

Abdul Qayoom 70
Android O & Java Notes

Coding Challenge #4 - REST & APIs - Build a Bitcoin Price Tracker:


What You Will Create:
Step 1 Import the Project:
Step 2 Check out the Files in the Stub Project:
Step 3 Add App Permissions to Access the Internet:
Step 4 Add the Android Asynchronous Http Client Dependency:
Step 5 Set up the Spinner View:
Step 6 Interpret the API Docs and Request a JSON:
Step 7 Make a GET Request Using the Networking Code:
Step 8 Parse the JSON and update the User Interface:
Step 9 Submit Your Assignment on Github [Optional]:
Bitcoin Ticker Challenge Solution:

Abdul Qayoom 71
Android O & Java Notes

Complete Firebase Database:


Introduction & Setup:

 Introduction:
o Firebase is cloud No-SQL database & comes with real time database.
o Real time database refers to the synchronization of data across all clients in real time.
 Setup:
o Sign -in Google firebase.
o Create a new project in firebase database.
o Add application in firebase.

Build a WhatsApp Clone and learn to use Cloud Data Storage [Tutorial]:
What Will We Make:
 We are going to create a chat application same as whatsapp.
 We will use firebase for saving our data on cloud.
 We will how to use could & store & retrieve data using firebase service.
 We will also learn to store data locally using SharedPreferences.
 We will work with listview & adapter.

Project Tour and Overview of Existing Code:


Download the Project Stub:


What is Firebase:
 Firebase is backend serves provider, owned by google.
 Firebase offers many of services but we will focus during this module of real time database &
authentication.

Firebase website:
Firebase & Big Brother:
Create a New Project on Firebase and Configure the Android App:
 Sign in with google account & go to console where all projects live.
 Follow the steps & create account.
 Now add App in project:
o Copy the package name from manifest & past in package name field.
o Leave other fields blank & register app.
o Download JSON file & paste in app directory by make in project view.
o Now add gradle file into project gradle files:
 Google services dependency class path in project gradle file.
Classpath ‘com.google.gms:google-services:4.3.10’
o Now app level gradle files:
 Apply plug-in in end of file:
apply plugin: 'com.google.gms.google-services'
 Add dependency for firebase:
implementation platform('com.google.firebase:firebase-bom:28.4.2')
 Add dependency for Google analytics:
Abdul Qayoom 72
Android O & Java Notes
implementation 'com.google.firebase:firebase-analytics'
 Add dependency for real time database:
implementation 'com.google.firebase:firebase-database'
 Add dependency for authentication:
implementation 'com.google.firebase:firebase-auth'
 Now sync:
o Now we have to enable authentication:
 Goto console & then authentication & select a method for sign-in:
 Enable email & password authentication.

Full List of Firebase Dependencies:


Access the Firebase Console:
Registering New Users, Validating Data & the Builder Design Pattern:
 Validate the password:
private boolean isPasswordValid(String password) {
//TODO: Add own logic to check for a valid password (minimum 6 characters)
String confirmPwd = mConfirmPasswordView.getText().toString();
return confirmPwd.equals(password) && password.length() > 5;
}
 Get instance method hides the object creation.
 Firebase authentication is possible by firebase auth object so Create one.
o Define:
private FirebaseAuth mAuth;
o Init:
mAuth = FirebaseAuth.getInstance();
 Create a firebase user by authentication in firebase server:
o Get email & password form text views.
o Create new user with that email & password:
public void createFirebaseUser(){
String email = mEmailView.getText().toString();
String pwd = mPasswordView.getText().toString();
mAuth.createUserWithEmailAndPassword(email, pwd)
.addOnCompleteListener(this,
new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
Log.d(TAG, "User is created: \n "+task.isSuccessful());
Toast.makeText(RegisterActivity.this, "Successful",
Toast.LENGTH_SHORT).show();
if (!task.isSuccessful()){
Log.d(TAG, "User creation failed ");
Toast.makeText(RegisterActivity.this, "Failed",
Toast.LENGTH_SHORT).show();
}
}
});
}
o Call user creation method with registration button by some validation as you fit right.
Abdul Qayoom 73
Android O & Java Notes
o Builder pattern is a way of creating object & configuring those on same time.

String Documentation:
EditText getText() Method:
Android Dialog Guide:
Task Class Documentation:
AlertDialog.Builder Class Documentation:
FirebaseAuth Documentation:
Storing Data Locally (on Device) using SharedPreferences:
 Using android shared preferences, we can save data locally on our devices.
 Shared preferences are ways to save simple pieces of data as key value pair.
o Get instance:
SharedPreferences sharedPreferences = getSharedPreferences(CHAT_PREFS, 0);
o Put value by edit method:
sharedPreferences.edit().putString(DISPLAY_NAME_KEY, displayName).apply();
o

SharedPreferences Class Documentation:


getSharedPreferences() Method Documentation:
Guide on using SharedPreferences:
Handling User Login with FirebaseAuth:
 We will use firebase authentication & sign in with email & password.

Retrieve the Locally Stored Data:


 We can retrieve the shared preferences by just getting the saved shared prefs using get
SharedPreferences methos by just providing key & mode.
SharedPreferences sharedPreferences =
getSharedPreferences(RegisterActivity.CHAT_PREFS, MODE_PRIVATE);
 We will provide separate name for every object for getting different shared prefs.
mDisplayName = sharedPreferences.getString(RegisterActivity.DISPLAY_NAME_KEY,
null);
 We can set default value if value is null.
if (mDisplayName == null) mDisplayName = "Anonymous";
Create the Model Class & Save Data to the Cloud:
 Data base reference is a particular location in cloud database.
 Database reference is used to read & write data in firebase database.
 We need a database reference object to communicate with cloud database at that location.
mDatabaseReference = FirebaseDatabase.getInstance().getReference();
 We can also set listener for enter key in soft keyboard by OnEditorListener method.
mInputText.setOnEditorActionListener((v, actionId, event) -> {
sendMessage();
return true;
});
 We will create a model for an indidual message in chat.
o Create variables which we want to save in db.

Abdul Qayoom 74
Android O & Java Notes
private String message;
private String author;
o Set Constructor for both vars & also a no - argument constructor:
public InstantMessage(String message, String author) {
this.message = message;
this.author = author;
}
o Also set setter & getter methods.
o We will use child & push methods of database reference to save data in cloud.
// TODO: Grab the text the user typed in and push the message to Firebase
String message = mInputText.getText().toString();
if (!TextUtils.isEmpty(message)){
InstantMessage chat = new InstantMessage(message, mDisplayName);
mDatabaseReference.child("messages").push().setValue(chat);
mInputText.setText("");
}
o

DatabaseReference Class Documentation:


FirebaseDatabase Class Documentation:
ListViews, Adapters & ArrayLists:
Building Layouts with an Adapter:
Firebase DataSnapshot Class Documentation:
BaseAdapter Class Documentation:
Oracle ArrayList Class Documentation:
Implementing the ViewHolder Pattern:
Smooth Scrolling in Android:
Retrieve Data from Firebase with a ChildEventListener:
Firebase ChildEventListener Documentation:
Oracle ArrayList Class Documentation:
Styling Views with 9 Patch Images:
Creating a 9-Patch (Resizable Bitmap):
Guide to 9-Patch Graphics:
Download the Complete Code for the FlashChat App:
Challenge Persist the Username in Firebase instead of Local Storage:
Solution Persisting a username in Firebase:

Abdul Qayoom 75
Android O & Java Notes

App Design Course Introduction:


Introduction to the App Design Course:
 We are here to learn 20% of design fundamentals & make it 100% by using in our ideas.
 We are here to just understand the app design.

Why is Design Important for an App Entrepreneur:


 There are around 2Million apps on apps store & 4 million apps ono play store, & design will make us
to stand out in that ocean.
 Design will fall in love to user not functionality.

Designer versus Non-Designer Thinking:


 Designer Mind:
o Color have a specific mode associated with & colors are not just limited to 10,20, or 100 but
they are thousands.

o Focus on fonts or typography before content.

o
 Non-Designer Mind:
o Color are just color & they limited to under 10,20 0r even 100.

o Just think about content not fonts.

Abdul Qayoom 76
Android O & Java Notes
o

Abdul Qayoom 77
Android O & Java Notes

Colour Theory:
 Colors should convey your message before your content.
 Thinks about your emotions which you want to convey before choosing any color.

Color Favoritism:

Abdul Qayoom 78
Android O & Java Notes

Abdul Qayoom 79
Android O & Java Notes

Abdul Qayoom 80
Android O & Java Notes
Understanding the Mood of Your Colour Palette:

Abdul Qayoom 81
Android O & Java Notes

Abdul Qayoom 82
Android O & Java Notes
How to Combine Colours and Formulate Colour Palettes:

 Choose one & chose another next to it.

o Good for background & front ground.


 Complimentary colors (Opposite each other)

Abdul Qayoom 83
Android O & Java Notes

Abdul Qayoom 84
Android O & Java Notes

o Complementary colors provide clashing designs.

Abdul Qayoom 85
Android O & Java Notes
o We can use split colors to make less classhing
o Good for logo design & Attention-grabbing screens.
 Split colors (Opposite but by next to it)

o They make less clashing color palate.


o Good for icon design.
 Triadic colors (In triangle):

o Well balanced & attention grabbing.


o But it seen like 90s designs b/c these color was very much in use during 90s.
 Monochromic colors (Take same color & add some amount of black or white to it):

Abdul Qayoom 86
Android O & Java Notes

o Modern look
o Work very well for modern digital design.

Handling Colors on Screen:


 Color theming:
o Color themes are designed to be harmonious, ensure accessible text, and distinguish UI
elements and surfaces from one another.
o A simple color scheme can have (Primary, Secondary & its variants (light & dark)).

 Color theme creation:


o Primary and secondary colors
o Variants of primary and secondary colors
o Additional UI colors, such as colors for backgrounds, surfaces, errors, typography, and
iconography.

Abdul Qayoom 87
Android O & Java Notes

 Primary color:
o A primary color is the color displayed most frequently across your app's screens and
components.
 Dark & light primary variants:
o Your primary color can be used to make a color theme for your app, including dark and light
primary color variants.
 Create contrasting UI elements:

Abdul Qayoom 88
Android O & Java Notes

o This UI uses a primary color and two primary variants.


 Secondary Color:
o A secondary color provides more ways to accent and distinguish your product. Having a
secondary color is optional, and should be applied sparingly to accent select parts of your
UI.
o If you don’t have a secondary color, your primary color can also be used to accent
elements.
o Secondary colors are best for:
 Floating action buttons
 Selection controls, like sliders and switches
 Highlighting selected text
 Progress bars
 Links and headlines
 Dark & Light secondary variants:

Abdul Qayoom 89
Android O & Java Notes

o This UI uses a color theme with a primary color, a primary variant, and a secondary color.
 Surface, background & error colors:
o Surface, background, and error colors typically don’t represent brand:
 Surface colors affect surfaces of components, such as cards, sheets, and menus.
 The background color appears behind scrollable content. The baseline background
and surface color is #FFFFFF.
 Error color indicates errors in components, such as invalid text in a text field. The
baseline error color is #B00020.

Abdul Qayoom 90
Android O & Java Notes

 Typography & iconography colors:


o "On" colors
o App surfaces use colors from specific categories in your color palette, such as a primary
color. Whenever elements, such as text or icons, appear in front of those surfaces, those
elements should use colors designed to be clear and legible against the colors behind them.
o This category of colors is called “on” colors, referring to the fact that they color elements that
appear “on” top of surfaces that use the following colors: a primary color, secondary color,
surface color, background color, or error color. When a color appears “on” top of a primary
color, it’s called an “on primary color.” They are labelled using the original color category
(such as primary color) with the prefix “on.”
o “On” colors are primarily applied to text, iconography, and strokes. Sometimes, they are
applied to surfaces.
o The default values for “on” colors are #FFFFFF and #000000.

Abdul Qayoom 91
Android O & Java Notes

 Accessible colors:

o To ensure an accessible background behind light or dark text, your background can
use light or dark variants of your primary and secondary colors.
o Alternatively, these colors can be used for typography that appears in front of light
and dark backgrounds.
 Color Swatches:
o A swatch is a sample of a color chosen from a range of similar colors.

Abdul Qayoom 92
Android O & Java Notes

volume_up
o Check marks indicate whether a text color is legible in front of a background:
 A white check mark indicates when white text is legible on a background
color.
 A black check mark indicates when black text is legible on a background
color
 Alternative colors:
o The Material Design color system supports alternative colors, which are colors used
as alternatives to your brand’s primary and secondary colors (they constitute
additional colors to your theme). Alternative colors can be used to distinguish
different sections of a UI.
o Alternative colors are best for:
 Apps with light and dark themes
 Apps with different themes in different sections
 Apps that are part of a suite of products
o Alternative colors should be used cautiously, because they can be challenging to
implement cohesively with existing color themes.
 Additional colors for data visualization:
o Apps can use additional colors to convey categories that are outside of your main
color theme. They are still a part of your full color palette.

Abdul Qayoom 93
Android O & Java Notes

o This app has a color theme with five additional colors, which it uses when multiple data
visualizations are shown on the same page.
 The Accounts section uses green
 The Bills section uses orange and yellow
 The Budget section uses purple and blue

Applying color to UI:

 App bars:
o Top and bottom app bars use an app’s primary color. System bars can use a dark or
light variant of the primary color to separate system content from top app bar content.

Abdul Qayoom 94
Android O & Java Notes

 Blending App bar with the background:


o When an app’s top or bottom app bar color is the same color as the background color,
they blend together, placing emphasis on an app’s content instead of its structure.

Abdul Qayoom 95
Android O & Java Notes

o This app’s bright, seamless layout uses its primary blue (blue 700) color for app bars,
bottom navigation, and the background color, so individual elements stand out less, and
content stands out more. The activation state uses the secondary yellow. It includes a
shadow on the bottom navigation to show the elevation division between surfaces.
 Backdrop:
o The backdrop has a front and back layer. To distinguish between these two layers, the
baseline back layer color is your primary color and the baseline front layer is white.

Abdul Qayoom 96
Android O & Java Notes

o This app uses its primary color (purple 800) on the backdrop’s back layer. The text fields
are a light primary variant (purple 700). A secondary color (red 700) is applied as an
accent to the flight fares.
 Sheets & Surfaces:
o The baseline color for sheets and surfaces, such as bottom sheets, navigation drawers,
menus, dialogs, and cards is white. These components can incorporate color to create
contrast between other surfaces. Contrast can make surface edges apparent, indicating
elevation differences when surfaces overlap.

Abdul Qayoom 97
Android O & Java Notes

o This product has changed the default white to a primary color in a bottom sheet and the
navigation drawer.
 This product uses a primary color (purple 500) in part of the bottom sheet instead
of the baseline white.
 This product’s navigation drawer uses its primary color (purple 500) instead of the
baseline white.
 Model Sheets:
o Use contrasting colors on surfaces that appear on-screen temporarily, such as
navigation drawers and bottom sheets. Usually these surfaces are white, but you can
use your app’s primary or secondary color.

Abdul Qayoom 98
Android O & Java Notes

o This app uses its primary color blue (blue 700) on the bottom navigation drawer, a primary
dark variant (blue 800) for the account switcher, and a secondary color (orange 500) for
selection.
 Cards:
o The baseline color for cards is white. This color can be customized to express brand
or improve legibility. Card text and icons can also use the color theme to improve
legibility.

Abdul Qayoom 99
Android O & Java Notes

o The surfaces of these cards use the primary color (purple 500). The app’s background
color is white. The secondary color (teal 200) is used for data visualization.
 Buttons, chips & selection controls:
o Buttons, chips and selection controls can be emphasized by applying your primary or
secondary color to them.
o Color categories:
 The baseline color for contained, text and outlined buttons is your primary color.
 The baseline color for floating action buttons and extended floating action buttons
is your secondary color.
 The baseline color for selection controls is your secondary color.

10
Abdul Qayoom
0
Android O & Java Notes

o The color theme for this app consists of a primary color (purple 500) with a primary dark
variant (purple 600) and a secondary color (teal 200).
 This product uses the primary color (purple 500) for the bottom app bar and the
secondary color (teal 200) as an accent for the floating action button and selection
controls.
 This product uses the secondary color (teal 200) as an accent for selected list
items.
 Button, Chips & Selection controls:
o Buttons, chips, and selection controls can be emphasized with your primary or
secondary colors.

10
Abdul Qayoom
1
Android O & Java Notes

o This app uses its primary color (pink 100) for its extended floating action button and
chips. It uses its primary dark variant (pink 900) for the slider.

10
Abdul Qayoom
2
Android O & Java Notes

o Selection controls can inherit your app’s secondary color.

10
Abdul Qayoom
3
Android O & Java Notes

o Don’t use one of your brand colors for coloring alerts. This will help it stand out.
 Floating Action Button(FAB):
o The floating action button (FAB) should be one of the most recognizable items on your
screen.
o Use color to create contrast between the FAB and surrounding elements, such as the app
bar. Your secondary color is the baseline color for use on the FAB. If your canvas uses
many colors, your FAB can use monochromatic coloring instead, to stand out from the
content.

 Typography & iconography:


o Color can express whether text has greater, or lesser, importance relative to other text.
Color also ensures text remains legible when placed above imagery or backgrounds,
which can make it difficult to read the text in front of them.
o Typography hierarchy:
 Color can increase both text’s visibility and its level of importance.

10
Abdul Qayoom
4
Android O & Java Notes

 The color theme for this app consists of a primary color (purple 500) and a
secondary color (orange 600). Orange accents the card’s headlines, and purple
appears on tabs and buttons.
o Headlines & tabs:
 Important text, like tabs and headlines, can use your primary or secondary
color.

10
Abdul Qayoom
5
Android O & Java Notes

 This app uses its secondary color (orange 800) to accent and call attention to the
headlines.
o Text Legibility:
 When text is placed above imagery, it often leads to legibility issues. Creating
a colored layer between text and image can ensure text remains legible.

10
Abdul Qayoom
6
Android O & Java Notes

 This app applies a yellow scrim above imagery to ensure text above it is legible.
o Icons:
 Icons help identify actions and provide information. Their color should
contrast against the background to ensure that they are legible and identifiable.

10
Abdul Qayoom
7
Android O & Java Notes

 Shrine uses its primary dark variant (pink 900) for icons.

Tools for Designing with Colour:


Color Hunt:
 Choose colors according to mode.

Material Palette:
 Very good for android developers.

Color Zilla:
 Browser extension for choosing color from sites, which they used.

Flat UI Colors:
 IOS developers use colors from this site.

Further Reading on Designing with Colour:

10
Abdul Qayoom
8
Android O & Java Notes

Typography:
Introduction to Typography:
 Typ0ography also pass message as colors so we should also know how to use them combine them
with others.

The Serif Font Family - Origins and Use:

 Serif have tiny little feets.


 Serif comes in use during carving letters on stones, where those little feets appear.
 Classes of serif:

10
Abdul Qayoom
9
Android O & Java Notes

 Size of “O” width in left & right side & top bottom is made differentiate in old & modern
styles.
 Slab Serif have no any difference in thin & thick size.

The Sans Serif Font Family - Origins and Use:


 San Serifs have no any feets.
 Families are:

 Humanist have modulation & Grotesque have no any change in font size from any size.

How Typography Determines Readability:


 Readability is best parameter to choose a fonts type.

11
Abdul Qayoom
0
Android O & Java Notes

How to Combine Fonts Like Pro:


 Title type font should be different from the body type phase fonts, which create contrast & Interest
in our design.
 Serif & Sans-Serif work very well (Heading & body).

 Serifs have better readability as compare to serifs so they should be in headings.


 Do no use sans-serif with sans-serifs.
 Use only two different fonts but not more than that.
 Use fonts as mode.
 Do not mix to modes with multiple fonts, that will make design very strange.

11
Abdul Qayoom
1
Android O & Java Notes

 Use same time era (old with old & new with new).
 Use same modes.
 Never ever use them:

 What font is a tool to identify & get info about type phase & fonts on web.
 Font Squirrel is free fonts site for download & use them.

Further Reading about Typography:

11
Abdul Qayoom
2
Android O & Java Notes

The Fundamentals of User Interface (UI) Design for Mobile:


Introduction to User Interface Design:
 We have to create engaging, beautiful & emotional response UI.
 Our focus is on that in this lesson.

The Tour Guide Approach to UI Design:


 Think app as a journey & design it like that so it make look & feel nice & easy to move.
 Move attention & guide to users point to point & don’t put all content on one place.
 Attention comes to bold & bright thing first & move top to bottom.

Web Design in 4 Minutes:


The Importance of Alignment:
 Alignment is a key in graphic design & it provide feel of good design.
 Minimized alignment lines as you can (Left, Right , Center).

What is Good Practice in Interaction Design:


 Light comes from top to bottom so use that strategy for UI design.

 Design should representative to the real world & it should be easily identifiable.
 Design should give clues to user.
 Thinks should look like cards or pieces on screen (Material design):

11
Abdul Qayoom
3
Android O & Java Notes

 All icons & things on screen should have some hint of interpretability.

Colour in User Interface Design:


 Start design with simple color(Monochrome) so we can focus on placement of things without
distracting by colors.
 Start with one color & add more if you want.
 Search design of other professional designers according your color hex-code on dribble.

Link to the Dribbble search by colour tool:


The Many Ways of Designing Text Overlays:
 Background should have less contrast than its content, Content should be stand out from the
background.
 If our background has image & it is changing over time than we can set an overlay between content
& image so it looks stand out from image.
 We can also blur to background image for better readability of text or content.
 We can set half overlay on background image if our content will be on half portion of screen.

How to Be an Attention Architect:


 Vary the font type phase & size for make design more attentive by (Increase size, change style ,
increase spacing etc).
 Architect user journey by thinking as a user.

What Clients Say and What Clients Mean - Translating Client Speak:
Further Reading on User Interface Design:

11
Abdul Qayoom
4
Android O & Java Notes

The Fundamentals of User Experience (UX) Design for Mobile:


Introduction to User Experience Design:
 UX vs UI:

 UX means thinks how user will user & UI means how it will look better.
 We should follow user to make it better & make users life easy.

Usability:
 Ask yourself what is the user using our app for (Core functionality of our app).
 Decrease the steps as you can to achieve main goal.
 Apps 1st screen should be about main functionality.
 And other functionality of come in last and one by one.

Asking for Permissions:


 Ask small fever 1st to make peoples feel constant.
 Then ask for other permissions or fevers slowly.

User Profiling:
 Profile your users about their experience & their purpose on your app.
 Profile your users & re-evaluate your app according to that.

Form vs. Function:


 Form vs function:

11
Abdul Qayoom
5
Android O & Java Notes

 Always focus how users will use it now how it looks good.

Consistency:
 App design should be constant with product, organization & users.
 Think about consistency not just in appearance but also content so it do not confuse to user.

Simplicity:
 Do simple as you can.
 Add feature as users demanding.

Don't Make Me Think:


 Do not increase difficulty of users & overload user struggle.
 Make it simple so they do not need to learn to use our app & also do not add learning lessons in app
in starting.
 Try use words which convey right message to user.
 Avoid confusing users.

Onboarding:
 Use swipe gesture when user is doing nothing & u want to teach him any of the feature you want.

Idiot Boxes:
 Do not show pop ups where user have no need for that.

11
Abdul Qayoom
6
Android O & Java Notes

Further Reading on User Experience Design:

11
Abdul Qayoom
7
Android O & Java Notes

Designing for iOS vs. Android - What are the Important Differences:
Android vs. iOS Design:
 Design should be fit to environment for what we are designing our application.

Navigation:
 Android have hardware button for back & ios do not so use back button on app for ios but not for
android.

 In Android avoid to use bottom nav menu (When needed you can) but use hamburger, b/c android
have hardware button on bottom & they looks very similar to bottom nav menu so avoid using in
android.

The Devil is in the Details:


 Title place also make difference in ios and android users.

11
Abdul Qayoom
8
Android O & Java Notes

 Choosing menu is available in android but ios have sliding wheel.

Differences in Icon Design:


 Icons also make difference for android & ios apps

11
Abdul Qayoom
9
Android O & Java Notes

Flat vs. Material Design:


 Flat design have not any shadow (No contrast, no gradient), it looks like piece of glass & nothing
stands out up from the screen.
 Material design have shadow (Slightly 3D & very near to real materials), It looks like piece of paper
of piece of card.
 Material design is good which provide feels that & users identify by which we have to interact with.

Differences in Establishing Visual Hierarchy:


 Visual hierarchy also make different in ios & android design.

12
Abdul Qayoom
0
Android O & Java Notes

 In Android (Established by size of fonts):


o Title will be large in all
o Sub title will be smaller than title.
o Content will be smaller than sub title.
 In IOS (Established by ):
o Title will be bold
o Sub title with regular
o Text will be thin

iOS and Android Design Guidelines:


 Get a device for which we are going to develop & make use of it as a user & search for best practices
in official apps.
 Use material design guide lines for better designing for android.
 Use ios human interface design guidelines for designing for ios.

Material Design Guidelines:


iOS Human Interface Design Guidelines:

12
Abdul Qayoom
1
Android O & Java Notes

Putting it All Together - A Step-By-Step Guide to the Mobile Design


Workflow:
 We are going to design a demo project and combining all of the designing concepts.
 This demo project will have:
o Choose workout
o Track workout
o Guided work out

Step 1 Design Patterns and Colour Palettes:


 Explore some best mobile patterns & expire from best designers work on sites (Mobile-
patterns.com & pttrns.com).
 Choose a color pallet form (color hunt .com)

12
Abdul Qayoom
2
Android O & Java Notes
Mobile Patterns:
Flat UI Colors:
Patterns:
Material Design Palette for Android:
Color Hunt:
Step 2 How to Design User Flow Diagrams:
Step 3 How to Create Wireframes:
Free Download of Pop App by WooMoo (Google Play Store):
Free Download of Pop App by WooMoo (Windows Tablet):
Free Download of Pop App by WooMoo (iOS App Store):
Wireframe cc:
UI Stencils' Free Downloadable Design Templates:
Step 4 How to Create Professional Mockups:
Sketch 3:
PhotoshopIllustrator:
Canva:
Marvel:
How to Use Sketch (4.1) to Create Mockups for Mobile:
Mockup for the example workout app:
How to Use Canva to Create Mockups:
Canva:
Your Turn to Create Your Own Mockups:
Alternatives to Sketch - UX Pin:
Tools for Creating Mockups - Smart Mockups:
Tools for Creating Mockups - Magic Mockups:
Tools for Creating Mockups – Placeit:
Alternatives to Sketch – Invisionapp:
Alternatives to Sketch – Marvel:
Alternatives to Sketch – Moqups:
Step 5 How to Create Animated App Prototypes:
Principle:
Marvel App:
InVision App:
Proto.io:
Mac Keynote App:
How to Create Animated Prototypes with Keynote:
How to Create Prototypes with Marvel App:
Check Out My Example Prototype Create with Sketch and Marvel:

12
Abdul Qayoom
3
Android O & Java Notes
Get Access to Mavel App Here:
Your Turn to Create a Prototype:
My Example Prototype Created with Marvel App:
Download the Free Android Marvel App to See Your App on Your Phone:
Download the Free iOS Marvel App to See Your App on Your Phone:
1.

12
Abdul Qayoom
4
Android O & Java Notes

Resources:
Where to Find Free-For-Commercial Use Image Assets:
Where to Find Free-For-Commercial Use Icons:
Keep Learning and Improving:
Sign up to the LAB Report here:

12
Abdul Qayoom
5
Android O & Java Notes

The Complete App Marketing Course:


The Importance of App Marketing:
The Fallacy of Build it and They Will Come:

12
Abdul Qayoom
6
Android O & Java Notes

Idea Validation - Save Yourself Time and Money:


The Importance of Idea Validation:
The Simplest Way of Validating Your Idea - The Starbucks Method:
Using Google Trends to Estimate the Size of Your Market:
Google Adwords Keyword Planner:
Google Trends:
The Landing Page Validation Method:
How to Create a Landing Page Website in Less than an Hour:
Wordpress:
Start Bootstrap:
Unbounce:
Leadpages:
Square Space:
Creating a Minimum Viable Product:
Gimlet Media - MVP Story:
Gimlet Media - Startup Stories (Grooveshark Story):
Quick MVP:
Using Crowd-funding to Validate and Fund Your Idea:
The Complete Crowdfunding Course. Get it for $19 with this Code!

12
Abdul Qayoom
7
Android O & Java Notes

App Monetization Methods - How to Make Money from Your App:


How to Monetise Your App on iOS vs. Android:
When You Should Create a Paid App:
When to use In-App Advertisements:
How You Thought About These Alternative Monetisation Models:

12
Abdul Qayoom
8
Android O & Java Notes

How to Optimize Your App Store Listing:


How to Get an App icon Designed without Breaking the Bank:
Fiverr:
99 Designs:
Split Testing for Super Success:
Store Maven:
What Makes a Good App Icon?
The Dos and Don'ts of Making App Screenshots:
MockUPhone:
LaunchKit (now open source):
Tools for Building Screenshots:

12
Abdul Qayoom
9
Android O & Java Notes

Growth Hacking Techniques for App Downloads:


Your First 1000 Customers:
1000 True Fans:
Building an Email List:
The All-Important Landing Page:
The Psychology of Influence - Robert Cialdini:
Thinking, Fast and Slow = Daniel Kahneman:
Blogging Your Way to Success:
Loose Leaf:
A Blogging Example:
Content Marketing for App Downloads:
Fit Men Cook:
7 Minute Workout:
How to Successfully Launch on Product Hunt:
PH Leaderboard:
Product Hunt:
How to Launch on Beta List:
BetaList:
How to Launch on Hacker News:
Hacker News:
If At First You Don't Succeed...:
Cross Promotion:
Social Referrals and Social Queuing:
Maître:
How to Make Social Media Work for You:

13
Abdul Qayoom
0
Android O & Java Notes

How to Get Press Coverage for Your App:


Do I need a PR Agency?
Not All Press is Created Equal:
How to Craft Your Story:
How to Craft Your Pitch:
How to Figure Out Which Journalists to Pitch:
Buzzsumo:
How to Find Anyone's Email Address:
Voila Norbert:
How to Pitch a journalist:
Boomerang for Gmail:
HubSpot Sales (previously known as SideKick):
Just-Add-Water Journalist Pitch Email:
Establishing a Relationship with a Journalist:
100 Journalists you should follow on Twitter:
What if You Still Can't Get Anyone to Write About You:
Journo Requests:
Response Source:
HARO:
Final Tips on Getting Press:
The Press Release is Dead (Mike Butcher):
Trust me, I'm lying (Ryan Holiday):

13
Abdul Qayoom
1
Android O & Java Notes

How to Get Your App Featured on the App Store:


How to Get Featured on the App Store:
Only on the App Store:
Work with the Corporate Mindset:
Native vs. Cross-Platform Apps:
Tips and Tricks for Getting Featured:

13
Abdul Qayoom
2
Android O & Java Notes

App Store Optimization - How to Rank Higher on the App Store Search
Algorithm:
What is App Store Optimisation (ASO)?
Top Tips to Optimise Your App Store Listing:
My Complete ASO Workflow:
Using Apple Search Ads as a Research Tool:
Early vs. Late Game Strategies:
Differences Between Google Play and Apple App Store:

13
Abdul Qayoom
3
Android O & Java Notes

The Right Way of Using Paid Advertising to Drive App Downloads:


When to use Paid Advertising or App Marketing:
Always Test Before You Advertise:
Which Platform to Advertise On:
How Much Does It Cost?
How to Setup Your Facebook Ad:
Use Your Competitors' Ad Budget:
Where Can I Find More Customers?
One Weird Trick to Get More Money from Apple:

13
Abdul Qayoom
4
Android O & Java Notes

App Store Reviews and Ratings:


How to Get More 5 Star Ratings and Reviews:
Use This Free Tools to Monitor Your App Reviews:

13
Abdul Qayoom
5
Android O & Java Notes

How to Use App Analytics to Increase User Retention:


How to use App Analytics to Increase User Retention:

13
Abdul Qayoom
6
Android O & Java Notes

White Hat vs. Black Hat Methods of Getting More App Downloads and
Revenue:
White Hat Techniques:
Black Hat Techniques:

13
Abdul Qayoom
7
Android O & Java Notes

Bonus How to Build Your App Showcase Website:


A 5 Second Way of Building a Web Page for Your iOS App:
How to Use Bootstrap to Build Your App Showcase Website:
Guidance on Setting up a Custom Domain and Hosting on Github:

13
Abdul Qayoom
8
Android O & Java Notes

Your Turn:
Add Navigation drawer in app:
During this app we will use material design concepts to develop a navigation drawer.

We will also learn to Impliment websites in android application.

 Create a project with empty activity:


 Add dependency to the project:
o implementation ‘com.google.android.material:material:1.3.0-alpha03’
o Sync now
 Create menus in menu folder:
o Create menus which you want to show in drawer.
 Working with main xml activity:
o Change parent layout to drawer layout:
<androidx.drawerlayout.widget.DrawerLayout

xmlns:android="http://schemas.android.com/apk/res/android "

xmlns:app="http://schemas.android.com/apk/res-auto "

xmlns:tools="http://schemas.android.com/tools "

android:id="@+id/my_drawer_layout"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context=".MainActivity"

tools:ignore="HardcodedText">

o Add Navigation drawer:


<com.google.android.material.navigation.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="@menu/navigation_menu" />

 Add String for you drawer in String value file:


o We need to add one & close functionality for drawer so we will add string for them.

<string name="nav_open">Open</string>
<string name="nav_close">Close</string>
 Working with main java file:
o Add Variable for drawer layout & toggle for drawer:
o Find them with ID:
o Open & close to drawer with toggle:
o Make always appear to drawer layout:

13
Abdul Qayoom
9
Android O & Java Notes
o Override selected item menu:

It's Time to Work Out Your Marketing Strategy:


Monthly Student Built App Showcase:

14
Abdul Qayoom
0

You might also like