Android Tips, Techniques and Theory

PART 2: Creating Content with Java with Android Studio (Programming required)

With Simple Recipes

Go Back To TOC

VITAL FEW TIPS

Using Android Studio Samples

Google Samples are useful in learning some of the Android basic concepts.

  1. From the Welcome to Android Studio screen, In the Quick Start section, select Import an Android code sample.
  2. In the Import Sample dialog box that appears, either scroll and select a sample from the list or type a topic of interest in the search field.

    NOTE: The UI section is a great category to start with.
  3. You can either:

Using Existing Activity

Instead of creating a new activity from scratch, you can use an existing activity:

  1. copy an existing activity (e.g., context_main.xml)
  2. paste it in the layout folder and give it a different name (mynewlayout.xml)
  3. modify or add components as needed
  4. If you want the new activity to launch when the app load:

Android SDK Reference

The online Android SDK Reference contained information about the Android API and is located at http://developer.android.com/reference/packages.html/.  It will show all of the packages and their classes, methods and events. One of the most used packages is android.widget which contains all of the components that you will use.
EXAMPLE:

  1. Click on a package name (e.g. android.widget).
  2. Scroll down in the bottom panel and review the interfaces and classes that is part of this package.
  3. Click on one of the classes (e.g., TextView) or interfaces for detail documentation.

You can also use the Chrome SDK Extension to search the online SDK Reference without having to go to the site:

  1. With the Chrome SDK Extension install, open Chrome and create a new tab and then type ad+Tab.
  2. Then type a search word (e.g., Button), make a selection from the list and then press the Enter key.

You can also use an offline copy of the Android SDK Reference if you installed it using Android Studio SDK Manager. If you have not downloaded it already, select it from the list and click the Install button. Now, simply navigate to the docs folder where the Android SDK Reference is installed and click on the index.html link to open it. (e.g., dev-tools/adt-bundled/sdk/doc/index.html).

Refactor Code

You can rename variables, methods, class and more by right-clicking on one of these items and then selecting Refactor > Rename or pressing CTRL+ALT+R (PC) or CMD+ALT+R (Mac). Android Studio will determine if an item is a reference to other identically named items and then rename all INSTANCES of them even in comments. How cool is that!!!
CAUTION: If you are renaming a top-level class, the filename will have to be changed as well.

Programming Construct Stub

Add programming code block stub for all programming constructs by typing a key phrase and then pressing the Enter key. For example, if you type fori and press the Enter key, you will get the following code block stub:

for (int i = 0; i < ; i++) {
   
}
asdfasfIf you type Toast and then select Toast from the list, you will get:

Toast.makeText(myCustomClass.this, "", Toast.LENGTH_SHORT).show();

Format Code

To format a portion of code so that it can be easier to read, select it first and then press CTRL+ALT+L (PC) and CMD+ALT+L (Mac). To format the entire file, don’t select anything. You may need to select more code again (e.g., a complete method) to get the indention and braces to match.

Reorganize Code

You can also reorganize code (class, method, or variable) by first ensuring the outline mode is on and then click and drag that item in the outline view to where you want to move it. For example, if you have a method that is only called from a certain class but available to all, drag it into that class.???????

Extract Local Variable Or Method

