Skip to content

Tag: programming

Android screen height and width

Context ctx = getContext();
Display display = ((WindowManager)ctx.getSystemService(ctx.WINDOW_SERVICE)).getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();

Yes, there are easier ways to retrieve the screen width on Android but there are cases that this long code is the only solution. You may already have the Context. WindowManager or the Display and so it would be smaller, but this code is more general.

PHP: array, all elements but first

$bric = array("Brazil", "Russia", "India", "China"); 
$ric = $bric; // array copy
$br = array_shift($ric); // left shift at $ric. $br stores "Brazil" 
print_r($bric); // $bric remains the same
print_r($ric); // $ric lost "Brazil"

Output:

Array
(
    [0] => Brazil
    [1] => Russia
    [2] => India
    [3] => China
)
Array
(
    [0] => Russia
    [1] => India
    [2] => China
)

Reference: PHP array_shift at php.net.

Java: invoking a method by name


import java.lang.reflect.*;

public class Foo {
	public void bar(int param){
		System.out.println(param);
	}	

	public static void main(String args[]){
		Object f = new Foo();
		try {
			Method m = f.getClass().getMethod("bar", int.class);
			m.invoke(f, 42);
		} catch (Exception e){
			System.err.println(e);	
		}
	}

}

$ java Foo
42

calling commands in Java

I don’t like the approach of calling native shell commands in any language instead of using multi platform libraries, but here is a little prof of concept Java program to call native commands.

import java.io.*;
import java.util.*;
public class Exec {
   public static void main(String args[]) throws IOException {
      Process proc = Runtime.getRuntime().e xec(args);
      BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
      String line;
      while ((line = br.readLine()) != null) {
         System.out.println(line);
      }
   }
}

Usage:

java Exec VALID_COMMAND

Example:

$ java Exec echo hello
hello

ps: I had to write “e xec” instead of exec because it was triggering some very strange security protection in the blog engine here. If you need to compile this code change that. =P Also there’s no error handling, you should pass a valid command when executing this code.

Iterating over a HashMap

Iterating over a HashMap using the enhanced loop (foreach) in Java is a good way to keep your code smaller, more legible and usually more semantically coherent.

import java.util.HashMap;
import java.util.Map;

class Foo {}

public class Main {
	
   public static void main(String args[]){
      Map mHash;
		
      mHash = new HashMap();
      mHash.put((byte)1, new Foo());
      mHash.put((byte)2, new Foo());
      mHash.put((byte)3, new Foo());
		
      for(Foo f: mHash.values()){
         System.out.println(f.toString());
      }
   }
}

Getting an Android app source

Getting the Android’s AlarmClock application source from official repositories:

git clone git://android.git.kernel.org/platform/packages/apps/AlarmClock.git

To get the head version for an old platform like the 1.4 (codename donut), choose the correspondent branch using -o or –origin:

git clone git://android.git.kernel.org/platform/packages/apps/AlarmClock.git --origin donut

Getting enviroment information on Android

This is a simple program I wrote called Who Am I that shows informations about the device which it is running. Which can be useful for developers and maybe advanced users.

Download:

  • WhoAmI.tar.bz2 – Eclipse project. It’s configured for Android platform 4 (1.6) but should work without problems in newer Android platform versions.
  • WhoAmI.apk – Application installation Android package.

Main Activity source code:

package net.silveiraneto.whoami;

import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.widget.EditText;

