CategoryTutorial

Simplified Logging in Android

Logging is one of the important tools for debugging an application.

When logging in Android, one usually writes code like

public class LoggingSample {

    public static final String TAG = "LoggingSample";
    ... 

    public void loggingMethod() {   

    final String formattedTestString = "first argument = %s, " + 
             "second argument = %s";
    final String firstArgument = "abc";
    final Object secondArgument = new  Object() {
        public String toString() {
            return "123";
        }
    };
    Log.d(TAG, "loggingMethod(): " + 
           String.format(formattedTestString, firstArgument,
           secondArgument));

    }
}

This then results in an output like

D/ LoggingSample: loggingMethod(): first argument = abc, second argument = 123

We need to add a tag and many times, in order to reproduce procedures, the name of the calling method. Not much of a deal, but since logging is done frequently it is often repeated

Since we don’t like repetitions, we decided to make it a little easier. Instead of the above, we now type

    L.d(formattedTestString, firstArgument, secondArgument);

To get an output like

D/LoggingSample:26(18510): onCreate(): first argument = abc, second argument = 123

What we get is the calling class’s name and the line number as a tag, the calling methods name plus the formatted string as a message.

 

If you are interested in this type of logging, you can now git clone the ANDLABS Android Utils and add them as a library project.

 

What do you think? How do you use logging? Please share your thoughts in the comments.

Getting started with the Universal Tween Engine

This is a guest post by Alexander Fröhlich. Alexander is a freelance developer and is supporting ANDLABS at its libgdx-based development. 

If you are not familiar with libgdx yet, please check out the first part of this series, the Getting started with libgdx-guide.

 

1 Tweening?

“Tweening” in games is the process of creating intermediate states and thus frames between two or more given states.

Example (Sprite Translation):
The most simple example would be moving a sprite or image from one x1, y1 position to another x2, y2 position on the screen.

Yet, as you might already suspect, this “Universal Tween Engine” is capable of manipulating not only x, y coordinates for sprite objects…. no, this cross-platform-engine written entirely in java language lets you tween every property of any object given that it has its getter/setter methods attached.

In this tutorial I will show you how this comes in handy for game developers when building ingame hints or tutorials for their game.

The following sample code illustrates basic use and setup of the universal tween engine in a libgdx code project.

2 Ingame Tutorial Tweening

First of all, declare your tweenManager instance. The tweenManager lets you keep track and manage all your tweens (i.e. tweening, tween actions and so on)

public class MyGame implements ApplicationListener {

    // Only one manager is needed, like a 
    // libgdx Spritebatch (MyGame.java)

    private static TweenManager tweenManager;

}

Instantiate the manager inside create() of your libgdx lifecycle:

Register an accessor class, which is the key binding between the manager and the object to be tweened. Here this will be the TutorMessage class. (see below).
So after calling registerAccessor every single object of class TutorMessage we create can be tweened by the TweenManager.

@Override
public void create() {
    setTweenManager(new TweenManager());
    Tween.setCombinedAttributesLimit(4);// default is 3, yet
                                        // for rgba color setting          
                                        //we need to raise to 4! 
    Tween.registerAccessor(TutorMessage.class, new 
                             TutorMessageAccessor()); 

}

The TutorMessage’s are the internal game objects for this sample which hold the position, scale and color message attributes.

public class TutorMessage {

    private String message; // string objects can not be tweened
    private float x;
    private float y;
    private Color color;
    private float scale;

}

To tween these message properties and make them accessible by the manager we have to declare how getting and setting every single attribute works.

Getter/Setter
So we define 3 sections (POS_XY, SCALE, COLOR) that process the current float[] values, handled over by the manager during runtime when tweening is active.

Of course same applies for the setters.

public class TutorMessageAccessor implements TweenAccessor<TutorMessage> {

    public static final int POS_XY = 1;
    public static final int SCALE = 2
    public static final int COLOR = 3;

    @Override
    public int getValues(TutorMessage target, int tweenType, 
                           float[] returnValues) {
        switch (tweenType) {
            case POS_XY:
                returnValues[0] = target.getX();
                returnValues[1] = target.getY();
                return 2;

            case SCALE:
                returnValues[0] = target.getScale();
                return 1;

            case COLOR:
                returnValues[0] = target.getColor().r;
                returnValues[1] = target.getColor().g;
                returnValues[2] = target.getColor().b;
                returnValues[3] = target.getColor().a;
                return 4;

            default: 
                assert false; 
                return -1;
        }
    }

