Java Programming for Android Developers For Dummies Cheat Sheet - dummies
Cheat Sheet

Java Programming for Android Developers For Dummies Cheat Sheet

From Java Programming for Android Developers For Dummies, 2nd Edition

By Barry Burd

Android is the open source, Linux- and Java-based, software framework for mobile and portable devices. The Android operating system powers 86% of all smartphones in the world today. Android not only has a majority of users, but with the help of a (very well designed) Java-based software development kit (SDK, for short), developing apps can be straightforward and fun. This cheat sheet concentrates on commonly used code handy for any developer wishing to try their hand at building their own Android applications with the help of Java.

Commonly Used Java Code

“I have to create an enhanced for statement. Can someone remind me how to code an enhanced for statement? And while you’re at it, how can I catch an exception? Where can I find all that Java stuff quickly?”

You find all that stuff right here in this cheat sheet. The Java program in this cheat sheet contains snippets of code representing many of Java’s most important language features, including switches, strings, breaks, if . . . else statements, and arrays. As an added bonus, the program even contains a sly reference to that classic Marx Brothers movie, Animal Crackers. Enjoy!
package com.example.cheetsheet;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

import android.widget.EditText;

import android.widget.TextView;

import android.widget.Toast;



import java.util.ArrayList;



public class MainActivity extends AppCompatActivity {

EditText editText;

TextView textView;

int myInt = 42;

double myDouble = 27649.00;

boolean myBoolean = true;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

editText = (EditText) findViewById(R.id.editText);

textView = (TextView) findViewById(R.id.textView);

}

public void onButtonClick(View view) {

char myChar = 'B';

String myString = "Hello";

ArrayList<String> myList = new ArrayList<String>();

String[] myArray = {"This ", "is ", "an ", "array."};

textView.append("myInt is " + Integer.toString(myInt) + "\n");

textView.append("myChar is " + Character.toString(myChar) + "\n");

Toast.makeText(this, myString, Toast.LENGTH_LONG).show();

textView.append("myInt + myString + \" \" + myDouble is ");

textView.append(myInt + " " + myString + " " + myDouble + "\n");

try {

myInt = Integer.parseInt(editText.getText().toString());

} catch (NumberFormatException e) {

e.printStackTrace();

}

textView.append("myInt is ");

if (myInt < 5) {

textView.append("small\n");

} else {

textView.append("large\n");

}

textView.append("Is myBoolean true? ");

if (myBoolean) {

textView.append("Yes\n");

}

textView.append("myInt is ");

switch (myInt) {

case 1:

textView.append("one\n");

break;

case 2:

case 3:

textView.append("a small number\n");

break;

default:

textView.append("a lot\n");

break;

}

for (int i = 0; i < 10; i++) {

textView.append(Integer.toString(i));

textView.append(" ");

}

textView.append("\n");

int i = 0;

while (i < 10) {

textView.append(i++ + " ");

}

textView.append("\n");

int j = 0;

do {

textView.append(Integer.toString(j++));

textView.append(j <= 9 ? ", " : "");

} while (j < 10);

textView.append("\n");

myList.add("Three ");

myList.add("cheers ");

myList.add("for ");

myList.add("Captain ");

myList.add("Spaulding");

for (String word : myList) {

textView.append(word);

}

textView.append("\n");

textView.append(addPeriod("Spaulding"));

textView.append("\n");

for (int n = 0; n < myArray.length; n++) {

textView.append(myArray[n]);

}

textView.append("\n");

}

String addPeriod(String string) {

return string + ".";

}

}

How to Create a Really Simple Android App

So, you want to see the fundamentals of Android app development in one small example? How about the Empty Activity app that Android Studio creates for you automatically? Too simple? How about adding a button and a menu?

When you launch this section’s app, you see a button with the words CLICK ME on its face. When you click the button, the button’s text changes to I’VE BEEN CLICKED. Then, when you click a menu item, the button’s text reverts to CLICK ME.

A simple app’s main activity

You start by creating a new project and selecting the Basic Activity option (not the Empty Activity option) in the Add an Activity to Mobile dialog box. The Basic Activity option creates code to handle menus.

