Using Cursor Adapters on Google Glass CardScrollView

Overview

Out of the box CardScrollView in the Google Glass GDK will only allow adapters of type CardScrollAdapter to be set on them. So I am going to share with you two custom classes that allow you to use a CursorAdapter on any of your CardScrollViews.

Note these are exact reuses of the CursorAdapter that is used in the standard Android SDK so I am not reinventing the wheel here. All I did was tweak them to allow for use with the GDK CardScrollView.

Code

You will need to add these two new classes to your project. Both CardCursorAdapter and CursorFilter. Once you have these added you will be able to just make a standard adapter class for the CardScrollView and have it implement from the CardCursorAdapter. Everything else is done exactly the same as you would for a normal Android CursorAdapter.

Gist Code

What's New From Microsoft's //Build/ 2015 (includes code)

Overview

Starting on the 29th Microsoft kicked off //Build/ 2015. For developers that watched at home and attended the event, we expected huge news about Hololens and Windows 10.

What we got? So much more.

Windows Phone

Lets start with what new things we have for Windows Phone. The biggest announcement was that Microsoft will now support you bring over Objective C (from your iOS apps) and Java (from your Android apps). This means that if you have an iOS or Android app you can bring it over to Windows Phone while changing very little amount of code. The best example they gave was Candy Crush by King. That is an iOS app brought over to Windows Phone.

For iOS you can literally pull the iOS project into Visual Studio, and with a few tweaks should be able to get it fully running without a huge refactoring.

For Android you apparently don’t even have to bring it into Visual Studio. You are supposed to be able to just build it for Windows Phone from Android Studio (though I didn’t see anything more about it).

Finally we got to see a deep dive into what to expect from Windows 10 on the phone. One of the coolest things about this is Continuum. This allows you to plug your phone into a monitor and have a fully functional computer at your disposal. With Universal Apps, this allows the App to fully scale to the new screen without issue and work just like it would on a standard desktop. This greatly changes the game because in some places the only smart devices people have are phones.

Hololens

When Microsoft showed off Hololens at the beginning of the year, a lot of people where skeptical. Their first reactions where somewhere along the lines of “Yeah, okay. That video is totally fake.” However, when Hololens entered the stage this week, it blew everyone away. Not only were they able to deliver on what they had originally showed off. They went even farther. Guests from different fields took stage to show off what they have been able to accomplish with this new device. We had Makers, Doctor, and Architects, and that is only the beginning.

After that they went on to tell us about development for Hololens. They showed us demos of how we can bring over applications that we have made for other platforms like it was nothing. Universal Applications have the ability to make things for Windows Phone, TV, Xbox, Desktop, Tablets, and Hololens all with one project.

They even went one last step. They brought a couple hundred of them to //Build/ to let developers both try them, and create an application for them.

Visual Studio Code

The first thing that Microsoft pushed out was something called Visual Studio Code. This is a light weight editor for use on Mac, Linux, and Windows.

Yes, you heard that right.

This editor is built on the same platform that other popular editors are built on top of. Like Github’s Atom editor. What sets it apart though is that they brought some of the power from Visual Studio with it. Intellisense is extremely good, and you can deploy and debug code directly from the editor. The supported deployable code bases at the moment are ASP.Net and Node.js but they plan on adding much more. We even get Gulp tasks, Git integration, and more!

You also read that correctly as well. Microsoft has released an editor with Visual Studio’s Roslyn built into it for both Mac and Linux. This is just a stepping stone to their greater vision of allowing any kind of development on all platforms.

Check it out here: Get Visual Studio Code!

Visual Studio

Microsoft also showed off a new Visual Studio and Blend as well. Coming with Visual Studio 2015 is their new open source compiler Roslyn, along with a whole new IDE. For people that have been using Visual Studio for years, it doesn’t look to new, but they built it from the ground up and added LOADS of new features. Unfortunately I can’t cover all of them, but I can hit some of the big ones.

First is the debugger. You are now able to edit code on the fly while you are debugging. No more of that purple line that makes you recompile and run if you change something. It even supports writing something then backing it up and running it again. Crazy right?! It gets better. You can also now use full lambda expressions in both the immediates window, and in your watch list.

They moved on to then show off some of the new renaming systems. When you do a rename you no longer have to deal with that annoying pop-up window, you can just do it inline without having to leave your keyboard. They even went a step farther to automatically look for conflicts and try to help you solve them. Renaming a new variable to the same name of a property in your object? Oh, that is easy to fix we can just add a this. in front of the old use of that name.

That brings me to error handling. There where a huge amount of error handling changes that they showed off, but in general ctrl + . is your best friend. It can do way more for you than it ever could.

Another big announcement was from the game section. Visual Studio now has an offical extension that allows you to create Minecraft Mods! Yup, Minecraft Mods. Instead of having to use that dreadfully awful Eclipse you can use these custom project types with amazing intellisense and some sdks to help you get started on your very first or most advanced mod! On top of that you can even debug and run it directly from Visual Studio. How cool is that?! You can find the extension here: Get Minecraft Extension!

