Android Studio Basics

Android Studio is based on JetBrains IntelliJ software (http://www.jetbrains.com/idea) that is the official Integrated Development Environment (IDE) for creating Android apps for Windows, Mac OS X and Linux. There are two versions:

It includes the following features:

Android Versions

Android versions are in alphabetical order and are based on some type of confectionery-themed code name starting with Cupcake. The earlier versions 1.0 and 1.1 were not released under specific code names — Wikipedia

See feautures associated with Android versions at https://en.wikipedia.org/wiki/Android_version_history.

Top Time-Saving Tips and Techniques (T4)

  1. Project Templates – Use as a starting template for a given project
  2. ALT + ENTER  – Quick Fix for many code completion and remediation
  3. SHIFT + SHIFT – Search for anything especially files
  4. Refactoring – Replace, move, delete or update code in multiple places all at once
  5. Live Templates – expand code from shortcuts
  6. Menu Maker – create menu code with UI interface
  7. Icon Maker – create various density icons from with Android Studio easily
  8. Generate Tool – create code automatically for classes after fields have been defined (e.g., constructor(s), getters/setters, toString method, etc.)
  9. Constraint Layout – to not have to rely of fragment
  10. RecycleView – to not have to rely on the ListView or the GridView
  11. XML markup – use XML markup instead of Java code whenever you can
  12. ALT + click a link – to go to the file

Keyboard Shortcuts (Delete and consolidate with tables below)

Below is a list of "vital few" shortcuts that will make you more productive when using Android Studio.

TIP: To learn all of Android Studio keyboard shortcuts go to Help > Default Keymap Reference. If you don't like the default keyboard options, you can change it by selecting Settings (PC) or Preferences (Mac) and select Keymap. To change them, you need to click on the Copy button, make changes and then click the OK button.

[NEED TO BE CLEAN UP]

On the Mac, replace ALT key with OPT key and CTRL key with CMD key unless otherwise stated.

Keyboard Shortcuts

Windows/Linux

Keyboard Shortcuts

Mac where it differs from Windows/Linux.
TIP:
For the most part, on the Mac, the commands are similar; however CMD is replaced for CTRL, OPTION is replaced for ALT.

Another View of KeyBoard Shortcuts

General Shortcuts 

DESCRIPTION SHORTCUT
Delete line  CTRL + Y
Safe Delete   ALT + DELETE
Close Active Tab   CTRL + F4
Build and run     SHIFT + F10
Build   CTRL + F9
All purpose (Meta)Shortcut CTRL + SHIFT + A

Navigation Shortcuts 

DESCRIPTION SHORTCUT
Reformat code  CTRL + ALT + L
Optimize imports  CTRL + ALT + O
Code Completion   CTRL + SPACE
Issue quick fix   ALT + ENTER
Surround code block   CTRL + ALT + T
Rename and refactor   SHIFT + F6
Line Comment or Uncomment   CTRL +/
Block Comment or Uncomment  CTRL + SHIFT +/
Go to previous/next method  ALT + UP/DOWN
Show parameters for method  CTRL + P
Quick documentation lookup CTRL + Q

Programming Shortcuts

DESCRIPTION SHORTCUT
Go to class   CTRL + N
Go to file     CTRL + SHIFT + N
Navigate open tabs      ALT + LEFT-ARROW or ALT + RIGHT-ARROW
Lookup recent files   CTRL + E
Go to line     CTRL + G
Navigate to last edit location  CTRL + SHIFT + BACKSPACE
Go to declaration   CTRL + B
Go to implementation     CTRL + ALT + B
Go to source      F4
Go to super Class   CTRL + U
Show Call hierarchy  CTRL + ALT + H
Search in path/project   CTRL + SHIFT + F

Menu Shortcuts

Create an Event Handler

Instead of writing the stub for an event handler, you can let Android Studio do it for you.

  1. Create or select an object and add an event handler to. Typically, this is a button:

    <Button android:onClick="buttonClickHandler" />|

    CAUTION: The event handler will become a Java method so you need to use the correct naming convention.

  2. Press ALT+ENTER key and choose Create onClick event handler for the list of intention action.
    NOTE: If the project has more than one class, you would see it listed.

  3. If there is only one class, click the OK button; otherwise, select the correct class and then click the OK button.
  4. CHECK POINT: You should see a method is created in the selected class.

    public void buttonClickHandler (View view) {
    						
    }

  5. Add the necessary code between the curly brace pairs.

    public void buttonClickHandler (View view) {
    Log.d ("myClassName", "A message here...");
    }

Create Classes and Other Components

You can create all kind of components (e.g., Class, Interface) from one menu option:

  1. Choose File > New > Java Class from the menu.
  2. In the Create New Class dialog box that appears, give the component a name and then choose the Kind from the menu:
    NOTE: It it best practice to start a class with a capital letter (e.g, MyUtilityClass).

  3. Click the OK button to create the component.
  4. CHECK POINT:  By default, the class is placed in the main package. If you want to move it to another package:
    1. Right click on the base package and choose New Package.
    2. In the New Package dialog box that appears give package a name and then click the OK button.
    3. Drag-and-drop the newly created class into the new package.
    4. In the Move dialog box that appears, click the Refactor button to move the class and change any code (package declaration) to match the new location.
    5. You can optioanal remove the comments.

Create Class, Getters and Setters

To create a Java class:

  1. Right-click on a package and select New > Java Class and enter a class name.
  2. Select Kind (Class, Interface, Enum, Annotation or Singleton) and then click the OK button.

To creae class stub:

  1. Right-click on a class and select Generate...
  2. Choose what you want to Generate from the list:
    1. Constructor
    2. Getter
    3. Setters
    4. Getters and Setters
    5. equals() and hashCode()
    6. toString()
    7. Override Methods
    8. Copyright
      NOTE: To create getters and setters, you must first create fields for the class.

EXAMPLE: Create Getters and Setters

You can create a set of getters and setters from a list of private instance variables.

  1. Create a class with a list of instance variables:

    public class CustomClass{
    private String myString;
    private int myInteger;
    private String myString2;
    }

  2. Position the cursor below the variables and right-click and select Source > Generate Getters and Setters.... from the list.
  3. In the Select Fields To Generate Getters and Setters dialog box that appears, select the fields that you want and then click the OK button.

Create a Method Automatically

You can define a method in one class and have it automatically created in another class. For example, let's say you have define a method name in the MainActivity.java class as highlighted below:

MyUtilityClass utility = new MyUtilityClass();
utility.addNumbers();
  1. CHECK POINT: Since the method addNumbers() does not exist yet, it will be highlighted in red.
  2. Click inside of the addNumbers() method and then press ALT+ENTER and select Create method 'addNumbers'.
  3. CHECK POINT: Notice that the addNumbers() method stub was creaed in the MyUtilityClass.java file and open this file because this is the class it is based on.

    public void addNumbers() {

    }

  4. Click the ENTER key to accept the default return type (void) and to place the cursor between the curly braces.  Now you can populate the method with your own code.

Refactor Code

There are a host of ways to use refactoring in Android Studio that allows you to rename, move and extract code. Most of the tasks can be access by selecting Refactor from the menu and then choosing an option:

Rename Code

For example, continuing with the code from the previous section:

  1. Place the cursor either in the method declaration in the MyUtilityClasss.java file OR in the MainActivity.java file where it is called and then press SHIFT+F6 and then RENAME the method (e.g., addTwoNumbers) and then press the ENTER key.
  2. CHECK POINT: Notice that the method was rename in both the MainActivity.java and the MyUtilityClass.java file even though it was change in one place.
  3. Click inside of the utility variable and press SHIFT+F6 to RENAME the varaible and you will be presented with several options. myUtilityClass was accepted for this example below:

    MyUtilityClass utility = new MyUtilityClass();
    utility.addNumbers();

  4. CHECK POINT: You should see that both the declaration and usage reference to the variable have been changed to myUtilityClass even though only one was changed.

    MyUtilityClass myUtilityClass = new MyUtilityClass();
    myUtilityClass.addTwoNumbers();

Move Code

Beside dragging and dropping a class from one package to another to move it, you can also use the Refactor method to move a package as will be demonstrated in the next step. Continuing with the code from the previous section:

  1. Open the MyUtilityClass.java file and click INSIDE of the MyUtilityClass method and then choose Refactor > Move... In the Move dialog box that appears, change the path where you want the package to be moved to and then click the Refactor button.
  2. CHECK POINT: You should see the package has been move in the Android scope panel. Notice also that the package declaration has been changed at the top of the file and if the package was move into the main package, the import statement will be removed.

Extract code

You can also EXTRACT CODE to other programming constructs as will be demonstrated in the next steps:



  1. Select the line(s) of code that you want to extract from some existing code. See the highlighted code below from the previous example:

    public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    MyUtilityClass myUtilityClass = new MyUtilityClass();
    myUtilityClass.addTwoNumbers();

    }
    }

  2. Right-click and from the menu select Refactor > Extract > Method... (CTRL+ALT+M). In the Extract Method dialog box that appears, give the method a name and then click the OK button.
  3. CHECK POINT: You should see the the line(s) of code has been extracted and placed in a method with the name you gave it and the extracted code was replaced by a method call (e.g., myMethods()).

    public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    myMethod();
    }

    private void myMethod() {
    MyUtilityClass myUtilityClass = new MyUtilityClass();
    myUtilityClass.addTwoNumbers();

    }
    }

