Java: Getting the Document from a Node or Element

When we for instance wishes to add a new element we need to pass along the document. If we have a element or a node we can get the document that way. Simply call getOwnerDocument and we are good.

Element element = //code to get a element
Node node = //code to get a node
 
//document from Node
Document document = node.getOwnerDocument();
 
//document from a Element
Document document = element.getOwnerDocument();

Java: Adding a Element under an Element (or Converting a Element to a Node)

When using Document a Element can only be appended with a Node, but what if we have a Element ?

Easy, Element extends Node so just pass the Element along and all is well

import org.w3c.dom.Document;
import org.w3c.dom.Element;
 
Document doc;
Element newElement;
Element oldElement; //code to find that
newElement = doc.createElement("tag");
oldElement.appendChild(newElement);

Java: Creating a enum and converting from a string to the Enum

Here is a simple example of how create a Enum and how to convert from a String to the Enum (the common reason for doing this would be is we at some point have for OurEnum.toString() and now wishes to get back to the OurEnum)

First we need to create the Enum, and this needs to be in its own file

public enum OurEnum { ENUM_A, ENUM_B, ENUM_C }

When we then later on (for instace have saved the toString value in a xml file) wish to

String ourEnumAsAString = "ENUM_A"; //replace with code to read the value
OurEnum ourEnum = OurEnum.valueOf(ourEnumAsAString);

Android resize a bitmap

Here is a snippet to scale down a bitmap – the original bitmap still needs to fit on memory though

InputStream bitmap = mContext.getAssets().open("image.file");
Bitmap scaledBitmap= Bitmap.createScaledBitmap(BitmapFactory.decodeStream(bitmap), 120, 120, false);
bitmap.

Android set background color of ActionBar

Here is a snipet that will set the background color of a ActionBar to a hexcolor.

final ActionBar bar = getActionBar();
 
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#000000")));

Color.parseColor will take any hexstring of a color and make it into a int.

Android: Suppressing the warning about using px in layout xml

When working with for instance the Sony SmartWatch there is a need to specify layout for the Watch in pixels (not device pixels) – as the SmartWatch is a fixed size and not dependent of the device it is connected to. When this is done the lint verification will warn about this being a bad idea, but it is possible to suppress this warning by adding the following to the xml file:

  1. add the namespace xmlns:tools=”http://schemas.android.com/tools”
  2. and then then you can disable the px-warnings by including this in your view: tools:ignore=”PxUsage”.

Example:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="@drawable/background"
>
 
    <View
        tools:ignore="PxUsage"
        android:id="@+id/smartWatchView"
        android:layout_width="128px"
        android:layout_height="128px"
        android:visibility="visible"
        android:layout_centerInParent="true" 
    />
 
</RelativeLayout>

Android garbage collection types

We are all used to seeing lines like “D/dalvikvm( 8285): GC_CONCURRENT freed 494K, 9% free 14648K/16071K, paused 2ms+2ms” in the logcat, but what does the types mean (why is the device Garbage collecting just then)?

From the sources “dalvik/vm/alloc/Heap.h” we find that

typedef enum {
    /* Not enough space for an "ordinary" Object to be allocated. */
    GC_FOR_MALLOC,
    /* Automatic GC triggered by exceeding a heap occupancy threshold. */
    GC_CONCURRENT,
    /* Explicit GC via Runtime.gc(), VMRuntime.gc(), or SIGUSR1. */
    GC_EXPLICIT,
    /* GC to try to reduce heap footprint to allow more non-GC'ed memory. */
    GC_EXTERNAL_ALLOC,
    /* GC to dump heap contents to a file, only used under WITH_HPROF */
    GC_HPROF_DUMP_HEAP
} GcReason;

And a slightly more expanded explanation is:
GC_FOR_MALLOC was triggered because there wasn’t enough memory left on the heap to perform an allocation.

GC_EXPLICIT means that the garbage collector has been explicitly asked to collect.

GC_CONCURRENT Is triggered when the heap has reached a certain amount of objects to collect.

GC_EXTERNAL_ALLOC is triggered when the VM is trying to reduce the amount of memory used for collectable objects, to make room for more non-collectable.

Java safe conversion of float to int

In most cases this is really not needed, if possible please keep the float as a float and work with it as such, but if needed the following works

public static Integer floatToInteger(float value){
    if (Math.round(value) < Integer.MIN_VALUE || Math.round(value) > Integer.MAX_VALUE) {
        throw new IllegalArgumentException
            (value + " cannot be cast to int without changing its value.");
    }
    return (int) Math.round(value);
}

(It might be needed for instance for a switch/case as that don’t work with float – or to work with external/legacy API’s that we can not or wish not to modify)

Sony Smart Extras (Smartwatch) Keeping the screen on – controlling the screen state

In the utils package there is a function that can be used to control the screen state.

    /**
     * Set the accessory screens state.
     *
     * @see Control.Intents#SCREEN_STATE_AUTO
     * @see Control.Intents#SCREEN_STATE_DIM
     * @see Control.Intents#SCREEN_STATE_OFF
     * @see Control.Intents#SCREEN_STATE_ON
     *
     * @param state The screen state.
     */
    protected void setScreenState(final int state) {
        if (Dbg.DEBUG) {
            Dbg.d("setScreenState: " + state);
        }
        Intent intent = new Intent(Control.Intents.CONTROL_SET_SCREEN_STATE_INTENT);
        intent.putExtra(Control.Intents.EXTRA_SCREEN_STATE, state);
        sendToHostApp(intent);
    }

So all we need to do in order to control the screen state is to call this with the correct screen state intent. The following example will keep the screen on

 setScreenState(Intents.SCREEN_STATE_ON);

Android: Rotate a bitmap

Here is a small sample that will rotate a bitmap.

Bitmap animation = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.eye_rotate, mBitmapOptions);
 
Bitmap bitmap = Bitmap.createBitmap(animation.getWidth(), animation.getHeight(), BITMAP_CONFIG);
bitmap.setDensity(DisplayMetrics.DENSITY_DEFAULT);
 
Matrix matrix = new Matrix();
matrix.reset();
matrix.setTranslate(0, 0);
matrix.postRotate(degrees, (animation.getWidth()/2), (animation.getHeight()/2));        	
 
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
int xPos = 0;
int yPos = 0;
Rect src = new Rect(xPos, yPos, xPos + animation.getWidth(), yPos + animation.getHeight());
Rect dst = new Rect(0, 0, animation.getWidth(), animation.getHeight());
 
canvas.drawBitmap(mBackground, src, dst, paint);
canvas.drawBitmap(animation, matrix, null);