We also finally have an offical Github Extension directly built into Visual Studio! This is part of the Team explorer and bring full support for handling, cloning, and working with all of you github repos.

Finally, They announced that they are partnering with Docker to bring offical Docker support to Visual Studio. You can now install the extension and you can build and publish ASP.Net v5 web or console apps directly to a container running on a Linux VM. You can find this extension here: Get Docker Extension

C# and XAML

With .Net 6 they aren’t going to be changing so much that it will cause us to relearn things all over again. Such a relief right? They even made some quality of life changes to help make our lives easier. Keep in mind these are just a few of the big ones, there are so many more that I won’t cover.

One huge one is that they are working on bring XAML debugging and binding debugging either in this release or the next one.

They made some nice changes to properties for us. Usually when you had a readonly property you usually had to do something like this:

private readonly string _x;

public string X
{
    get
    {
        return _x;
    }
}

public example(string x, string y)
{
    _x = x;
    _y = y;
}

However, they have now simplified it down to this:

private readonly string _x;

public string X => _x;

public Api(string x, string y)
{
    _x = x;
}

Next they showed off a new way to use string.Format. Usually a string format would look something like this:

KeyValuePair<string, string> x = new KeyValuePair<string, string>();

string query = string.Format("{0}={1}", x.Key, x.Value);

but now all you have to do is this:

KeyValuePair<string, string> x = new KeyValuePair<string, string>();

string query = $"{x.Key}={x.Value}";

How about an object that has an attributes property that you want to initialize, usually you need to add each one one at a time. Like so:

Dictionary<string, object> keys = new Dictionary<string, object>();
keys["id"] = Guid.Empty;
keys["name"] = "Jeremy";

Now you are able to initialize values inline like properties on a normal object:

Dictionary<string, object> keys = new Dictionary<string, object>()
{
    ["id"] = Guid.Empty,
    ["name"] = "Jeremy"
} ;

Another huge one is when you have a nullable object and you have an if statement where you want to check if it is null. Usually you would have something like this:

Dictionary<string, object> keys = new Dictionary<string, object>()
{
    ["id"] = Guid.Empty,
    ["name"] = "Jeremy"
};

if (keys != null && (Guid)keys["id"] == Guid.Empty)
{
    // Do something
}

You can now greatly simplify if statements by doing something like this:

Dictionary<string, object> keys = new Dictionary<string, object>()
{
    ["id"] = Guid.Empty,
    ["name"] = "Jeremy"
};

if ((Guid)keys?["id"] == Guid.Empty)
{
    // Do something
}

Finally the last one I’m going to go over is for async methods. Right now you can’t really use an await inside of a case or finally. However, starting now you can actually do just that! No more of that disgusting workarounds that you had to come up with to get around it. They even added the ability to append the case with a when after it to make it more specific. Like so:

try
{

}
catch (Exception ex) when (ex.Data == null)
{

}
finally
{

}
    

This only scratches the surface of everything that was shown at //Build/ but hopefully this gives you a head start.

Happy Coding.

Properly Pull Scaled Assets For Android and Android Wear

Overview

I’m going to show you how to properly pull in a scaled asset (specifically drawables) for either Android or Android Wear. Currently I see a lot of Bitmap.createScaledBitmap even in Google’s example projects for their Watch Faces. However, this is extremely inefficient and can slow things down. If you are using that, then you have already loaded the full image into memory and are now adding a new version of it (just smaller) to your memory.

So I am going to show you the correct way to do it. This code is also formatted so you can throw it into a Util class and use it everywhere.

How it’s done

Android specifically has a Class that helps us with building and working with images, and it is called BitmapFactory. Using this we can actually “decode” the image file to get a little bit of metadata that we need to calculate the new size. Then pull it at that size without having to actually fully load the image twice!

Pretty neat right?

In Practice

We are going to start with a standard method which will take the height and width you want the resource at and the id of the resource.

// since this is for a static Util Class pass int he resources as well
public static Bitmap pullScaledResourceBitmap(Resources resources, int width, int height, int resourceId) {
    BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
    // set the option to just decode the bounds because we just want
    // the dimensions, not the whole image
    bitmapOptions.inJustDecodeBounds = true;
    // now decode our resource using these options
    BitmapFactory.decodeResource(resources, resourceId, bitmapOptions);
    // since we have pulled the dimensions we can set this back to false
    // because the next time we decode we want the whole image
    bitmapOptions.inJustDecodeBounds = false;
    // look below to see the method to use to update the options to set
    // the sample size so we decode at the right size
    bitmapOptions.inSampleSize = calculateInSampleSize(bitmapOptions, width, height);
    // now decode the resource again and return it, because it decodes
    // as the scaled image!
    return BitmapFactory.decodeResource(resources, resourceId, bitmapOptions);
}

public static int calculateInSampleSize(BitmapFactory.Options bitmapOptions, int reqWidth, int reqHeight) {
    final int height = bitmapOptions.outHeight;
    final int width = bitmapOptions.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth)
    {
        final int halfHeight = height / 2;
        final int halfWidth = width / 2;

        while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) {
            inSampleSize *= 2;
        }
    }

    return inSampleSize;
}