See page 419-420 or look for examples on web.
See examples at JetBrians: https://www.jetbrains.com/idea/help/extract-variable.html#d1751486e170/
If you forget to create an instance variable in your class, you  can  “convert” a local variable into an instance variable (field) by pressing CTRL+ALT+F (PC) or CMD+ALT+F(Mac)
private TextView myTextView;
@Override
protected void onCreate(Bundle  saveInstanceState) {
super.onCreate(saveInstanceState) ;
setContentView(R.layout.activity_main);
TextView  myTextView  = new TextView();

Fix Built Errors

There are several things you can do if you have built errors.

  1. Check to ensure there is no errors in your code.
  2. Press F5 to refresh project.
  3. Select Project > Clean to remove temporary files and rebuild project.
  4. Delete the R.java file.  If the Compile Automatically is enabled, the file will be immediately recreated. Otherwise, you will need to compile the project again.

Vital Few Shortcuts

Content And View

The Context is an abstract class that allows you via activities to access:

There are many methods of the Context class. Below are a few of some of the most common methods that are used:

The View Class ALWAYS used the Content class as a parameter: The View class has three public constructors:

  1. View (Content content)—simple constructor to use when creating a view from code.
  2. View (Content content, AttributeSet attrs)— constructor that is called when inflating a view from XML.
  3. View (Content content, AttributeSet attrs, int defStyle)—constructor to use when inflating and XML file and applying a class-specific base style.

Instant Run

As of Android Studio 2, a new feature that is turned on by default called Instant Run has been added that works with versions back to Android 4 (Ice Cream Sandwich) that can be a great time-saver. In previous versions, any time any changes were made to an app (e.g., Java, Resources or Configuration file); the app had to be rebuilt and re-launched. With Instant Run, CERTAIN CHANGES could be made on a running app without having to re-launch or restart the app. Go to the Preferences (Mac) or Settings (Windows) window and select Build > Execution > Deployment  > Instant Run and you will see the four options that are enabled for Instant Run. The first option allows you to hot-sway code and resource changes on deployment. To see how it worked in previous versions, uncheck Restart activity on code changes, click the OK button and then run your app again.
Regardless of the Android version, Instant Run only works on debug builds and not on release builds because additional components has to be added to the debug version of the app before it is launched to enable Android Studio to communicate with the app at runtime. To check the type of build you are currently using, go to the Build Variants Window.
Java code gets INSERTED into a running app without having to restart the current activity. There are three states that you need to be aware of:

Java For Android

The Android SDK supports a sub-set of Java 6-8 constructs and packages (e.g., java.lang, java.text, java.util). However, it also has its own set of Android Studio packages that begin with the prefix android:

Android build process uses

Add Components With Java

While it is easier to add components to a layout using an XML file, you can also add components to a layout using Java. Remember, each component in an XML file represents an instance of an object from a Java class (blueprint).

  1. Create a new project using a Blank template and save it as AddingComponentsWithJava.
  2. Change the root element RelativeLayout to a LinearLayout.

    NOTE: As you change the name of the opening element, the closing elements gets updated at the same time. How cool is that!

  3. Add an orientation attribute within the LinearLayout element and set its value to vertical.

    NOTE: This will allow us to add components that will stacked vertically.

  4. Add an id attribute within the LinearLayout element:

    android:id=”@+id/custom_layout”

    NOTES:
  1. Go the the MainActivity.java file, before the closing tag of the onCreate() method add the following code:

    LinearLayout layout = (LinearLayout) findViewById(R.id.custom_layout);
    // Since each object extends from the View class, layout parameters (e.g., height, width) will be added to them
    ViewGroup.LayoutParams params = new ViewGroup.LayoutParams();


  2. Assign the wrap_content constant as arguments for the height and width of the LayoutParams method:

    ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(
    ViewGroup.LayoutParams.WRAP_CONTENT,
    ViewGroup.LayoutParams.WRAP_CONTENT
    );

  3. Below the previous code, create an instance of the EditText and Button class:

    EditText edittext = new EditText(this);
    Button button = new Button(this);

    NOTE: The constructor method requires a context. Since you are within the current activity, you can pass it the keyword this that refers to the fact that the button is created in the context of THIS activity.

  4. Below the EditText declaration code, add the editView to the layout container:

    EditText editview = new EditText(this);
    layout.addView(editview);

  5. Below the Button declaration code:
  1. CHECK POINT: Run the app in an emulator. You should see the input text field and the button were “programmatically” added to the layout.

    NOTE: Notice that the two components are added AFTER the EXISTING TextView (e.g., “Hello, World”) that was defined in the XML layout. Hence, compontent(s) in the XML layout is executed FIRST and then any component(s) in the onCreate() method in the Java class is executed afterward.

    SEE ANDROID APP: AddingComponentsWithJava

Id With Java

The id in the XML file is used to get a HANDLE (or reference) to the component in the *.java file by attaching it to a local variable or a property. Another way to express an id is that it is used to BIND (initialize) a component to a local variable or property in the *.java file as part of the MVC design pattern.

EXAMPLE: How To Use ID with Java

While IDs are written in XML files, they are referenced in Java files programmatically once the XML files are compiled.

EXAMPLE:
TextView myText = (TextView) findViewById(R.id.myTextView)

Will return a generic View of a component that has an id of myTextView that is then CASTED in the correct View type (in this case, a TextView) denoted by (TextView) on the right side of the equal sign.