Java get a XML document (file, string or inputstream) as a org.w3c.dom.Document

This helper function will read a xml string (or any InputStream) and create a Document from this.

public static Document loadXMLAsDom(String xml){
	return loadXMLAsDom(new ByteArrayInputStream(xml.getBytes()));
}
public static Document loadXMLAsDom(InputStream inputStream) {
	DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
	documentBuilderFactory.setNamespaceAware(true);
	DocumentBuilder documentBuilder = null;
	Document document = null;
	try{
		documentBuilder  = documentBuilderFactory.newDocumentBuilder();
		document = documentBuilder.parse(new InputSource(inputStream)); //use InputSource here to get better support for encodings
		inputStream.close();
	}
	catch (ParserConfigurationException e){
		System.out.println("loadXMLAsDom got a ParserConfigurationException! "); e.printStackTrace;
	}
	catch (IOException e){
		System.out.println("loadXMLAsDom got a IOException! "); e.printStackTrace;
	}
	catch (SAXException e){
		System.out.println("loadXMLAsDom got a SAXException! "); e.printStackTrace;
	}		
	return document;
}

Java getting exception.printStackTrace as a string

In cases like when I simply want to make a System.out.println or similar with some details of a exception then the following static helper function is very nice as it takes the exception (uses printStackTrace) and returns a string with the contents of it.

public static String getStackTrace(Exception e){
	StringWriter stringWriter = new StringWriter();
	PrintWriter printWrtier = new PrintWriter(stringWriter);
	e.printStackTrace(printWrtier);
	return stringWriter.toString();
}

Android custom dialog

This will create a custom dialog.

AlertDialog.Builder builder;
AlertDialog alertDialog;
 
Context mContext = this;
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.help_dialog, (ViewGroup) findViewById(R.id.layout_root));
 
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText(getString(R.string.help_string));
 
builder = new AlertDialog.Builder(mContext);
builder.setView(layout);
alertDialog = builder.create();
 
alertDialog.show();

And create a “help_dialog.xml” this name is from the inflater

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout_root"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    >
    <TextView android:id="@+id/text"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:textColor="#FFF"
        />
</LinearLayout>

LayoutInflater at android dev

Android getString(R.string.text) in a static method

Sometimes there is a need to access recourses from static methods.
In order to do this we need to pass along the Context to the method and use getString from that Context.

Example:

package com.f15ijp.android.test;
 
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.WindowManager;
 
public class Help {
	public static AlertDialog helpDialog(Context theContext, String helpMessage){
	AlertDialog alertDialog = new AlertDialog.Builder(theContext).create();            	
    	alertDialog.setTitle("Help");
    	alertDialog.setMessage(helpMessage);
    	alertDialog.setButton(theContext.getString(R.string.close_help_btn), new DialogInterface.OnClickListener() {
	    @Override
	    public void onClick(DialogInterface dialog, int which) {
		return;						
	    }
	});
    	WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        lp.copyFrom(alertDialog.getWindow().getAttributes());
        lp.width = WindowManager.LayoutParams.FILL_PARENT;
        lp.height = WindowManager.LayoutParams.FILL_PARENT;
        /*by calling alertDialog.show() now and then again after setAttributes the background
         * the background activity is replaced by a black box. 
         * If this first alertDialog.show() is removed then the (current) acitivity is used as a background. 
         */
        alertDialog.show();
        alertDialog.getWindow().setAttributes(lp);
        return alertDialog;
    }
}

Java iterating over a Map

In java it is not hard to iterate over a Map. The following example is quick and simple (and if your Map is not of this sort you can change it accordingly easily).

for (Map.Entry<String, Object> entry : map.entrySet()) {
    String key = entry.getKey();
    Object value = entry.getValue();
    // ... do important stuff here!
}

Java Array toString

Doing a toString on a array don’t really tell that much about the array. Here is one way to get the contents of the array as a string.

int[] myArray = new int[2];
myArray[0] = 1; myArray[1] = 2;
System.out.println("array contains " + java.util.Arrays.toString(myArray));
 
//will output array contains [1, 2]

Java Converting a int to a string

The Integer Class have a static method toString that takes a int as input and gives us back a string.

int myInt = 1;
System.out.println(Integer.toString(myInt);

This is a log more efficient and nice in the long run than just concating the int with a empty string ( myInt + “” ) as that actually creates a bit of overhead. Not much, but still.

Java Converting between Boolean & String

To convert from a Boolean to a string

new Boolean(new String("hej".equalsIgnoreCase("HEJ")).toString();

and then from a string to a boolean

boolean theValue = Boolean.parseBoolean(strBoolean);

Java safe conversion of long to int

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

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

The reason that theLong.intValue() is not suggested here is that intValue rounds the value to fit a int – it don’t say it can’t be done.

Setting up JAVA_HOME on Window

The JAVA_HOME variable should point to the JDK’s bin folder in order for Java applications (jar, war, etc) to know where Java lives.

To setup a JAVA_HOME environment variable on Windows.

  • Right click on the My Computer icon in the start menu or on the desktop and select properties
  • Click the Advanced Tab
  • Click the Environment Variables button
  • Under System Variable, click New
  • Enter the variable name as JAVA_HOME
  • Enter the variable value as the install path for the Development Kit
  • Click OK
  • Click Apply Changes

Word of caution, Java is not fond of spaces, so I use pathnames without spaces.

Note: You will need to click OK, apply changes AND reload cmd to see the changes there.