Presentation @ Techblog workshop about new Android design guidelines.
Android Code Tips
There are 49 posts filed in Android Code Tips (this is page 1 of 10).
Android Get metadata from AndroidManifest to your code
In your manifest’s application tag:
usage:
String user = getMetadata(this, “user);
public static String getMetadata(Context context, String name) {
try {
ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(
context.getPackageName(), PackageManager.GET_META_DATA);
if (appInfo.metaData != null) {
return appInfo.metaData.getString(name);
}
} catch (PackageManager.NameNotFoundException e) {
// if we can’t find it in the manifest, just return null
}
return null;
}
Rename files to lowercase
As you probably now, your application’s images that are in the drawable directory must be named in lowercase.
Unfortunately this is not true for the iPhone applications. A big portion of my job is to develop Android apps using resources from existing iPhone apps. In order to be quick and efficient, I wrote this bash script that renames all your files in your current directory to lowercase, creates a new folder named 2x (which contains the large images) and removes the @2x extension.
for i in `find .`; do mv -v $i `echo $i | tr '[A-Z]' '[a-z]'`; done mkdir 2x mv *2x.png 2x/ cd 2x/ for i in `find .`; do mv -v $i `echo $i | tr -d '@2x'`; done
Please have a backup before using it!
UTF-8 encoding at post values with HttpClient
It took me a while to find out how, so I believe it will be useful for you too.
HttpClient client = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("http://urlhere.com"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("name1", "utfvalue1")); nameValuePairs.add(new BasicNameValuePair("name2", "utfvalue2")); UrlEncodedFormEntity formEntity = null; try { formEntity = new UrlEncodedFormEntity(nameValuePairs, "UTF-8"); } catch (UnsupportedEncodingException e2) { e2.printStackTrace(); } if (formEntity != null) httpPost.setEntity(formEntity); ...
Copy the content of an input stream to an output stream
How to copy the content of an input stream to an output stream
/** * Copy the content of the input stream into the output stream, using a temporary * byte array buffer whose size is defined by {@link #IO_BUFFER_SIZE}. * * @param in The input stream to copy from. * @param out The output stream to copy to. * * @throws IOException If any error occurs during the copy. */ private static final int IO_BUFFER_SIZE = 4 * 1024; private static void copy(InputStream in, OutputStream out) throws IOException { byte[] b = new byte[IO_BUFFER_SIZE]; int read; while ((read = in.read(b)) != -1) { out.write(b, 0, read); } }