Get $500+ of the best After Effects files, video templates and music for only $20!
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»

Add Comment

Discussion 9 Comments

  1. Yago says:

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

  2. rajibahmed says:

    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 :)

  3. sam says:

    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?

  4. bob says:

    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- ??

  5. bob says:

    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!

  6. Chuck says:

    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.

  7. gigabyte says:

    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.

  8. Tom says:

    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…

  9. R1D2 says:

    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.

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.