Thursday, August 21, 2014

10 Eclipse Navigation Shortcuts Every Java Programmer Should Know

Man, I’m such an impatient guy. I cringe whenever I see somebody squint and frown, looking for a JSP file in Eclipse by browsing painfully through the gazillion JSPs in multiple folders in the Package Explorer. I squirm whenever I see somebody looking for a Java class by clicking through packages, one by one, backtracking if it’s the wrong package, and so on, until he sees the correct Java class.
I mean, any resource in the workspace is literally seconds away. Ditto to classes (and interfaces, and members, and so on). Why waste time and brain cycles to wade through countless lines in countless files? I thought that every Eclipse user knows this, in fact, if you’re reading this, most probably you already know this too. But thousands of Eclipse JDT users who never bother to read tech blogs in all probability will also never bother to find out what Eclipse can do for them. And it’s a pity, really, because they’re really missing out a lot. So maybe if you know one, you can forward this to them or something. Make them more productive or something, ya know. 30 seconds saved for every file can add up to really a lot!
So without further ado, let’s say you want to:
  • Open any file quickly without browsing for it in the Package ExplorerCtrl + Shift + R. This shortcut opens a dialog box that accepts the name of the file you’re looking for. It even accepts wildcard characters, yo. Typing *-conversion.properties will give you the list of all files that ends with -conversion.properties. So everytime you want to open a file–stop that hand from going to the mouse, and press Ctrl + Shift + R instead!
Opening a resource in Eclipse
  • Open a type (e.g.: a class, an interface) without clicking through interminable list of packagesCtrl + Shift + T. If what you want is a Java type, this shortcut will do the trick. Unlike the previous shortcut, this even works when you don’t have the Java source file in your workspace (e.g.: when you’re opening a type from the JDK).
Opening a type in Eclipse
  • Go directly to a member (method, variable) of a huge class file, especially when a lot of methods are named similarlyCtrl + O. Say, you’re browsing through a file which has 500+ lines of code. How do you look for a method? Don’t use Ctrl + F and then type the method name. Use Ctrl + O, which gives you a list of candidates that match what you’ve typed so far. Select the member you want using the arrow keys, and press Enter.(Alternatively, if you just want to jump from one member to the next (or previous), you can use Ctrl + Shift + ↓ or Ctrl + Shift + ↑, respectively.) UPDATE: As Nick pointed out in the comments section, pressing Ctrl + O again shows the inherited members. Thanks Nick! :)
Browse Member
ctrl_o_2.jpg
  • Go to line number N in the source fileCtrl + L, enter line number. Of course if the stack trace is in the Eclipse console, you can just click the hyperlink. But if it’s in a log file or something, just use this shortcut to go to the line in a jiffy.
Go to a line number
  • Go to the last edit locationCtrl + Q for . If you have a big file, it’s annoying to jump from one location in line 1000+ to 2000+ only to realize after looking at line 2017 that you’ve made a mistake in that location near line 1000+ just now. This shortcut brings you right to where you last edited a file. Very handy in a big file. Gone are the days of “let’s see… where did I edit it again… nope, nope… ah there it is”. (This even works when you’re already looking at a different file.)
  • Go to a supertype/subtypeCtrl + T. Before I found this, if I want to go to the superclass of a class, I’d go the the very top of the file, hover my mouse over its superclass, hold Ctrl, and click. Disgusting. Now I just press Ctrl + T and I get this dialog below, which toggles between supertypes and subtypes when you press Ctrl + T again.
Subtype hierarchy view
Supertype hierarchy view
  • Go to other open editorsCtrl + E. I know you can cycle through the editors using Ctrl + F6 as well, but I prefer Ctrl + E because Ctrl + F6 has this annoying behaviour of requiring you to keep the Ctrl key down, and the distance between Ctrl and F6 is so far I have to twist my left hand to do that. Just press Ctrl + E, and either use the arrow buttons, or type the name of the file you’re editing.
Open editor
  • Move to one problem (i.e.: error, warning) to the next (or previous) in a fileCtrl + . for next, and Ctrl + , for previous problem. No need to lift your hands off the keyboard to click on that red or yellow stripe.
  • Hop back and forth through the files you have visitedAlt + ←and Alt + →, respectively. I have to admit I don’t find myself using these two often, though.
  • Go to a type declarationF3. Alternatively, you can hold Ctrl down and click the hyperlinked variable or class or whatever it is the declaration of which you want to see–but why lift your hand off the keyboard? Just press F3 and Eclipse will bring you to the declaration of whatever is at the cursor at that moment.
