Thursday, April 16, 2015

Check if app is in development mode or production mode

Make sure Gradle is configured properly.
if (BuildConfig.DEBUG == true) {
  // development mode
}

Friday, March 6, 2015

Wake up from sleep, unlock screen when activity launches

This snippet come in very handy when debugging apps on a real device.

Wake up, unlock screen and keep it on:

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);


Note: Make sure to remove it in release versions.

Set a TTF font to TextView

Place the font in assets folder

Example for Android studios: app/src/main/assets/font.ttf

Typeface typeface = Typeface.createFromAsset(getAssets(), "font.ttf");
TextView textView = (TextView) findViewById(R.id.textview_name);
textView.setTypeface(typeface);

Display list of clickable items on Alert dialog

Display a simple list of clickable items on a alert dialog.
new AlertDialog
  .Builder(getApplicationContext())
  .setTitle("Actions")
  .setItems(new String[]{
    "Item #1",
    "Item #2",
    "Item #3"
  }, new DialogInterface.OnClickListener() {
       @Override
       public void onClick(DialogInterface dialogInterface, int i) {
         switch (i) {
           case 0 : // do something
             break;
           case 1 : // do something
             break;
           case 2 : // do something
             break;
         }
      }
    })
  .create()
  .show();

Iterate a SQLite Cursor Object in Android

There are numerous ways of iterating over a cursor object. This is what I prefer:

cursor.moveToFirst();
while (!cursor.isAfterLast()) {
  // Do something
  cursor.moveToNext();
}
cursor.close();


Here's another one (this is one of the simplest approach):
for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()){
  // Do something
}