Use Live Templates

Live Templates are snippets code that can be created by writing a code shortcut that will be expanded to the complete code stub when you click the TAB or the ENTER key. They are defined in the Preference (Mac) or Settings (Windows) menu under Editor > Live Templates. They are used to speed up your coding and fall in five categories:

Examples:

  1. Type Toast and then press the TAB or the ENTER key:

    Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT).show();
    NOTE: If you have automatic import turned on in the Preferences or Settings, an import statement will be added to the top of the code.

  2. CHECK POINT: You should see the word Toast expand to  Toast.makeText(MainActivity.this, "", Toast.LENGTH_SHORT).show();. Now, you can replace the word MainAcitvity if you need to. If you press the ENTER key, you will be taken to a place in the Live Template (between the double quotes) to give the Toast a string for the Toast message (e.g., "message goes here...).
  3. Move the cursor after a Class declaration and then type const and then press the TAB key and then enter a constant name where the cursor was placed (e.g., MYCONSTANT).

    public class MainActivity extends AppCompatActivity {
    private static final int MYCONSTANT = 331;

  4. CHECK POINT: You should see the word const has been REPLACED with private static final int MYCONSTANT = 331;. Now, if you press the ENTER key, you will see the value of the constant gets updated. That's because the constant value is randomized and it does NOT matter what the value is as long as it is CONSTANT (does NOT change). It is best practice to with a constant with ALL CAPS (eg., MYCONSTANT).
  5. Type logi and then press the TAB or the ENTER key and then complete or change the string to whatever you need it to be.

    Log.i(TAG, "onCreate: onCreate was fired");
    NOTE: The TAG constant does not exist. You can click inside of it and press ALT+ENTER and then select Create constant field 'TAG" from the menu and then give the constant a string value (e.g., MainActivity).

  6. CHECK POINT: You should see the word logi expands to Log.i(TAG, "onCreate: "); before you changed it.

Create Your Own Live Tempalte

You can review the default Live Templates to see how to create your own. Since setting the text property is a common task that you perform often, it may be helpful to create a Live Template to speed up writing code.

  1. Give a TextView an id property that will be used later (e.g., myTextView).
  2. Write a code sample of what you want to use as a Live Template. For this example, we will use:

    TextView tv = (TextView) findViewById(R.id.myTextview);
    tv.setText("Set text property for TextView here...");

  3. Select the lines of code and then from the menu select Tools > Save As Live Templates...
  4. In the Live Templates dialog box that appears, give the template an abbreviation and a description and then modify the code by:
    1. Removing all of the instances of android.widget. (including the period)
    2. Deleting the path before the R object
    3. Wraping what you want to be variables with a pair of dollar signs with variable names (e.g., $myVariable$)
    4. Removing space on the second line


      NOTE: Notice a user defined template will show up in the user section of the Live Templates dialog box above..

  5. Click the OK button to create the Live Template.
  6. CHECK POINT: Delete the original lines of code and then type the abbreviation tvText in some code and then press the TAB or ENTER key. You should see the abbreviation expands. Press the TAB key and enter the TextView id (e.g., myTextView) and then press the TAB key again and enter a string message for the TextView.

    TextView tv = (TextView) findViewById(R.id.myTextView);
    tv.setText("My text is set here...");

  7. CHECK POINT: Run the app in an emulator and you will see the text that you set appear in the TextView.

TIP: EVALUATING AN EXPRESSION

IMPORTANT CONCEPT TO REMEMBER: While not real useful now, it is important to learn early how to evaluate expressions in your code to see if your code is working as expected. This is done by setting a breakpoint where you want the code to stop and then evaluating an expression in the code:

  1. Set a breakpoint on the findViewById line
  2. Press the Debug button (not the Play button) to run the app in debug mode.
  3. Choose a virtual device from the list and press the OK button.

    NOTE: Notice that the app stop executing at the break point.

  4. Copy an expression from the code. In this case, (TextView) findViewById(R.id.textView);
    NOTE: You will need to add a semicolon to complete the expression.
  5. Then, select Run > Evaluate Expression... or press ALT+F8 to open the Expression Evaluation dialog box and then paste the expression in the Expression text field.
  6. CHECK POINT: Press the Evaluate button. You should see A LOT of the values for that expression with two of them with the phrase "Hello World!" in it. Notice is says, "Hello, World!" instead of "How are you doing?" because that line of code is AFTER the breakpoint so the setText() method has not yet been executed.



  7. Now, type the following expression [((TextView)findViewById(R.id.textView)).getText(); ] and press the Evaluate button again.  You should see the a short list of values being displayed along with the "Hello World!" phrase.



  8. Delete both the text field in the XML file and the two lines of code that was added in the Java file.