Jon Rumsey

An online markdown blog and knowledge repository.


Project maintained by nojronatron Hosted on GitHub Pages — Theme by mattgraham

Class Notes Taken During Week 6 Java 401

Monday 20 June

Class canceled.

Lab Class 26

Wants Style, Color, and Fonts.

See paper notepad for list of Font and Color pallette options.

Summer Solstice

Class will be held, run by David Souther.

Data Structures

Arrays, LinkedLists, Stacks, Queues, and Trees.

Use Linked Lists when editing data mostly near the end of a list.

Use a Tree when you want to keep things sorted => They will make it faster to locate data or determine if the tree contains the data at all.

Maps

They are KVPs.

The notion of a map is tied to Keys (things to consider when going into the map to find values) and Values (the value).

Bracket notation and dot-notation are examples of KVPs.

ArrayLists: Index is the key; Value at that index location is the... value.

Array constraints: Indexes will be zero-based and less than the total length of the array values count.

For Maps, we want to find the value quickly.

TreeMap: Maintains a backing "Tree" to help find data.

Invariance: "The rules" under which a datastructure operations.

Map Invariant Rules:

TreeMap Invariants:

Note: TreeMaps can be slow unless the data is unsorted, and HashMaps are more common.

Hash Invariants:

Hash Functions

Hash Collision

Hash Index Implementations

What Is A "Good Hash Code"?

Scaling:

Where would HashMaps be implemented?

When should I think about using a Map?

Random Accessing map items (for add or update):

Assignment:

Key Takeaways

Big-O Analysis is not the be-all, end-all:

Dealing with Data Structures you must consdier bit/byte sizes of the data:

Pigeonholing Algo:

Weds Class Notes

Android Development Overview

Bring-forward learnings from Code 301 e.g. React and Components.

Intro To Android Studio

We are going to build "Task Master" project that will build upon for the remainder of this course.

Do lots of exercising with UI Constraints to experience how they impact the UI in the emulator.

There will be times you will need to CLI-kill the emulator: Find PID, use kill command. Emulator has the PID.

Event Listeners: onClick() etc. They do not handle everything for you, but will be used a lot for Android development.

Vocabulary:

Wednesday:

Android Project

Package Names MUST BE UNIQUE, and must start capitalized.

Select an "Empty Activity".

API Level: Check out apilevels.com to see API Level utilization.

Level 24 is a good balance between features and coverage.

No legacy Android.Support files/libraries will be necessary.

OnCreate method: Just launches the current Activity.

Directory 'res/layout': Create new Activities in here.

Directory 'res/values': Contains XML files. 'strings.xml' is the most important one and will get quite large.

Directory 'res/values/themes': Overall App look and feel, including all Activities.

Directory 'manifests': AndroidManifest.xml defines where resources can be found including online APK, theme selector, icon seelctor, etc.

AndroidManifest also defines Activities and intent-filter actions and categories. These are largely auto-generated.

Tests: Uses AndroidJUnit4.

Unittests: Test your methods internally to validate your logic.

Android Tests: Interactivity of Views (did it display?) and Buttons (did it display? Was it clicked?).

Build.Gradle: There are 2 of them:

In the Module build.gradle:

MainActivity.java: Where Main app logic is implemented in code.

activity_main.xml is where the UI is defined.

Use DeviceManager to create or select existing devices. Be sure to match your configured API Level here too!

System Images must be downloaded locally in order to run an emulator for specific devices (takes time to D/L and intsall).

Layout Constraints: Determine an item that will be an "anchor" element, and then drag constraints from other items to it. There are other ways to go about it, but this method is fairly simple and effective.

Use IDs! Set the 'id' in camelCase so that the UI elements will be properly addressable. Use semantic id naming.

Chains: Use these to chain-together elements to enable various layout spacings, horizontal/vertical constraints, etc.

Constraint Layout: Make sure you stay in this layout type, for the duration of this class.

Text View: For displaying text.

All other Text Palette items besides Text View are input type elements.

RecyclerView: A List.

FragmentContainerView: Frags go in here.

ScrollView: More view available below/beside your view.

Switch: Utilize Boolean type to manage/receive these settings.

Containers: Various collection view and interactive elements. Spinner is an up/down spin-view of a collection of data.

Most of the work in these Labs will deal with the UI.

Lifecycle of Android App UI elements: onCreate, onDestroy, onStart, onStop.

These Activity Lifecycle items will be discussed in more detail during the week.

Android Developers Documentation has details on Activity Lifecycles (diagram)

