Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Tuesday, 6 March 2012

Android: write string to a file


FileOutputStream os = new FileOutputStream(fileName);
OutputStreamWriter osw = new OutputStreamWriter(os); 
osw.write(str);
osw.flush();
osw.close();

Do not use
DataOutputStream os = new DataOutputStream(new FileOutputStream(file));
os.writeUTF(str); // this will write a weird char at the beginning of the file

os.writeUTF writes the string with a modified UTF-8 encoding. If the file is opened by WebView as HTML, a weird char shows up at the beginning of the file. 


Sunday, 26 February 2012

Android: run time-consuming work in another thread

Many times you want to run time-consuming work in another thread instead of main thread because UI will stop response if you run it in main thread, and the user will frustrate.

It is easy to implement:

Just wrap up the time-consuming code with


new Thread(new Runnable() {
  public void run() {

  //... time-consuming work

  }
}).start();


Friday, 24 February 2012

Java: inline initializer for Map

Flurry has a function

FlurryAgent.logEvent(String event, Map<String,String> parameters)

It can be called with an inline initializer like this

FlurryAgent.logEvent("event", new HashMap<String,String>() {{
  put("key1","val1");
  put("key2","val2");
}});


Timing in Java

Timing in Java is easy.

long start = System.nanoTime();

long time = System.nanoTime()-start;

The unit is nanosecond. The long type is enough for 300 years.