OK, that’s it for this post. There are tons of other Eclipse shortcuts not covered by this article. To see the whole list, just open up your Eclipse (I’m assuming Eclipse 3.2 here–in older or more recent versions this may differ slightly), go to Help → Help Contents → Java Development User Guide → Reference → Menus and Actions. The whole motherload is there, from generating comments, correcting indentations, surrounding with, and so on.
The point I’m trying to get across is: Eclipse has a LOT of shortcuts to make things real easy for you. Java (or heck, any software) development is hard. We shouldn’t make it harder on ourselves by fighting our tools! Let our tools help us as much as possible, so we all can go back on the dot and spend more time with our family, lovers, or whatever it is we want to spend more time on. There’s no honour in working hard inefficiently. Only disgrace.

Sunday, August 10, 2014

Three ways to take a screenshot on a Mac

You are probably familiar with the first two keyboard shortcuts, but the third might be the most useful of the bunch.
I take a lot of screenshots on my MacBook Pro. I use the Command-Shift-4 method frequently to take a screenshot of a selection of my desktop, but there is a better way if you want to take a screenshot of an open window.


1. Command-Shift-3
It captures a screenshot of your entire screen.
2. Command-Shift-4
It turns the cursor into a crosshair, which you can drag to select a portion of your screen to capture. Release the mouse button or trackpad to take the shot.
3. Command-Shift-4, then space bar, then click on a window
Hitting the space bar turns the crosshair into a little camera icon, which you can move over any open window. Click on your desired window to take a screenshot of it. A screenshot captured by this method features a white border around the window with a bit of a drop shadow.

Friday, August 8, 2014

Google Play Game Services and Admob in LibGDX



Google Play Game Services offers cross platform social leaderboards, achievements, and much more (realtime multiplayer, cloud saves, anti-piracy...). 
AdMob has been rebuilt, leveraging the best of Google's ad platforms. It's designed for app developers, with an intuitive UI to help you start earning from your app quickly, create campaigns in minutes to acquire new users, and gain insights into your app's performance. 
I've started implementing google play game services leaderboards, achievements and google AdMob in my LibGDX Android Games, and the purpose of this blog article is to walk through the process so you can do the same!

  • I've published an example project on Google Play check it out!
  • The example project is freely available on GitHub check that out too!

Continue reading after the jump to find out how to add these features to your own games!


Development environment:


Android studio 0.8.2
Android SDK 20
LibGDX 1.2.0
Other dependence library, please check the build.gradle


Create project:



  • Execute the jar by double clicking it or from the command line via java -jar gdx-setup.jar
    • Specify your project's configuration (Configuration Panel)
    • Specify the libgdx stable/nightly release zip file or press one of the buttons to download the latest stable/nightly release (Library Selection Panel).
    • Hit the "Generate projects" button (Generation Panel)
In this tutorial,  I select Android and iOS, freetype and Box2d.  The project directory:



Import the project into Android studio


File->Import Project,

There is one Gradle version error,
Error:The project is using an unsupported version of the Android Gradle plug-in (0.10.4)
<a href="fixGradleElements">Fix plug-in version and re-import project</a>

Change the " classpath 'com.android.tools.build:gradle:0.10+' " to "classpath 'com.android.tools.build:gradle:0.12.+'" in the build.gradle

Now, you can run the android application in the Android studio.



Set up the game in the Google Play Developer Console

You can follow Google instruction to set up the game:

Need to know these  things, we need to use them in the project.

1, Game application ID

2, Achievements ID

3, Leaderborads ID


4, Create a linked application, certificate fingerprint

You need input the correct certificate fingerprint, if you want test the debug apk, use the debug keystore. Don't forget to update to release certificate fingerprint when you release the apk to Google Play.
Open a terminal and run the the Keytool utility to get the SHA1 fingerprint of the certificate. You should get both the release and debug certificate fingerprints.
To get the release certificate fingerprint:
keytool -exportcert \
-alias <your-key-name> \
-keystore <path-to-production-keystore> \
-list -v
To get the debug certificate fingerprint:
keytool -exportcert \
-alias androiddebugkey \
-keystore <path-to-debug-keystore> \
-list -v










5, Add test user

Add the account you login on the test device into the testing user list.