Event Listeners

Review: How to create and adding an Event Listener:

  1. Get a UI element by ID.
  2. Anonymous function call/event listener.
  3. Callback function OnClick.
  4. Do stuff witin the Callback function.

Create your own callback method in Java to handle events:

  1. For this example we will be working within the onCreate() method.
  2. Button submitButton = MainActivity.this.findViewById(R.id.) (location of the XML defining the UI we are working with)

Developing Activities

In this example:

  1. Create a button and give it an appropriate ID and name.
  2. Create a new Activity and name it, and set it to not auto-launch.
  3. Add items to the new activity for create a new page with element constraints.
  4. Open the new Activity java code and build modular code just like we've been doing up to now.
  5. Update Main Activity, onCreate method, implement an Event Listener and Handler per instructions above.
  6. Set the EventHandler method using 'setOnClickListener'

Use an Arrow Function e.g.:

orderFormButton.setOnClickListener(v -> {
  Intent intentItem = new Intent(MainActivity.this, DestinationActivity.class);
}); // this enables forward and backward navigation

Intents are a lot like HTML's Anchor tag => Take user to a different view or page.

Naming Convention (camelCase and descriptiveness) is important!

Event Listeners and Handlers need to be created at App start.

Note: The Activity that we routed to can route the user back to the previous activity using Event Handlers and Callbacks.

Various Errors Will Appear in the IDE

Click the Fix command on each Warning to set new Static Data into the XML.

Google Play Store requires that all of these are cleared.

Building an APK

Build Menu > Build Bundles and APKs > Build APK(s).

These are dumped into folder

Kill Emulator

ps -ax | grep emulator
kill nnnn
get-process emulator
stop-process -Name $name_from_above_command

A Look Ahead

Week 1: Android basics.

Week 2: AWS Amplify, then try push to GooglePlay Store.

Week 3: File Storage, Location, and Mine? AWS? Launching other Apps from out App.

Week 4: Analytics and Lectures, as well as monetization of mobile apps, as well as OSS contributing.

Week 5: Final Presentations Week!

About 3 to 7 AWS technologies will be discussed throughout.

Consider getting AWS Certificates post-Code 401, but don't forget having completed school work to prove your knowledge.

Consider MOB PROGRAMMING and DEBUGGING to help get through various blockers/issues throughout these weeks.

Hash Maps

Sets and Maps are like really big arrays.

Hash Maps are in best-case O(1), and lookup based on keys is very effecient even with very large data sets.

Do not just overwrite data, use collision handling (chaining etc) to deal with duplicate keys.

Handling collisions will be a requirement going forward.

Thursday 24-June Notes

TODO: Fix the Neighborhood ZipCode Record type so that the GH tests stop failing!

Android Dev Testing

MUST run emulator to do integration / UI testing.

Standard unittests can be run, but only against non-UI components and members.

Android Dev Thursday

Intents: Routes between activities.

Preferences: Simple data storage for (settings?).

Espresso: Click-test testing in Android Studio.

Action Bar: The header bar the the Activities, located in the Theme definition, and can be shut-off/hidden.

Android Dev Thursday Talk

Activities: The Views and/or Forms that display information on the screen and provide interactive elements like buttons and textboxes and labels.

MainActivity (the first form you see).

Shared Preferences: Persistent, local storage, accessible from 2 fully-functional, separate Apps. Similar associative behavior is Facebook and the Messenger apps. User-info, configs (light/dark mode), etc are commonly stored here. Do NOT store large data items here.

Extras => Intents: Transitive Storage.

Rooms: The "database on your phone". Meant to store larger data sets.

AWS/Cloud Storage: Even larger datasets and complex information should be stored in the cloud.

Rename MainActivity to HomeActivity (refactor) so it is more semantically understandable.

Recommend creating an "activities" package to place all Activities into so they are well organized.

Text Elements are based on TWO DIFFERENT CLASSES and READONLY or READ-WRITE behaviors:

Shared Preferences Setup
  1. Remember to set an id to every element added to the UI.
  2. Declare a public static final TYPE property to create a KEY to associate with KVP to store in preferenceEditor.
  3. Declare 'SharedPreferences preferences;' as a Class Property.
  4. Create shared preferences instance 'PreferenceManager.getDefaultSharedPreferences(this);'
  5. Get Save button 'Button userSaveButton = findViewById(R.id.BUTTON_ID);
  6. Use onClick (see code detail below).
  7. Get nickname (see code detail below).
  8. Put nickname in the preference editor.
