Home

10 Ways to Avoid Mistakes When Programming Your Android App with Java

|
|  Updated:  
2017-01-13 14:51:58
Java Essentials For Dummies
Explore Book
Buy On Amazon
Everyone makes mistakes. It’s a fact of life. However, if you heed the advice here, it doesn’t have to be a fact of your Java programming.

Putting capital letters where they belong

Java is a case-sensitive language, so you really have to mind your ps and qs — along with every other letter of the alphabet. Here are some concepts to keep in mind as you create Java programs:
  • Java’s keywords are all completely lowercase. For instance, in a Java if statement, the word if can’t be If or IF.
  • When you use names from Android's Application Programming Interface (API), the case of the names has to match what appears in the API.
  • The names you make up yourself must be capitalized the same way throughout the entire program. If you declare a myAccount variable, you can’t refer to it as MyAccount, myaccount, or Myaccount. If you capitalize the variable name two different ways, Java thinks you’re referring to two completely different variables.

Breaking out of a switch statement

If you don’t break out of a switch statement, you get fall-through. For instance, if the value of roll is 7, the following code prints all three words — win, continue, and lose:

switch (roll) {

case 7:

textView.setText("win");

case 10:

textView.setText("continue");

case 12:

textView.setText("lose");

}

Comparing values with a double equal sign

When you compare two values, you use a double equal sign. The line

if (inputNumber == randomNumber)

is correct, but the line

if (inputNumber = randomNumber)

is not correct.

Adding listeners to handle events

You want to know when the user clicks a widget, when an animation ends, or when something else happens, so you create listeners:

public class MainActivity extends Activity

<strong>implements OnClickListener, AnimationListener</strong> {

public void onClick(View view) {

}

public void onAnimationEnd(Animation animation) {

}

When you create listeners, you must remember to set the listeners:

ImageView widget = new ImageView(this);

widget.<strong>setOnClickListener</strong>(this);

AlphaAnimation animation = new AlphaAnimation(0.0F, 1.0F);

animation.<strong>setAnimationListener</strong>(this);

If you forget the call to setOnClickListener, nothing happens when you click the widget. Clicking the widget harder a second time doesn’t help.

Defining the required constructors

When you define a constructor with parameters, as in

public Temperature(double number)

Java no longer creates a default parameterless constructor for you. In other words, you can no longer call

Temperature roomTemp = new Temperature();

unless you explicitly define your own parameterless Temperature constructor.

Fixing nonstatic references

If you try to compile the following code, you get an error message:

class WillNotWork {

String greeting = "Hello";

static void show() {

textView.setText(greeting);

}

}

You get an error message because the show method is static, but greeting isn’t static.

Staying within bounds in an array

When you declare an array with ten components, the components have indexes 0 through 9. In other words, if you declare

int guests[] = new int[10];

you can refer to the guests array’s components by writing guests[0], guests[1], and so on, all the way up to guests[9]. You can’t write guests[10], because the guests array has no component with index 10.

Anticipating null pointers

A NullPointerException comes about when you call a method on an expression that has no “legitimate” value. Here’s an example:

public class MainActivity extends AppCompatActivity {

TextView textView;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

<strong> // You forget the findViewById line.</strong>

}

public void onButtonClick(View view) {

textView.setText("Hello");

}

}

In Java, a reference type variable that doesn't point to anything has the value null. So in this example, the textView variable's value is null.

You can't call the setText method on the null value. For that matter, you can't call any method on the null value. When Java tries to execute textView.setText("Hello"), the app crashes. The user sees an Application has stopped message. If you're testing the app using Android Studio, you see NullPointerException in the Logcat pane.

To avoid this kind of calamity, think twice about any method call in your code. If the expression before the dot can possibly be null, add exception-handling code to your program:

public void onButtonClick(View view) {

try {

textView.setText("Hello");

} catch(NullPointerException e) {

Toast.makeText(this, "The app has recovered from an error.",

Toast.LENGTH_LONG).show();

}

}

Using permissions

Some apps require explicit permissions. For example, some apps talk to Twitter's servers over the Internet. This doesn't work unless you add a <uses-permission> element to the app's AndroidManifest.xml file:

<uses-permission android:name= "android.permission.INTERNET">

If you forget to add the <uses-permission> element to your AndroidManifest.xml file, the app can't communicate with Twitter's servers. The app fails without displaying a useful error message. Too bad!

The Activity Not Found

If you create a second activity for your app, you must add a new <activity> element in the app’s AndroidManifest.xml file. The element can be as simple as

<activity android:name=".MySecondActivity">

but, in most cases, the element is a bit more complicated.

If you don’t add this <activity> element, Android can't find the MySecondActivity class, even though the MySecondAcitivity.java file is in the app's project directory. Your app crashes with an ActivityNotFoundException.

And that makes all the difference.

About This Article

This article is from the book: 

About the book author: