
Android Tips
Android tip #020 – Broadcast intents
Platform/Language: Java/Android
Description: we can send broadcast messages (Intents) in our application. They can be useful when we need to comunicate Activities with other Activities, Services with Activities and so on. It is a good way to send and listen messages in the whole application.
We need a receiver (which will listen the message) and a sender (which will send the message)
Code:
Sender.java
1 2 3 4 5 6 7 | public static final String BROADCAST_MESSAGE = "my_message"; private void sendBroadcastMessage(Context context) { Intent i = new Intent(); i.setAction(BROADCAST_MESSAGE); context.sendBroadcast(i); } |
ReceiverActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | public class ReceiverActivity extends Activity { private BroadcastReceiver receiver = new BroadcastReceiver(){ @Override public void onReceive(Context arg0, Intent arg1) { ReceiverActivity.this.doSomething(); } }; private void doSomething() { } public void onResume() { super.onResume(); IntentFilter filter = new IntentFilter(); filter.addAction(Sender.BROADCAST_MESSAGE); this.registerReceiver(this.receiver, filter); } public void onPause() { super.onPause(); this.unregisterReceiver(this.receiver); } /* ... */ } |
Android tip #019 – Database not open
Platform/Language: Java/XML/Android
Description: A very common error when we are working with database is not check that we have the database opened. So, we will receive the exception “java.lang.IllegalStateException: database not open“. We can fix it with a simple condition before we execute any query.
Code:
YourClass.java
1 2 3 4 5 6 7 8 9 10 11 12 | SQLiteDatabase d = null; // Initialization, other queries and so on... // ... if (d == null || !d.isOpen()) { d = db.getWritableDatabase(); // d = db.getReadableDatabase(); } // Your query here // ... |
Android tip #018 – Resize layout on show/hide keyboard
Platform/Language: XML/Android
Description: sometimes we need to resize the layout when the keyboard appears. For example, when you click in one of your TextView, and this one is hidden by the keyboard (or maybe other menus on the bottom). Easily we can change this behavior adding a small setting to the Activity in the manifest.
Using the field android:windowSoftInputMode=”adjustResize” will do the work for us.
Code:
AndroidManifest.xml
1 2 3 4 5 6 | <!-- ... --> <activity android:name=".net.eridem.myapp.YourActivity" android:windowSoftInputMode="adjustResize"> </activity> <!-- ... --> |
Android tip #017 – Intercepting back button
Platform/Language: Java/XML/Android
Description: In order to intercept the BACK button and other buttons (without include HOME button), we need to override the method dispatchKeyEvent in our Activity. Another way to do that is overriding the method onBackButton()
Code:
YourActivity.java
1 2 3 4 5 6 7 8 9 10 | @Override public boolean dispatchKeyEvent(KeyEvent event) { // Handling the back button if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) { this.showQuitDialog(); return true; } else { return super.dispatchKeyEvent(event); } } |
YourActivity.java
1 2 3 4 | @Override public void onBackPressed() { this.showQuitDialog(); } |
Android tip #016 – Use custom fonts
Platform/Language: Java/XML/Android
Description: In order to use custom fonts in some Views, we need to import the font files to the folder /assets/font/ and apply the typeface to the View (not all views support it, some examples are TextView, Button, RadioButton, and so on). Here an easy example using Arial.ttf
Code:
In our file structure
1 | /assets/font/Arial.ttf |
YourActivity.java
1 2 3 4 5 | Typeface fontResource = Typeface.createFromAsset( context.getAssets(), "font/Arial.ttf"); TextView textView = (TextView) this.findViewById(R.id.tv1); textView.setTypeface(fontResource); |
Android tip #015 – Drawable to Bitmap (and vice versa)
Platform/Language: Java/XML/Android
Description: this code convert a Bitmap to Drawable and vice versa. It is useful when we are working with graphics.
Code:
MyActivity.java
1 2 3 4 5 6 7 8 9 10 11 | private Bitmap drawableToBitmap(Drawable drawable) { if (drawable == null) return null; return ((BitmapDrawable)drawable).getBitmap(); } private Drawable bitmapToDrawable(Bitmap bitmap) { if (bitmap == null) return null; return new BitmapDrawable(bitmap); } |
Android tip #014 – Multi-language application
Platform/Language: Java/Android
Description: if we need to create an application that supports different languages, we need to create different folders for values for different languages. Here an example of English (default), Spanish (es) and Swedish (sv). The language is selected automatically using the system language.
Code:
Different folders inside /res/
1 2 3 | /res/values/strings.xml /res/values-es/strings.xml /res/values-sv/strings.xml |
English /res/values/strings.xml
1 2 3 4 | <?xml version="1.0" encoding="utf-8"?> <resources> <string name="hello">Hello</string> </resources> |
Spanish /res/values-es/strings.xml
1 2 3 4 | <?xml version="1.0" encoding="utf-8"?> <resources> <string name="hello">Hola</string> </resources> |
Swedish /res/values-sv/strings.xml
1 2 3 4 | <?xml version="1.0" encoding="utf-8"?> <resources> <string name="hello">Hej</string> </resources> |
YourActivity.java
1 2 3 4 5 6 7 8 | /* ... */ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String helloString = this.getString(R.id.hello); } /* ... */ |
Android tip #013 – Gradient backgrounds
Platform/Language: XML/Android
Description: we can create easily backgrounds with XML drawables. In this example, we will create a new resource on the folder “drawables” that will contain a gradient and we will apply it to one of our layouts.
Code:
my_gradient.xml
1 2 3 4 5 6 7 8 9 10 | <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <gradient android:angle="90" android:startColor="#FFFD7E00" android:endColor="#FFF4322A" android:type="linear" /> </shape> |
your_layout.xml
1 2 3 4 5 6 7 8 | <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/my_gradient"> </LinearLayout> |
Android tip #012 – Saving and loading preferences
Platform/Language: Java/Android
Description: save and load preferences on Android is quite easy. You can save primitive values as Key-Value. SharedPreferences class on android is very useful to save states on Android.
Code:
YourActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | private static final String PREFS_NAME = "preferences"; private static final String PREF_USERNAME = "pref_username"; /* ... */ private final String yourDefaultUsernameValue = ""; private String yourUsernameValue; /* ... */ private void savePreferentes(Context context) { SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_APPEND); SharedPreferences.Editor editor = settings.edit(); // Edit and commit editor.putString(PREF_USERNAME, yourUsernameValue); editor.commit(); } private void loadPreferences(Context context) { SharedPreferences settings = getSharedPreferences(PREFS_NAME, Context.MODE_APPEND); // Get value yourUsernameValue = settings.getString( PREF_USERNAME, yourDefaultUsernameValue); } |
Android tip #011 – Update user interface from a thread
Platform/Language: Java/Android
Description: with the class Handler, you can throw a Runnable class (a intended to be executed by a thread) and furthermore, you can update the user interface. On this code, we implements Runnable in our own Activity and we override the method run.
Code:
YourActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public class YourActivity extends Activity implements Runnable { @Override public void onCreate(Bundle savedInstanceState) { // ... // Throw new thread new Handler().postDelayed(this, 100); } @Override public void run() { // This is the method caught by the handler // and it is running in a thread. /* You can update the interface on here */ } } |