    @Override
    public void setValues(TutorMessage target, int tweenType, 
                            float[] newValues) {
        switch (tweenType) {
            case POS_XY: 
                target.setPosition(newValues[0], newValues[1]); 
                break;

            case SCALE: 
                target.setScale(newValues[0]); 
                break;

            case COLOR:
                Color c = target.getColor();
                c.set(newValues[0], newValues[1], newValues[2], 
                        newValues[3]);
                target.setColor(c);
                break;

            default: 
                assert false;
        }
    }
}

Having bind our TutorMessage class to the TweenManager we can now integrate it into the game.
Remember? We want to provide a kind of ingame tutorial system. So every time our user should see an animated on-screen help, we call the now defined method. The tweenHelpingHand method takes the parameter targetX, targetY that indicate the position where the helping hand (sprite) and its bound message (bitmapfont) should move to.

Then we say Tween
  .to (
      – TutorMessage currentTm ( the message to be moved )
      – int TutorMessageAccessor.POS_XY (constant to select which property should be tweened)
      – float 3f (total tweening duration)
  )
  .target (
    – targetX, targetY ( the final screen position of our tweened message )
  )
  .ease (
    – TweenEquations.easeOutCirc ( one possible interpolation pattern – i.e. moving pattern here)
  )
  .start (
    – MyGame.getTweenManager()  ( binds this tween to the manager )
  )

private void tweenHelpingHand(int targetX, int targetY) {

    // kill current tween - or pre-existing
    MyGame.getTweenManager().killTarget(currentTm);

    // move
    Tween.to(currentTm, TutorMessageAccessor.POS_XY, 3f)
         .target(targetX, targetY)
         .ease(TweenEquations.easeOutCirc)
         .start(MyGame.getTweenManager());

    // colorize
    Tween.to(currentTm, TutorMessageAccessor.COLOR, 3f)
         .target(1f, 1f, 1f, 1f)
         .ease(TweenEquations.easeOutCirc)
         .start(MyGame.getTweenManager());

}

Finally we have to call update inside the libgdx render() method to have the started Tween be updated constantly.

MyGame.getTweenManager().update(delta);

Here you go!
Enjoy this very powerful any easy to use tweening library.

Combining Scene2d animations and Tweening is also possible. You just have to write the ActorAccessor binding class and provide access (getter/setter) to its properties.
Like with Scene2d actions, the universal tween engine also allows sequencing of multiple tweens!

 

If you have any questions or suggestions, please leave a comment.

Introduction to AndEngine – Getting the code

In this series I will tell you how to use one of my favorite Android 2D Game Engines, AndEngine. We will go step by step through the processes, starting at simply getting the code, continuing with drawing sprites, using cameras, physics and so on.

AndEngine was started by Nicolas Gramlich as part of his Bachelor’s thesis in the beginning of 2010. It is an engine that provides lots of powerful features while hiding more advanced things like Open GL calls from the developer. It provides lots of extensions like a  Robotium extension, a Box2D extension, which is mostly written and maintained by badlogicgames‘ Mario Zechner for his libGDX-project, a SVG extension or a TMX tiled maps extension.

It has been used in various featured games like Greedy Spiders, Noogra Nuts or Zynga’s Dream Zoo.

Let’s get started.

 

Getting the code

At the very beginning you’ll need to download the most recent version of AndEngine. To do that, open your console, go to the directory of your choice and do a git clone of the engine by typing

git clone git://github.com/nicolasgramlich/AndEngine.git

That’s all. You now have a powerful game engine, ready to be used on your computer or mobile device.

Now here’s a story: When AndEngine was written, the author had to make a choice: did he want to write lots of useful code or lots of useful documentation? He chose the more fun part and that’s why AndEngine provides little to no documentation, which is one of its most frequent points of criticism. However, the source is all open, you can read it, change it, do whatever you like with it. There are the AndEngine forums and Nicolas tries to write the code in a way that it’s documenting itself.

In order to provide the developers an idea of what AndEngine can do, the AndEngine samples were created. You can get them by also cloning the git repository:

git clone git://github.com/nicolasgramlich/AndEngineExamples.git

As you can now see there are a lot of dependencies to the different extensions. Go ahead and clone them:

git clone git://github.com/nicolasgramlich/AndEngineAugmentedRealityExtension.git
git clone git://github.com/nicolasgramlich/AndEngineLiveWallpaperExtension.git
git clone git://github.com/nicolasgramlich/AndEngineMODPlayerExtension.git
git clone https://github.com/nicolasgramlich/AndEngineMultiplayerExtension
git clone https://github.com/nicolasgramlich/AndEnginePhysicsBox2DExtension
git clone https://github.com/nicolasgramlich/AndEngineSVGTextureRegionExtension
git clone https://github.com/nicolasgramlich/AndEngineTexturePackerExtension
git clone https://github.com/nicolasgramlich/AndEngineTMXTiledMapExtension

Now you have a lot of code. Import them into your IDE of choice. Your workspace should now look something like this:

Let’s start a look at the examples. Connect your device or start an emulator with GPU emulation and run the AndEngineExamples on it.

AndEngine physics example

AndEngine physics example

What you will find is an overview over AndEngine’s many features.

There are two important branches of AndEngine: The GLES2-branch and the GLES2-AnchorCenter branch. Since the latter will become the main branch soon, it is recommended to pull its code too. To do so, just go into each of your AndEngine-projects using your shell and execute

git pull origin GLES2-AnchorCenter

You might want to switch to this branch now by executing

git checkout -b GLES2-AnchorCenter origin/GLES2-AnchorCenter

Now take your time to play, take a look into the code and look forward to the next part of this series in which we will go through the basic parts of the engine.

 

If you are having problems compiling any of AndEngine’s code or issues cloning the repositories, please post a comment.

Two simple ways to make your users aware of incorrect input

Did you ever enter a wrong password and got an AlertDialog telling you that you entered something wrong? You probably did and you probably also noticed that this alert dialog most likely takes one more click to continue, a click that could be saved. One way to avoid the AlertDialog are Toasts. Here are two nice but rarely used other ways to tell your users that they should enter something different.

Setup

Let’s assume we have an EditText which we use in our UI.
EditText mEditText ;
//...
mEditText  = (EditText ) findViewById(R.id.myEditText );

Furthermore we have a method showError() which we call when the EditText contains invalid data.

1 Shake

A nice way to show the user that, for example, an entered password was incorrect is to shake the EditText. Please note that I took this code from the official ApiDemos and modified it slightly.

First, we have to define our shake animation. Go to your res folder, create the subfolder anim and place a file shake.xml in it. In this file, create a translation like this:
< translate xmlns:android="http://schemas.android.com/apk/res/android" android:fromXDelta="0%" android:toXDelta="5%" android:duration="1000" android:interpolator="@anim/cycle_7" />

TranslateAnimations let us move views ond the x or y axis of our screen. Since we want to shake it from left to right, we only apply the translation on the x axis. We move it from zero percent of the view’s width to five percent of the view’s width and let the translation last one second (1000 ms). Furthermore, we use the interpolator cylce_7 wich is placed in anim/cycle_7.xml and looks like the following:
< cycleInterpolator xmlns:android="http://schemas.android.com/apk/res/android" android:cycles="7" />

It’s a simple CycleInterpolator. This kind of interpolators express the number of repetitions an animation should do. In our case, we repeat the animation seven times.

Now we only need to apply our shake animation to our EditText every time something incorrect is entered. We can do it like this:

private void showError() {
Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
mEditText.startAnimation(shake);
}

That’s it. Super easy, super smooth integration into the UI.

2 SetError

This is my personal favourite. It is the setError()-method which comes out of the box with the EditText view. When calling this method, the right hand compount drawable of the will be set to the error icon. When the EditText also has focus, the text you gave to setError() will be shown in a popup. If you don’t like the default error icon, you can also use setError(CharSequence error, Drawable icon) to set your own icon. The routine to show errors can then look like this:

private void showError() {
mEditText.setError("Password and username didn't match");
}

Which will result in errors shown like this:

setError() on ICS

setError() on ICS

Which looks good, catches the user’s attention and doesn’t need any extra clicks to disappear.

Conclusion

Showing errors without interrupting the user flow can be accomplished easily on the Android plattform. For even more attention by the user, the two methods mentioned can also be combined.

 

Please feel free to share your methods of showing error messages in the comments.

© 2024 Droid-Blog

Theme by Anders NorenUp ↑