public class ... {
  // set up the editor
  SharedPreferences.Editor preferenceEditor = preferences.edit();

  userSaveButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
      // grab the edit text for nickname
      EditText userNicknameText = findViewById(R.id.USER_NAME_INPUT_ID);
      String userNicknameString = userNicknameText.getText().toString();

      // userNicknameString will be the KEY in SharedStorage
      preferenceEditor.putString(USER_NICKNAME_TAG, userNicknameString); 
      preferenceEditor.apply(); // DO NOT FORGET THIS ELSE NOTHING SAVES!!
    }
  });
}
Shared Preferences Consumption
  1. init shared prefs
  2. get the value
  3. set the returned value to a view Element
// after the Class declaration
SharedPreferences preferences;

// within a method that needs to grab this data
preferences = PreferenceManager.getDefaultSharedPreferences(this);
String userNickname = preferences.getString(UserSettingsActivity.USER_NICKNAME_TAG, "No Nickname");
TextView userNicknameText = findViewById(R.id.ELEMENT_ID);

// the rest of the method and class code...
Toast

A Toast is an animated UI element that slides up from the bottom of the screen containing an informational message for the user, and after a predetermined period of time, animates sliding back down off the bottom of the device screen.

Toast.makeText(UserSettingsActivity.this, "Settings saved!", Toast.LENGTH_SHORT).show();
Snackbars
Snackbar.make(findViewById(R.id.ELEMENT_ID))
Device File Explorer

Check out 'data.com.yourthing.packagename' to view cached data including 'Shared Preferences'.

Android Activity Lifecycle

Check out The Activity Lifecycle on Android Developers

Check out the diagram

Only run when the View first loads: 'onCreate()' => ONLY runs the very first time a View is loaded and launched.

Runs when the View is resumed: 'onResume()' => When going BACK to a View

Android Extras

These are used to send things along with Intents.

Android Values Strings

Use 'strings.xml' in res/values directory to store regularly used strings e.g. for UI element text.

Espresso Testing Intro

  1. Emulator MUST BE RUNNING.
  2. Run > Record Espresso Test, do NOT force close it.
  3. Click items (slowly) and watch the Record Your Test viewer load with the UI navigation commands.
  4. Add an Assertion Statement e.g.: Does a text box have the correct text in it? Do the expected element(s) exist on-screen?
  5. Save and allow installing the test dependencies.

The test is then written for you!

Friday 24 June

Code Challenge Whiteboard Discussion

Using shortcuts in the whiteboard is okay so long as you are vocalizing what these shortcuts mean e.g. while in an interview.

The right-tree might have duplicate values within itself! Solution: Use a SET to force uniqueness, or otherwise implement a way to avoid duplicates in your output.

Use the heading Questions/Edge Cases:

Question: When hashmapping Numbers, is a colliding value guaranteed to be a duplicate?

Tip: Arrays are usually a good go-to starting point for storage and/or returns, rather than creating a custom object, or dealing with Dicts, Sets, etc.

Android Development Recycler Views and More

Android Studios Recycler View

A Recycler View is similar to HTML tags UL and OL.

Only loads what it can display, rendered through fragments.

A View Holder encapsulates a Fragment.

A Fragment contains the actual data.

Actual data will be stored in an Array (or other Collection).

ScrollView: Loads ALL DATA AT ONCE, so it could heavy.

Set A TextView Into A Fragment

  1. Add a RecyclerView to the Activity where you want it to belong in WYSIWYG, give it a good ID.
  2. Create a method to grab a reference to the RecyclerView.
  3. Set the Layout Manager of the RecyclerView to a LinearLayoutManager.
  4. Set the Layout Manager horiz/vert scrolling behavior.
// 2. Create a method to grab a reference to the RecyclerView
private void setUpProductListRecyclerView() {
  RecyclerView productListRecyclerView = findViewById(R.id.productListRecyclerView);
  // 3. Set the layout manager of the RecyclerView to a LinearLayoutManager
  //    REMEMBER TO ADD the Context, which is usually the Activity you are currently in.
  RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);

  // 4. Set the Layout Manager horiz/vertical scrolling behavior
  productListRecyclerView.setLayoutManager(layoutManager);

  // 6. Bring in the ProductsListRecyclerViewApdater
  ProductListRecyclerViewAdapter adapter = new ProductListRecyclerViewAdapter();

  // 7. Set the adapter RecyclerView
  productListRecyclerView.setAdapter(adapter);

}
  1. Create a new ProductListRecyclerView Class.