The following listing contains the app’s main activity. The lines that you type yourself are set in boldface. The other lines (the lines that Android Studio creates automatically when you select Basic Activity) are set in normal font.

package com.example.cheatsheet2;

import android.os.Bundle;

import android.support.design.widget.FloatingActionButton;

import android.support.design.widget.Snackbar;

import android.support.v7.app.AppCompatActivity;

import android.support.v7.widget.Toolbar;

import android.view.View;

import android.view.Menu;

import android.view.MenuItem;

import android.widget.Button;

public class MainActivity extends AppCompatActivity {

Button button;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

button = (Button) findViewById(R.id.button);

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

setSupportActionBar(toolbar);

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);

fab.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View view) {

Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)

.setAction("Action", null).show();

}

});

}

public void onButtonClick(View view) {

button.setText(R.string.been_clicked);

}

@Override

public boolean onCreateOptionsMenu(Menu menu) {

getMenuInflater().inflate(R.menu.menu_main, menu);

return true;

}

@Override

public boolean onOptionsItemSelected(MenuItem item) {

int id = item.getItemId();

if (id == R.id.action_reset) {

button.setText(R.string.click_me);

return true;

}

return super.onOptionsItemSelected(item);

}

}
To make this code work, you have to define a few extra goodies. In particular, you need the following:

  • A button on your main activity’s layout
  • A layout file for your menu
  • A few string values

You can create all these things with Android Studio’s point-and-click tools, but here, you can see the code. (Sometimes, it’s easier to type code than to do lots of pointing and clicking.)

The main activity’s layout file

This listing contains the code for the main activity’s layout.

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout

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/content_main"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:paddingBottom="@dimen/activity_vertical_margin"

android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

app:layout_behavior="@string/appbar_scrolling_view_behavior"

tools:context="com.example.cheatsheet2.MainActivity"

tools:showIn="@layout/activity_main">

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="@string/click_me"

android:id="@+id/button"

android:onClick="onButtonClick"/>

</RelativeLayout>
This XML code belongs in your project’s res/layout/content_main.xml file. You type the boldface code; Android Studio types the rest.

The menu resource file

An action bar (also known as an app bar) appears at the top of the device’s screen. The action bar may contain menu items. In addition, the action bar contains an action overflow icon. When the user clicks the action overflow icon, more menu items may appear. On many devices, the action overflow icon looks like three dots in a vertical line.

A file in your project’s res/menu directory describes the contents of the action bar. This listing contains the file’s code.

<menu 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"

tools:context="com.example.cheatsheet2.MainActivity">

<item

android:id="@+id/action_reset"

android:title="@string/action_reset"

app:showAsAction="never"/>

</menu>

According to this code, the action bar contains only one menu item. But the attribute app:showAsAction="never tells Android not to display the item directly on the action bar. Instead, that item appears only when the user clicks the action overflow icon. In the Java code, the onOptionsItemSelected method says that when the user clicks the menu item, the button’s text reverts to CLICK ME.

In case you’re wondering, some alternatives to app:showAsAction="never" are app:showAsAction="ifRoom" and app:showAsAction="always".

The project’s text strings

The strings.xml file lives in the project’s res/values directory. In the strings.xml file, all the text labels used in the code are defined. (See the following listing.)

<resources>

<string name="app_name">CheatSheet 2</string>

<string name="action_reset">Reset</string>

<string name="been_clicked">I\'VE BEEN CLICKED</string>

<string name="click_me">CLICK ME</string>

</resources>

Elsewhere in the project, the name attributes in this code are used instead of the strings CLICK ME, I’VE BEEN CLICKED, and Reset. For example, the names R.string.click_me and R.string.been_clicked appear in the main activity. And the reference @string/action_reset appears in the menu’s resource file.

A double-quote mark has a special meaning in XML documents. For example, in the strings.xml file, the quotation marks in name="click_me" tell you where the name attribute’s value begins and ends. In the same way, a single quotation mark (‘) has a special meaning in XML. So, in the strings.xml file, you use the combination \' to put an apostrophe in the word I’ve. The combination \' is called an escape sequence. The escape sequence indicates that you want to display an ordinary single quotation mark, with no special meaning intended.