Setup AdMob


You can follow this instruction to create app and adunit.
https://support.google.com/admob/v2/topic/2745286?hl=en&ref_topic=2792286




LibGDX App Setup in Android Studio



1, Add Google play service dependence

Open the build.gradle, add         
compile 'com.google.android.gms:play-services:5.0.77'



2, Modify the  AndroidManifest.xml

a. Add Permission:
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

b. Add meta-data
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <meta-data android:name="com.google.android.gms.games.APP_ID" android:value="@string/app_id" />

c. Add AdActivity for AdMob
        <activity
            android:name="com.google.android.gms.ads.AdActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" />

3. Add Game App Id in the strings.xml
    <string name="app_id">794485152673</string>


4. Add Admob ad in the game.

Check the AndroidLauncher.java for detail.

a, Create the ad view
    private AdView createAdView() {
        adView = new AdView(this);
        adView.setAdSize(AdSize.BANNER);
        adView.setAdUnitId(AD_UNIT_ID);
        //adView.setId(12345); // this is an arbitrary id, allows for relative positioning in createGameView()
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
        params.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
        adView.setLayoutParams(params);
        adView.setBackgroundColor(Color.BLACK);
        return adView;
    }
b. Start request the ad

        AdRequest adRequest = new AdRequest.Builder().build();
        adView.loadAd(adRequest);

5. Add game service

a. Add GameHelper.java and GameHelperUtils.java into android project. These are game service wrapped class.

b. Add game service interface in the core project. Use this interface to communicate between game and application. 
public interface ActionResolver {
public boolean getSignedInGPGS();
public void loginGPGS();
public void submitScoreGPGS(int score,String id);
public void unlockAchievementGPGS(String achievementId);
public void getLeaderboardGPGS(String id);
public void getAchievementsGPGS();
}
Then implement the interface in the application.
public class AndroidLauncher extends AndroidApplication implements GameHelper.GameHelperListener, ActionResolver {

....
   @Override
    public boolean getSignedInGPGS() {
        return gameHelper.isSignedIn();
    }

    @Override
    public void loginGPGS() {
        try {
            runOnUiThread(new Runnable(){
                public void run() {
                    gameHelper.beginUserInitiatedSignIn();
                }
            });
        } catch (final Exception ex) {
        }
    }

    @Override
    public void submitScoreGPGS(int score,String id) {
        Games.Leaderboards.submitScore(gameHelper.getApiClient(), id, score);

    }

    @Override
    public void unlockAchievementGPGS(String achievementId) {
        Games.Achievements.unlock(gameHelper.getApiClient(), achievementId);
    }

    @Override
    public void getLeaderboardGPGS(String id) {
        if (gameHelper.isSignedIn()) {
            startActivityForResult(Games.Leaderboards.getLeaderboardIntent(gameHelper.getApiClient(), id), 100);
        }
        else if (!gameHelper.isConnecting()) {
            loginGPGS();
        }
    }

    @Override
    public void getAchievementsGPGS() {
        if (gameHelper.isSignedIn()) {
            startActivityForResult(Games.Achievements.getAchievementsIntent(gameHelper.getApiClient()), 101);
        }
        else if (!gameHelper.isConnecting()) {
            loginGPGS();
        }

    }
....
}

c. Call the game service interface method in the game, report the score and unlock the achievement

    private void gameOver() {
        gameEnd = true;
        winGameOver.setVisible(true);

        if (!game.actionResolver.getSignedInGPGS())
            game.actionResolver.loginGPGS();
        else {
            int bestscore = GamePreferences.instance.getBestScore();
            game.actionResolver.submitScoreGPGS(bestscore, GamePreferences.instance.getLeaderboardid());

            String achid = null;
            //
            if (bestscore > 10) {
                achid = "CgkIobeF2I8XEAIQCA";
            } else if (bestscore > 50) {
                achid = "CgkIobeF2I8XEAIQCQ";

            } else if (bestscore > 100) {
                achid = "CgkIobeF2I8XEAIQCg";

            } else if (bestscore > 150) {
                achid = "CgkIobeF2I8XEAIQCw";

            } else if (bestscore > 200) {
                achid = "CgkIobeF2I8XEAIQDA";
            }
            if (achid != null)
                game.actionResolver.unlockAchievementGPGS(achid);

        }
    }

That's all there is to it! Now all you need to do is build your apk,  drop the apk on your device, install, and play :)