public class WhoAmI extends Activity {
    private EditText mEditor;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.whoami);

        mEditor = (EditText) findViewById(R.id.editor);

        Object[][] properties = {
        	{"Build.BOARD", Build.BOARD},
        	{"Build.BRAND", Build.BRAND},
        	{"Build.CPU_ABI", Build.CPU_ABI},
        	{"Build.DEVICE", Build.DEVICE},
        	{"Build.DISPLAY", Build.DISPLAY},
        	{"Build.FINGERPRINT", Build.FINGERPRINT},
        	{"Build.HOST", Build.HOST},
        	{"Build.ID", Build.ID},
        	{"Build.MANUFACTURER", Build.MANUFACTURER},
        	{"Build.MODEL", Build.MODEL},
        	{"Build.PRODUCT", Build.PRODUCT},
        	{"Build.TAGS", Build.TAGS},
        	{"Build.TIME", Build.TIME},
        	{"Build.USER", Build.USER},
        };

        for(Object[] prop: properties) {
        	mEditor.append(String.format("%s: %s\n", prop[0], prop[1]));
        }
    }
}

And its Android Manifest:



    
        
            
                
                
            
        
    

The Caps Lock Java Socket Server

Here is a simple server for those who are starting studying sockets or just needs a simple socket server example for reuse while writing your own behavior.

Features:

  • A client should enter a string and the server would answer the same string, with each symbol in up case, when possible.
  • Default port at 8080.
  • One client at time.
  • No multi threading. I said its a simple server.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
	private static final int DEFAULT = 8080;

	public Server() {
		this(DEFAULT);
	}

	public Server(int port) {
		ServerSocket sock;

		try {
			sock = new ServerSocket(port);
			System.out.println(String.format("Listening on port %d.", port));

			while (true) {
				try {
					Socket client = sock.accept();
					System.out.println("A new connection was accepted.");

					BufferedReader in = new BufferedReader(
							new InputStreamReader(client.getInputStream()));		
					OutputStreamWriter out = new OutputStreamWriter(client
							.getOutputStream());
					String input = "";

					while (!input.equals("exit")) {
						input = in.readLine();
						if (input.equals("shutdown")) {
							System.exit(0);
						}
						out.write(input.toUpperCase() + "\r\n");
						out.flush();
					}

					in.close();
					out.close();
					client.close();
					System.out.println("Connection closed.");
				} catch (NullPointerException npe) {
					System.out.println("Connection closed by client.");
				}
			}
		} catch (IOException ioe) {
			System.err.println(ioe);
			System.exit(-1);
		}
	}

	public static void main(String[] args) throws IOException {
		new Server();
	}
}

Usage:

$ javac Server.java
$ java Server
Listening on port 8080.

In another terminal:

$ telnet localhost 8080
Trying ::1…
Connected to localhost.
Escape character is ‘^]’.
hi
HI
The quick brown fox jumps over the lazy dog.
THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.
exi
EXI
exit
EXIT
Connection closed by foreign host.

Beware the locale

See-ming Lee 李思明 SML Photo

Today I was programming a toString method for a class widely used in a application, using the very useful String.format that provides a C’s like printf formatter.

@Override
public String toString() {
   return String.format("VO[a: %.1f, b: %.1f, c: %.1f]", a, b, a+b);
}

%.1f means a float with one digit precision after the dot separator. The code produces something like:

VO[a: 1.0, b: 2.0, c: 3.0]

The problem arises when running a JUnit test on this method wrote using a regular expression to extract the values from the String to test it correctness. We cannot assume that the dot will be always the separator for displaying a float value, in my locale pt_BR would be a comma. So the output would be:

VO[a: 1,0, b: 2,0, c: 3,0]

For a predictable output we can set a Locale for String.format:

Locale en = new Locale("en");
return String.format(en, "VO[a: %.1f, b: %.1f, c: %.1f]", a, b, a+b);

So it will always use the dot as common separator. Of course you should follow and respect the localization and internationalization efforts in others moments but in this toString case we are using it internally for debug and unitary testing so we can set a English default locale for safety reasons.

Miojo Script

O pre-requisito é o notify-send, um utilitário de linha de comando do libnotify. No Ubuntu:

sudo aptitude install libnotify-bin

E aqui o script em si:

sleep 5m; notify-send "aviso" "tirar o miojo do fogo"

Pronto, depois de cinco minutos isso vai aparecer: