How to sort an ArrayList in Java

If you want to sort any ArrayList in java, you need to make sure, your objects in the arrylist are comparable. This is done by using implements Comparable and implementing the abstract method compareTo (T cmp). For example if you want to sort some highscores you can do it like this.

public class Highscore implements Comparable

	public int compareTo(Highscore cmp)
		if (cmp.getAnzQuad() > getAnzQuad())
			return -1;
		} else {
			return 1;

public class Highscores

	public ArrayList getHighscores ()
		ArrayList ret = new ArrayList();
		// Fill the ret ArrayList with your highscores	

		// Sort the highscores with Collections.sort
		return ret;

This is a simple, but powerfull solution to sort an ArrayList.

Capture screenshot in Java (AWT)

In Java there is a easy was to capture screenshots. The following captureScreenshot method will capture a screenshot of the display of your screen and save it to the disk.

public void captureScreenshot(String filename) 
   throws Exception 
   java.awt.Dimension size = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
   java.awt.Rectangle rectangle = new java.awt.Rectangle(size);
   java.awt.Robot robot = new java.awt.Robot();
   java.awt.image.BufferedImage image = robot.createScreenCapture(rectangle);
   javax.imageio.ImageIO.write(image, "png", new;

If you want to create a screenshot of a specific part of your screen, you have to modyfy the rectangle. You can do this with rectangle .setBounds(int x, int y, int width, int height).

Rectangle API:

Note: This will need “java.awt”. So you cannot run this code on Android devices, because there is no java.awt package available. Also note, that you have to run a X-Server on linux to execute this. If you try to execute this on a linux server without X-Server, you will not be able to capture screenshot of your terminal.
On Windows this is not a problem. The capture screenshot method will work on windows even if you are not the Administrator.

How to get the name of the current method in Java

There is a simple solution, to get the name of the current method in Java. It uses the stack trace to get the name of the mehod. It works with different virtual machines like oracle, dalvik (Android), Open JDK, etc.

String name = Thread.currentThread().getStackTrace()[1].getMethodName();

But don’t use this in time-critical code, because working with the StackTrace is not recommended for high performcnce activities.


Android Background Service Template

This is a simple Android background Service Template. You can use it to run updates in the background without blocking the UI. To start and stop the service use the following lines in your activity:

// starting the service
Intent intent = new Intent(this, UpdateService .class);
// stopping the service
Intent intent = new Intent(this, UpdateService .class);
// The UpdateService class 
// Change the interval integer value to your needs and implement the method with your requrements

public class UpdateService extends Service 
    private UpdateThread myythread;
    public Intent intent;
    public boolean isRunning = false;

    long interval=30000; // Fixed interval of 30 seconds

    public IBinder onBind(Intent arg0) 
        return null;

    public void onCreate() 
        myythread  = new UpdateThread(interval);

    public synchronized void onDestroy() 

            isRunning = false;

    public synchronized void onStart(Intent intent, int startId) 
        super.onStart(intent, startId);

            isRunning = true;

    class UpdateThread extends Thread
        long interval;
        public UpdateThread(long interval)

        public void run()
                System.out.println("Service running");
                	 // TODO Service actions
                catch (InterruptedException e) 
                    isRunning = false;

This is all you need to execute a service on android devices. Don’t forget to add the service to your AndroidManifest.xml file.

Converting pixels to dp and dp to px in Android

If you play around with height and width for a android device you often need to convert between real pixel (px) and device indipenden pixel (dp, dip).

The following methods are a easy solution to convert between px to dp

	private float px2Dp(float px, Context ctx)
		return px / ctx.getResources().getDisplayMetrics().density;

	private float dp2Px(float dp, Context ctx)
		return dp * ctx.getResources().getDisplayMetrics().density;

The density equals the following values depending on your device type.

.75 on ldpi (120 dpi)
1.0 on mdpi (160 dpi; baseline)
1.5 on hdpi (240 dpi)
2.0 on xhdpi (320 dpi)
3.0 on xxhdpi (480 dpi)
4.0 on xxxhdpi (640 dpi)

Alternativ you can use a util from the android SDK to get pixel from dip.

		Posted on Tags , , , , , 			

How do I remove objects from an array in Java?

To remove objects from an array in Java you have to make a List out of the array with Arrays.asList(), and call remove(object) on all the appropriate elements. Then call toArray() on the ‘List’ to make back into an array again. This is not terribly performant, but if you use it in a properly way, you can do it like this.

List list = new ArrayList(Arrays.asList(array));
array = list.toArray(array);

This does work with not only with String arrays. You can arrays of every Class to remove objects from your array. Here is another simple Example for a List of Cars.

List list = new ArrayList(Arrays.asList(array));
array = list.toArray(array);

Thats all. You only have to change the instantiation of the ArrayList to match with your array. So you can delete objects from arrays of any Class.

Can Shared Preferences be private?

Short answer


Long answer

Shared Preference are saved in the file system of your device, and the Shared Preferences Mode defines whether other applications have the right to read or write the Shared Preferences or not. Android SharedPreferences with mode “MODE_PRIVATE”, “MODE_WORLD_READABLE” and “MODE_WORLD_WRITABLE” are possible in android.

    This is the default mode, where the created file can only be accessed by the calling the application (or other applications sharing the same user ID).
    This mode allows all other applications to have read access to the Shared Preferences.
    If you choose this mode, all other applications to have write access to the Shared Preferences.

The getSharedPreferences mothod in the Context class can take two arguments. The first argument is the name of the Shared Preference and the second on is the mode. With the mode you can determines if the shared preferences are private or not.

About Shared Preferences

Full name

Interface for accessing and modifying preference data. For any particular set of preferences, there is a single instance of this class that all clients share. Modifications to the preferences must go through the SharedPreferences.Editor.

Currently SharedPreferences do not support multiple processes.

Nested Classes

  • SharedPreferences.Editor
    Interface used for modifying values in a SharedPreferences object.
  • SharedPreferences.OnSharedPreferenceChangeListener
    Interface definition for a callback to be invoked when a shared preference is changed.

Public Methods

  • abstract Boolean contains(String key)
    Checks whether the preferences contains a preference.
  • SharedPreferences.Editor edit()
    Create a new Editor for these preferences, through which you can make modifications to the data in the preferences and atomically commit those changes back to the SharedPreferences object.
  • Map getAll()
    Retrieve all values from the preferences.
  • boolean getBoolean(String key, boolean defValue)
    Retrieve a boolean value from the preferences.
  • float getFloat(String key, float defValue)
    Retrieve a float value from the preferences.
  • int getInt(String key, int defValue)
    Retrieve an int value from the preferences.
  • long getLong(String key, long defValue)
    Retrieve a long value from the preferences.
  • String getString(String key, String defValue)
    Retrieve a String value from the preferences.
  • Set getStringSet(String key, Set defValues)
    Retrieve a set of String values from the preferences.
  • void registerOnSharedPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener listener)
    Registers a callback to be invoked when a change happens to a preference.
  • void unregisterOnSharedPreferenceChangeListener(SharedPreferences.OnSharedPreferenceChangeListener listener)
    Unregisters a previous callback.

Android SharedPreferences with private mode are default in android. Other modes like WORLD_READABLE and WORLD_WRITABLE are possible if you need SharedPreferences with this mode.

How to read the status code of a HTTP request?

If you open a URLConnection with the Hypertext Transfer Protocol, the Object of URLConnection that is returned from openConnection is a HttpURLConnection. This class defines a method, which is able to access the status code of the http response. To get the status of your http reesponse, it is necessary to cast the URLConnection Object to a HttpURLConnection, and invoke the method getResponseCode().

URL url = new URL ( “” );
URLConnection connection = url.openConnection();

Int code;
if ( connection instanceof HttpURLConnection)
   HttpURLConnection httpConnection = (HttpURLConnection) connection;
   code = httpConnection.getResponseCode();
// In this case the code is 200

Most used codes are:

  • 200 OK
  • 301 Moved Permanently
  • 401 Unauthorized
  • 403 Forbidden
  • 404 Not Found
  • 500 Internal Server Error

A list of available HTTP Response codes can be found at

Export sharedPreferences to file

With the getAll function of sharedPreferences it is possible to save the shared preferences to a file. The following code example is probably the easyest way to do it. With the saveSharedPreferences method you can save all shared preferences a file to the root of your sdcard.

Make sure your App has the following permission. It allows the application to write to external storage.

 Possible modes: 

/* Execute save SharedPreferences example code */
String name = "MyName";
int mode = MODE_PRIVATE;
File path = new File(Environment.getExternalStorageDirectory().toString());
File file = new File(path, "MySharedPreferences");
saveSharedPreferences (name, mode, file);

private void saveSharedPreferences(String name, int mode, File file)  
    SharedPreferences prefs = getSharedPreferences(name, mode);
        FileWriter fw = new FileWriter(file);
        PrintWriter pw = new PrintWriter(fw);
        Map prefsMap = prefs.getAll();
        for(Map.Entry entry : prefsMap.entrySet())
            pw.println(entry.getKey() + ": " + entry.getValue().toString());            
    catch (Exception e)
    {, e.toString());

Android Reflection-API Constructor without parameters

If you have to create an object with default constructor, you can invoke the newInstance() method on a Class.
This simple class creates the instance of a named class using the empty default constructor by calling the newInstance method:

public class ReflectionTester throws InstantiationException, IllegalAccessException, ClassNotFoundException 
   public static Object createObject(String className) {
      return Class.forName(className).newInstance();