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.

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.

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: http://docs.oracle.com/

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.

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

Source: http://stackoverflow.com/

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:

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

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.
http://developer.android.com/reference/android/util/TypedValue.html

But for me the upper solution with px2Dp and dp2Px works perfect.

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.

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.

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

Yes

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.

  • MODE_PRIVATE
    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).
  • MODE_WORLD_READABLE
    This mode allows all other applications to have read access to the Shared Preferences.
  • MODE_WORLD_WRITEABLE
    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
android.content.SharedPreferences

Description
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.

Note
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.

Summary
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().

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 http://en.wikipedia.org/wiki/List_of_HTTP_status_codes.

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.

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: