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:

Using Older Versions of Android and Android Studio

Below is a list of information regarding the use of older verisons of Andriod Studio and Andriod OSes.

Using Shortcuts

There are several types of shortcuts (keyboard, menu and code) that you can used to make writing code and working in Android Studio easier.

TIP: The sooner you learn these shortcuts that more proficient you will be and the more time you will save coding. So it is best to learn them upfront.

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 AND CHECK]

The following keys represent the Windows OS. On the Mac, unless otherwise stated, replace these PC keys with their corresponding Mac keys

  • ALT with OPT
  • CTRL with CMD
  • ENTER with RETURN
  • DELETE with BACKSPACE
  • F1—Show documents
  • F4—Jump to source
  • SHIFT key twice—open the Search Everywhere feature of Android Studio and type a search word (e.g., MainActivity).
  • ENTER or TAB—autocomplete code. (e.g., Start typing a class and then press ENTER or TAB to auto-complete the class name. If the class is in a different package, it will automatically import the package at the top of the code.
  • DOUBLE-CLICK ON A TAB to view full screen of panel.
  • ALT + 0—open Message Panel
  • ALT + 1—open Project Panel
  • ALT + 2—open Favorites Panel
  • ALT + 4—open Run Panel
  • ALT + 5—open Debug Panel
  • ALT + 6—open Android Monitor Panel
  • ALT + 7—open Structure Panel Panel
  • ALT + 8—open Version Control Panel
  • CTRL + /comment or uncomment selected line(s) of code with single line comments (e.g., //)
  • CTRL + SHIFT + /comment or uncomment selected line(s) of code with block comment (e.g., /* ... */).
  • CTRL + CLICK on a method or a resource - open method or resource file.
  • CTRL + SPACEBAR—bring back up Auto-complete if it has disappear AND shows documentation.
  • CTRL + D—copy and duplicate code repeatedly below existing selected code.
  • CTRL + Y   (PC) or CMD + BACKSPACE   (MAC)—cut selected code.
  • CTRL + J—jump to documentation for a class, etc.
  • CTRL + SHIFT + J—add a Javadoc comment to a method or a class
  • CTRL + P—brings up a list of valid parameters for a constructor when the cursor is in between a blank constructor parenthesis.
  • CTRL+Q—Show documents
  • CTRL + SHIFT + SPACEBAR—show the various type of constructor assigned to the class.
  • CTRL + SHIFT + ENTER—complete a statement with a semicolon.
  • SHIFT + ALT + UP ARROW or DOWN ARROW—MOVE a line of code up or down.
  • SHIFT + CMD + UP ARROW or DOWN ARROW—MOVE a complete statement up or down.
  • CTRL + ALT + Lreformat code to make is easier to read.
  • CTRL + ALT + T—surround with programming constructs (if/else, while, catch/try, do/while, etc.).
  • ALT + ENTER and click on a string and then enter a resource name - convert a string (e.g., Hello, World) to a string resource (e.g., @string/resource_name).
  • F2/SHIFT + F2—jump between highlighted syntax errors.
  • ALT + UP and ALT + DOWN ARROW keys—to quickly move between methods.
  • CMD + SHIFT + RETURN—to complete a statement with a semicolon.
  • CTRL + SHIFT + A—Command look up
  • CTRL+ALT+L—Reformat code
  • ALT+INSERT— Generate method

 

  • CTRL + ALT + SHIFT + N—Search for symbol
  • CTRL + F9—Build
  • SHIFT + F10—Build and run
  • ALT + 1—Toggle project visibility
  • ALT + LEFT ARROW or ALT + RIGHT ARROW—navigate open tabs
  • ALT + F8—Evaluate Expression
  • CTRL + MOUSE CLICK—Drill Down
  • ALT + INSERT— Generate method
  • CTRL+P—Show method parents
  • CMD+N— Generate method
  • CTRL+BACKSPACE—Delete line
  • OPTION+CMD+O—Search for symbol
  • CMD+F9—Build
  • CTRL+R—Build and run
  • CMD+1—Toggle project visibility
  • CTRL+LEFT ARROW or ALT+RIGHT ARROW—navigate open tabs
  • CMD + MOUSE CLICK—Drill Down
  • CTRL+SHIFT+ UP_ARROW or DOWN_ARROW—to MOVE a line of code or a complete method. Select it and then press the key combination.
  • To reformat code, select Code > Reformat Code…
  • You can fold (collapse or expand) code by clicking on Code > Folding and choosing one of the options (e.g., Expand, Collapse, Expand Recursively, Collapse Recursively).
  • You can show various views of the editor:
    • Double-click on the tab to expand the editor
    • View > Enter/Exit Full Screen
    • View > Enter/Exit Distraction Free Mode (hide tools)
    • View > Enter/Exit Presentation Mode (larger font size but still editable)
    • Right-click on an editor tab and select Split Vertically/Horizontally (create two instance of view)
      NOTE: You can make changes in one view while freezing the other view.
    • Right-click on an editor tab and select Move Right/Down
  • To move a window:
    • Click on the gear icon at the top right-corner of the window and then uncheck the Docked Mode
    • Go back and choose Floating Mode. Now you can move or resize the window.
    • To return it back, uncheck the Floating Mode and then choose Docked Mode.
    • You can also move the tab and window by clicking on the gear and selecting Move To and then select a direction (Top, Bottom, Left, or Right).
    • You can also just drag the tab where you want it to be.
    • To hide a window, click the hide window icon at the top-right corner of the window.
    • To restore the windows back to their original settings, select Window > Restore Default Layout. Once you have the windows set up the way you like them, you can select Window > Store Current Layout as Default.
  • If you are in a *.java file, you can easily get to the related XML file that is associated with it by clicking on the related file icon on the left side of the code view window and you will be immediately taken to the XML file.

Live Templates are code snippets 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:

  • Android
  • AndroidComments
  • AndroidLog
  • AndroidParcelable
  • AndroidXML

    Below are some of the Live Templates shortcuts for Android:

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 MainActivity 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 (e.g., 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 Template

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:
    • Removing all of the instances of android.widget. (including the period)
    • Deleting the path before the R object
    • Wrapping what you want to be variables with a pair of dollar signs with variable names (e.g., $myVariable$)
    • 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.

Creating Programming Constructs

In CONJUNCTION with the shortcuts listed above, you can create common programming constructs (e.g., classes, methods, getters/setters, event handlers, etc.)

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:
    • Right click on the base package and choose New Package.
    • In the New Package dialog box that appears give package a name and then click the OK button.
    • Drag-and-drop the newly created class into the new package.
    • 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.
    • You can optional remove the comments.

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 crease class stub:

  1. Right-click on a class and select Generate...
  2. Choose what you want to Generate from the list:
    • Constructor
    • Getter
    • Setters
    • Getters and Setters
    • equals() and hashCode()
    • toString()
    • Override Methods
    • 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.

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 created 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.

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...");
    }

Refactoring Code

You can easily update multiple areas of your code at the SAME time using a technique called refactoring. This is a big time saver compared to the normal cut/copy and paste or search/replace operations.

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:

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 variable 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();

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.

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();

    }
    }