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.


How to create random human readable passwords in PHP

To generate random readable passwords you can combine words, letters and special chars. The words can come from a wordlist array. For example you can use the list of the 10,000 most common English words in order of frequency, as determined by n-gram frequency analysis of the Google’s Trillion Word Corpus.

In the exmaple the words are taken from a static array, but you can use the google-10000-english.txt file with the php file() function which reads an entire file into an array. The generated password will contain one or more of the words in the list, depending on the length parameter. If you execute


you will get a random readable password with a length of 10 chars, but you can adjust the parameter to get a password with a different length.

function random_readable_pwd($length=10){

    // the wordlist from which the password gets generated
    // (change them as you like)
    $words = 'AbbyMallard,AbigailGabble,AbisMal,Abu,Adella,TheAgent,AgentWendyPleakley,Akela,AltheAlligator';

    $phonetic = array("a"=>"alfa","b"=>"bravo","c"=>"charlie","d"=>"delta","e"=>"echo","f"=>"foxtrot","g"=>"golf","h"=>"hotel","i"=>"india","j"=>"juliett","k"=>"kilo","l"=>"lima","m"=>"mike","n"=>"november","o"=>"oscar","p"=>"papa","q"=>"quebec","r"=>"romeo","s"=>"sierra","t"=>"tango","u"=>"uniform","v"=>"victor","w"=>"whisky","x"=>"x-ray","y"=>"yankee","z"=>"zulu");

   // Split by ",":
    $words = explode(',', $words);
    if (count($words) == 0){ die('Wordlist is empty!'); }

    // Add words while password is smaller than the given length
    $pwd = '';
    while (strlen($pwd) < $length){
        $r = mt_rand(0, count($words)-1);
        $pwd .= $words[$r];

    $num = mt_rand(1, 99);
     if ($length > 2){
        $pwd = substr($pwd,0,$length-strlen($num)).$num;
    } else {
        $pwd = substr($pwd, 0, $length);

   $pass_length = strlen($pwd);
   $random_position = rand(0,$pass_length);

   $syms = "!@#%^*()-?";
   $int = rand(0,9);
   $rand_char = $syms[$int];

   $pwd = substr_replace($pwd, $rand_char, $random_position, 0);

    return $pwd;


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.

Connect the esp8266 to the wireless network

For the IoT you can use a cheap esp8266 microcontroller with WiFi onboard. To connect the esp8266 to the wireless network you can use the following lua snippet that will work with the nodemcu firmware.

After connecting to the internet, you can create a TCP/IP server or client to send and receive data from your esp8266 microcontroller.

How to use LIMIT and ORDER BY in sqlite

To get the first 10 in descending order in sqlite


To get the first 10 in ascending order in sqlite


Note: If there are less than 10 entrys in the sqlite database, you will get less than 10 results.

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.

Disable wordpress automatic updates

In some cases it makes sense to disable automatic wordpress updates. For example if you want to have a special release of a running wordpress installation to check plugins or themes with this release. Or if are not ready to update to the latest version of wordpress or you want to update manualy….

The wordpress developers have considered this and you can easily put the following line of code to your wordpress wp-config.php file.

define('WP_AUTO_UPDATE_CORE', false );

This will disable all wordpress updates including the minor and major core updates.

If you want to enable wordpress only do the minor updates then use the following line.

define('WP_AUTO_UPDATE_CORE', 'minor' );

If you dount know how to do this or you don’t have access too your wp-config.php file, you can use the plugin. The Update Control plugin adds some options to your Settings – General page. It lets you specify how auto-upgrades should function, without the need to specify constants, edit the wp-config.php or add filters.

Note: Only disable automatic wordpress updates if you know, what you are doing. Some updates are needed because of security reasons and if you disable the update function, it can happen, that your wordpress installation is vulnerable.



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.