Learn Java for Android Challenge: Iteration

Learn Java for Android Challenge: Iteration

Tutorial Details
  • Technology: Java + Android SDK
  • Difficulty: Beginner
  • Estimated Completion Time: 20-30 minutes
This entry is part 6 of 13 in the series Learn Java for Android Development

You’ve read about how iteration works in Java. Test your new skills with this challenge: five progressively difficult exercises that help you solidify your knowledge of the Java programming language and Android development. That’s right, Android too! You may need to refer to other Android tutorials that we’ve published on Mobiletuts+, but if you can complete this challenge successfully you will know you are progressing nicely in your Java and Android SDK understanding.

Setup

To prepare for this challenge, you’ll want to start with a basic Android application. Simply create an Android application within Eclipse and edit its default Activity, specifically the onCreate() method, to test the code from each of these challenges.

If what we’ve just asked of you is already too challenging, we would recommend taking a step back. Start with some of the Android tutorials, such as Introduction to Android Development or Beginning Android: Getting Started with Fortune Crunch. Once you’ve mastered setting up an Android project, return and try these exercises.

Getting Started: Working with String Array Resources

At first, we considered using a simple string array for you to use to complete these iteration challenges:

String aColors[] = {"Red", "Orange", "Yellow", "Green", "Blue", "Indigo", "Violet"};

However, there’s a much better way to store fixed arrays of values in Android: as resources. To create a string array resource, you must first create String resources for each value. Next, create a String Array resource using those String resources as elements. Use the <string-array> tag to combine String resources into an array resource using child <item> tags for each element. For instance, here’s an array of colors inside an Android resource file:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="red">Red</string>
    <string name="orange">Orange</string>
    <string name="yellow">Yellow</string>
    <string name="green">Green</string>
    <string name="blue">Blue</string>
    <string name="indigo">Indigo</string>
    <string name="violet">Violet</string>
    <string-array name="colorsArray">
        <item>@string/red</item>
        <item>@string/orange</item>
        <item>@string/yellow</item>
        <item>@string/green</item>
        <item>@string/blue</item>
        <item>@string/indigo</item>
        <item>@string/violet</item>
    </string-array>
</resources>

To load this array resource in your Activity class, use the getStringArray() method of the Resources object. For instance:

String aColors[] = getResources().getStringArray(R.array.colorsArray);

Challenge #1: Warm-Up Challenge

Now you’re ready to get started. Load the string array from the resources, as discussed above. Then, iterate through the array’s contents using a for() loop. Print each string to the Android LogCat debug log using the Log.v() method.

Extra points if you use the shorthand version of for() loops, discussed in Learn Java for Android Development: Working with Arrays.

Find the answer to this challenge in the challengeOne() method of the downloadable project.

Challenge #2: Stretch Your Skills

Iterate the same array as Challenge #1, but use a different iteration mechanism. For example, use a while() loop instead. Print each string to the Android LogCat debug log using the Log.v() method.

Find the answer to this challenge in the challengeTwo() method of the downloadable project.

Challenge #3: Reverse!

Iterate the same array backwards. Print each string to the Android LogCat debug log using the Log.v() method.

HINT: Challenge #2 can help.

Find the answer to this challenge in the challengeThree() method of the downloadable project.

Challenge #4: It’s All About Character

Next, go back to the for() loop you created in Challenge #1. Update it to print out the individual characters of each String as well. This challenge will require an inner for() loop.

HINT: You can use the toCharArray() method of the String class to retrieve a character array.

The answer to this challenge is in the challengeFour() method of the downloadable project.

Challenge #5: Reflect on How Far You’ve Come

For this final challenge, you’re going to need a bit of understanding about Java reflection. Use reflection to iterate through the declared fields within the android.os.Build class using a for() loop. Print each field name to the Android LogCat debug log using the Log.v() method.

HINT: Our short tutorial on Java reflection will teach you everything you need to know to complete this challenge.

We’ve provided two different solutions for this challenge. The first solution assumes that the package is imported and the compiler knows about the class. The second solution does not make this assumption. These solutions are found in the challengeFiveA() and challengeFiveB() methods of the downloadable project.

Conclusion

Android developers use iteration techniques on a regular basis to solve coding problems. Iteration is frequently used to iterate arrays, data structures like lists, or database content using cursors. Feel free to post your alternative answers (or any questions) in the comments section.

Best of luck!

Series Navigation«Learn Java for Android Development: Reflection BasicsLearn Java for Android Development: Inner Classes»

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://www.mindcookin.com Yago

    I enjoyed this quick challenge, would like to see more like this. It’s very funny!

  • http://d32.com.bd rajibahmed

    Your series is really interesting so please dont stop. Keep up the good work. I was struggling with inner classes because i have less experience in Java. I have seen the use of anonymous inner classes but googled it with Anonymous functions like JavaScript. I could find explanation to that back then … But now have better understanding of Advance Java features
    thanks to you guys and MobilTuts :)

  • http://samgarfield.com sam

    Okay so where do I put the xml resource? Is it in its own file? Does it go in the resources directory? What do I name it? Did I miss this somewhere in one of the previous tutorials?

  • bob

    This is quite frustrating- in the solution there is a reference to Debug tag- and use LogV to output- however there is no reference to the tut to expain how these work. Would appreciate some guidance- ??

  • bob

    Looked at the solution and this challenge seems a bit much for someone who is looking at Java for beginners- This seems to be a common problem with all “beginners books” that they are pitched to high for beginners!

  • Chuck

    I dont usually comment but, i thought i should here. Ive been telling ppl for a while now that i feel like theres alot of tuts that can teach ppl the basics of android but, from there youre stuck in this awkward stage where you can read code and follow tuts but, you cant quite excute a idea from scratch to app. Exercises like this are amazing bc they force ppl to put what there reading about to use. please keep them coming.

  • gigabyte

    This tutorials have been awesome. I’ve tried to go through other Android tutorial but they expect you to know Java well, and most Java tutorials I’ve looked at the code doesn’t work for Android. I’ve been programming for years in languages like Perl, php, Javascript, etc; but Java is foreign to me. I’d like to start writing Android apps and this the first one that I’ve seen that I’m finally starting to catch on to things.

    Thanks a lot.

  • Tom

    I’ve found this tutorial to be a giant leap ahead from the previous ones, which were all fairly linear and took things step by step. Where do I put the getStringArray() method? I’ve inserted it into my Activity class and I’m getting a “array cannot be resolved or is not a field” error.

    I have an automatically generated R class in my project, but in your example we’re calling on array and colorsArray in this class, and they’re not in there. Are we meant to put them in the R class? If so, how?

    You lost me at this tutorial…

  • R1D2

    I cant do this excercise because the totorials dont explain how to use the Log.v command, particularly, how do we view what we logged? frustrating end to an otherwise great guide.

    • Alex

      I downloaded the source code and looked at the solution. For people who couldn’t figure out how the Log.v works, it’s in the source code. But I’m not seeing my colors in the Log.Cat. And that’s not in the source code :)) so what now? the code isn’t showing any errors but does it really work if it doesn’t print to the Cat.Log ?

      • Alex

        no matter. I figured it out. If you have more than one project in the explorer, make sure you’re looking at the proper filter. At first all were empty for me too, but after a few runs, the Log.Cat got filled up, and now I have all my colours :)

  • 43WDC.Sirius

    woa! Where can i find the updated series for this one??
    I’d really like to try the Exercises too!. But it throws errors like the code:

    String aColors[] = getResources().getStringArray(R.array.colorsArray);

    couldnt find the right syntax for the getStringArray(). . please sir. and other concerned developers out there . . :(

  • mohammed el-sayeh

    // print all strings using for loop
    String[] colorS = getResources().getStringArray(R.array.colorsArray);
    for (String clr : colorS) {
    Log.v(“For”, clr);
    // print characters of each string
    for (char c : clr.toCharArray()) {
    Log.v(“char”, c + “”);
    }
    }

    String[] arr = getResources().getStringArray(R.array.colorsArray);
    // using while
    int i = 0;
    while (i 0);

    // print the name of each field in android.os.Build Class (using java reflection)
    try {
    Class classToCheck = Class.forName(“android.os.Build”);
    Field[] fields = classToCheck.getDeclaredFields();
    for (Field field : fields) {
    Log.v(“Field”, field.getName());
    }
    } catch (ClassNotFoundException e) {
    e.printStackTrace();
    }