That is all there is to it! Give it a try.

Calculate Layout Dimensions Before Render

Overview

Usually when you want to make an animation to show some hidden content, or draw a layout onto a canvas you need to know the dimensions. The issue is that you can’t really get them until that view has been rendered to the user. I am going to show you a way to do this without having to render it to the user. I have used this to get specific heights for one item in a ListView or full height of a ListView allowing me to expand and collapse from one item to all of them. I also used this to replicate the vignette feature from Google Glass to help draw specific things into the top right of an image.

How it works

We are going to use the built-in system for Views called MeasureSpec. Basically we are going to give the view parameters on how we would want it measured, and it would then go and get the real dimensions for this device. I will give you two examples of this.

The first one is measuring out a layout that we know exactly what the height and width we want it to be set to.

layout.measure(View.MeasureSpec.makeMeasureSpec(640, View.MeasureSpec.EXACTLY),
        View.MeasureSpec.makeMeasureSpec(360, View.MeasureSpec.EXACTLY));

But say we want to get the dimensions of something that we don’t know the exact values for since the text can be multiple lines. We can then say something like this.

layout.measure(View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.AT_MOST),
        View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));

In this view I’m using the ListView to set the largest width that it can go, so that the text wraps correctly when it measure the layout. This allows me to get an exact value for what the height would be if it were rendered.

Since this view isn’t rendered yet or is hidden, your getHeight() and getWidth() values with either be nothing or just off. So to get these values you just measured you would use this:

// get the height
layout.getMeasuredHeight();
// get the width
layout.getMeasuredWidth();
Layout Change Animations (Sliding Height)

Overview

One animation I see a lot, is the slide to open. Usually this is the actual layouts of a view being changed. However, if you just change the height it will just flash open. So I will show you two ways you can actually do this animation.

ValueAnimation

The first way you can do this, is by using a ValueAnimation (which can be used in an AnimatorSet). This animation goes though and changes the value of a set property along a parabola (or any line equation you specifically set into the Interpolator). It then goes to each point on it and then lets you create an equation based on where on that line the animation is at.

// view we want to animate
final View messageView = view.findViewById(R.id.message_section);

// set the values we want to animate between and how long it takes
// to run
ValueAnimator slideAnimator = ValueAnimator
        .ofInt(currentHeight, newHeight)
        .setDuration(300);


// we want to manually handle how each tick is handled so add a
// listener
slideAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
    @Override
    public void onAnimationUpdate(ValueAnimator animation) {
        // get the value the interpolator is at
        Integer value = (Integer) animation.getAnimatedValue();
        // I'm going to set the layout's height 1:1 to the tick
        messageView.getLayoutParams().height = value.intValue();
        // force all layouts to see which ones are affected by
        // this layouts height change
        messageView.requestLayout();
    }
});

// create a new animationset
AnimatorSet set = new AnimatorSet();
// since this is the only animation we are going to run we just use
// play
set.play(slideAnimator);
// this is how you set the parabola which controls acceleration
set.setInterpolator(new AccelerateDecelerateInterpolator());
// start the animation
set.start();

Custom Animation

A second more extreme solution, that doesn’t seem to always work the way you want, is to create a custom class that extends Animation. This is much more flexible and works almost exactly the same as the above ValueAnimator. You can make the constructor take in the new height and old height. This also uses the interpolator so you can still set a custom equation. Here is a basic example:

public class SlideAnimation extends Animation {

    int mFromHeight;
    int mToHeight;
    View mView;

    public SlideAnimation(View view, int fromHeight, int toHeight) {
        this.mView = view;
        this.mFromHeight = fromHeight;
        this.mToHeight = toHeight;
    }

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation transformation) {
        int newHeight;

        if (mView.getHeight() != mToHeight) {
            newHeight = (int) (mFromHeight + ((mToHeight - mFromHeight) * interpolatedTime));
            mView.getLayoutParams().height = newHeight;
            mView.requestLayout();
        }
    }

    @Override
    public void initialize(int width, int height, int parentWidth, int parentHeight) {
        super.initialize(width, height, parentWidth, parentHeight);
    }

    @Override
    public boolean willChangeBounds() {
        return true;
    }
}

The above is almost exactly the same, but you will have to then use it somewhere, so that will look something like this:

View messageView = view.findViewById(R.id.message_section);

Animation animation = new SlideAnimation(messageView, currentHeight, newHeight);

// this interpolator only speeds up as it keeps going
animation.setInterpolator(new AccelerateInterpolator());
animation.setDuration(300);
messageView.setAnimation(animation);
messageView.startAnimation(animation);

Conclusion

Both of these will get you the same kind of result, and can be built upon. Be careful though, it doesn’t always work in all places. When I made this custom animation class it doesn’t work when I used it in a drawer, but ValueAnimator did. Here is a gif of what it would look like. (keep in mind the gif makes it look choppy when it really isn’t).

sliding_animation