public class ProductListRecyclerViewAdapter extends RecyclerView.adapter {
  // Implement all 3 methods required by the Interface/Abstract Class
  ...
}
  1. Back to the setUpProductListRecyclerView method, bring-in the ProductListRecyclerViewApapter.
  2. Set the adapter RecyclerView in setUpProductListRecyclerView method.
  3. Make a FragmentClass called "fragment.ProductListFragment" using a "Blank Fragment template.
  4. COMMENT-OUT any Params statements, and any code statements that rely on them.
  5. Open the Fragment in the DesignView and name it appropriately, set up layout_width and layout_height, and supply it an ID that makes sense. There are no constraints like an Activity would have. Enter FrameLayout tool and CHANGE the Fragment from Frame Layout? to a "Constraint Layout".
  6. Go back into the Adapter Class and edit the onCreateViewHolder() method to 'Inflate the Fragment'.
// 11. Inflating a Fragment
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
  // Dealing with a Layout so R.layout instead of Id
  View productFragment = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_product_list, parent, attachedToRoot=false);
  // 13. Attach Fragment to ViewHolder within the onCreateViewHolder() method in ProductListRecyclerViewAdapter.
  return new ProductListViewHolder(productFragment);
}
  1. Create a ViewHolder class to hold a Fragment called ProductListViewHolder inside ProductListRecyclerViewAdapter. Include a default CTOR that accepts a View type param, and update the super() statement if you've changed the param name.
  2. Attach Fragment to ViewHolder within the onCreateViewHolder() method in ProductListRecyclerViewAdapter.
  3. Configure ProductListViewHolder.getItemCount() method to return hard-coded Integer 100 (for testing purposes).

Next Set of Steps:

  1. Create a Data Class e.g. Product, and include a CTOR, Field(s), and GET/SETters.
  2. Create Data Items and store them into a ListArray. These just represent data that would come from any data source e.g. a DB.
  3. In ProductListRecyclerViewAdapter create a field as a Collection of e.g. Products, create a CTOR with the product param.
  4. Bind data items to Fragments inside of ViewHolders within method onBindViewHolder(). (see Class Code Repo for the TextView holder code that goes in here). Include a codeblock that will call products.get(position).getName() and assign the output to String productName. 'productFragementTextView.setText(position + ". " + productName);'. Also include in getItemCount() method 'return products.size()'.

Make Entries TAP-able:

  1. In ProductListRecyclerViewAdpater class, clean up the RecyclerView.Adapter references to actually use ProductListRecyclerViewAdapter. Update remaining methods that need to use the ProductListViewHolder in Params etc.
  2. Hand-in the Activity Context. In MainActivity, supply Context to the ProductListRecyclerViewAdapter, by adding 'this' to the params list (which causes red lines). Set a Field of type Context called 'callingActivity' and add Context to the CTOR so calling methods can include the Context with the method call.
  3. OnClick event listeners must be set on the Bindings, not on the View Element.
  4. Include a putExtra() method to store the productName (grabbed by its position, previously) and then call callingActivity.startActivity(goToOrderFormIntent).

Dr. Robin Behavior, Interviews, and Strategies

7 Steps from grad to employment

Graduation => Employment

  1. Finish 401
  2. Look for work => When you start looking is up to you but do not languish. Take time off, but get back to the routine ASAP.
  3. Send Stellar Resume to employers => Select great projects to showcase; describe who you are and what you know.
  4. Leverage your network.
  5. Technical Interviews.
  6. Meet the team => Behavioral questions, learn about the org, pitch yourself. At this point you are being seriously considered. Will I fit in this space? Can I hit the ground running?
  7. Receive an Offer =>
  8. Negotiation => DO NOT SHY AWAY from this, speak up for yourself and counter at least once, then decide to continue with offer negotiations, or thank them and move on.

GTM Strategy

Behavioral Interviews

A series of questions and/or scenarios, that have you explain how you handle situations.

Considered to be the best predictor of future behavior.

It's really a conversation about past experiences.

Practice the STAR Method to become ready to handle these questions.

Remember that the Results part of the STAR method is an opportunity to elaborate on what was learned, takeaways, etc.

Common Questions:

"Tell me about a time when you had the chance to take the lead."

Respond in the format: Situation, Task, Action, Results.

Advice:

References

Raul: logcat Colors

Raul: more logcat Stuff

How to answer behavioral questions on YouTube

Behavioral interview dos and donts by MyPerfectResume.com

Smart Strategies for behavioral questions.

Glassdoor How to prepare for the interview

Return to root readme