Showing posts with label android. Show all posts
Showing posts with label android. Show all posts

Sunday, July 13, 2014

Guava's I/O Sources and Sinks on Android

I love Guava's I/O wrappers - ByteSource, ByteSink, CharSource, and CharSink. They encapsulate I/O stream (or reader/writer) access in a way that makes it easy for me to open & close the stream in the same location; when I pass a stream directly, the points of opening it and reliably closing it may be far apart. They also have helper methods to sweeten some common tasks, like reading an entire char source.

Android provides an existing mechanism for accessing private files while controlling their access modes: Context.openFileOutput and Context.openFileInput. As a Source/Sink primer, here's a cool way to adapt between the two:

The usage would look like this:
AndroidPrivateFileGuavaAdapter adapter =
  new AndroidPrivateFileGuavaAdapter("filename", Context.MODE_PRIVATE, context);

 // Read all text
String contents = adapter.asCharSource().read();

 // Write some bytes
byte[] bytes = ...; // obtains bytes from somewhere
adapter.asByteSink().write(bytes);

Monday, October 21, 2013

Android: backup and restore an app's data during development

During development, having an app with a realistic configuration and data set is really useful. Here's a trick that can help.

Connect a device with the app configured with lots of good data, turn USB debugging on, and then:
adb backup com.example.mypackage

Later, on another device (or the same device after a clean install):
adb restore backup.ab

W00t.