Wednesday, 29 October 2014

Checking the bits in Java

To check a certain bit in the position n is enabled or not, the follow sentence could be used:

boolean isBitNEnabled = (data & (1 << n) != 0)

For instance, the follow code could be used to check if the second bit is enabled or not.

boolean isBit2Enabled = (data & (1 << 2) != 0)


Friday, 3 October 2014

The 8 golden rules of interface design

1. Strive for consistency.
Consistent sequences of actions should be required in similar situations; identical terminology should be used in prompts, menus, and help screens; and consistent color, layout, capitalization, fonts, and so on should be employed throughout. Exceptions, such as required confirmation of the delete command or no echoing of passwords, should be comprehensible and limited in number.

2. Cater to universal usability.
Recognize the needs of diverse users and design for plasticity, facilitating transformation of content. Novice to expert differences, age ranges, disabilities, and technological diversity each enrich the spectrum of requirements that guides design. Adding features for novices, such as explanations, and features for experts, such as shortcuts and faster pacing, can enrich the interface design and improve perceived system quality.

3. Offer informative feedback.
For every user action, there should be system feedback. For frequent and minor actions, the response can be modest, whereas for infrequent and major actions, the response should be more substantial. Visual presentation of the objects of interest provides a convenient environment for showing changes explicitly.

4. Design dialogs to yield closure.
Sequences of actions should be organized into groups with a beginning, middle, and end. Informative feedback at the completion of a group of actions gives operators the satisfaction of accomplishment, a sense of relief, a signal to drop contingency plans from their minds, and an indicator to prepare for the next group of actions. For example, e-commerce web sites move users from selecting products to the checkout, ending with a clear confirmation page that completes the transaction.

5. Prevent errors.
As much as possible, design the system such that users cannot make serious errors; for example, gray out menu items that are not appropriate and do not allow alphabetic characters in numeric entry fields. If a user makes an error, the interface should detect the error and offer simple, constructive, and specific instructions for recovery. For example, users should not have to retype an entire name-address form if they enter an invalid zip code, but rather should be guided to repair only the faulty part. Erroneous actions should leave the system state unchanged, or the interface should give instructions about restoring the state.

6. Permit easy reversal of actions.
As much as possible, actions should be reversible. This feature relieves anxiety, since the user knows that errors can be undone, and encourages exploration of unfamiliar options. The units of reversibility may be a single action, a data-entry task, or a complete group of actions, such as entry of a name-address block.

7. Support internal locus of control.
Experienced users strongly desire the sense that they are in charge of the interface and that the interface responds to their actions. They don’t want surprises or changes in familiar behavior, and they are annoyed by tedious data-entry sequences, difficulty in obtaining necessary information, and inability to produce their desired result.

8. Reduce short-term memory load.
Humans’ limited capacity for information processing in short-term memory (the rule of thumb is that we can remember "seven plus or minus two chunks" of information) requires that designers avoid interfaces in which users must remember information from one screen and then use that information on another screen. It means that cell phones should not require re-entry of phone numbers, web-site locations should remain visible, multiple-page displays should be consolidated, and sufficient training time should be allotted for complex sequences of actions.


Saturday, 27 September 2014

Adding Picasso on Android Studio

Picasso is a tool to load the image into an image view. It is special useful for images which should be downloaded from the internet. It is like Universal Image Loader, but personally I had problem with Universal Image Loader with small images, so I prefer to use Picasso.

In order to start to use Picasso in Android Studio you must add it into dependencies. Just add the follow line in the dependencies section of you build.gradle file.

    compile group:'com.squareup.picasso', name:'picasso', version:'2.3.4'


More information:

Friday, 12 September 2014

Android - Are we in the main thread

The main thread of Android is taking care of the interaction with the user and it shouldn't be used for time consuming tasks. For those tasks, they should be run in a separate thread.

But for some specific tasks which are related with changes on the UI, they must be executed on the main thread. Otherwise the app could crash due to an exception.

To avoid this problem, it could be good to check if the running thread is the main thread or not. To do so, execute the follow sentence.  

    Looper.myLooper() == Looper.getMainLooper()

Or you can use:

    if (Thread.currentThread() != Looper.getMainLooper().getThread()) {
        return true;


Monday, 16 June 2014

Jekins and Android - Dependencies between jobs

If several code of the same project are stored in different repositories, such as the case of libraries, several jobs must be created since each job can only retrieve the code from on repository. In this case, there is a special way to execute the jobs related.

I am going to use an example to show this. Let's say we have a project called Main in the repository 1. This project depends on a library called library1 stored in the repository 2.

1. Configure the project.
In the project.profile of the project Main, it must have a relative path to the library1 directory IN JENKINS, not in the local computer. This could be the content:


where "Library1" is the name of the job which is related with library1 configured in Jenkins.

Note that there are two levels "up"s. The first one is because the actual directory is in the folder workspace inside of the actual job, the second one is used to go back to the job level, where all the jobs have their own folder.

Once there, it goes to the job "Library1" and inside that folder, the folder workspace, where the data of the last stable compilations goes.

Now commit (and push) the changes to the repository.

2. Download this plugin for Jenkins, which is used to execute one project after another:

3. Creates a new project of build flow
3.1 On the home screen of Jenkins, click on new job
3.2 Enter the name of the job. Select the type of job as "Build Flow"
3.3 In the config of the project, under "Execution trigger", there will be a special windows called "Define build flow using flow DSL". Enter the follow lines


Where Main is the name of the job in Jenkins which is related with the project Main.

StackOverFlow - Ant Build Android Project with Dependencies

Monday, 26 May 2014

Android - Hide and show textView

In android, when a text is quite big, it could be hidden and when you click on it, show the text.

1. Hide
To hide the text, the easier way is by using the attribute MaxLines and ellipsize to the end.

2. Show
Once the text has been hidden, if by any action of the user you wan to show the entire text, you should do the follow:

TextView completeDescriptionTextView = (TextView)findViewbyid(;
// The ellipsize must be set as null for android 2.3                                                          

3. Extra
In order to detect if the textview has been ellipsized, this works:
private boolean hasBeenEllipsized(TextView textView) {
    Layout layout = completeDescriptionTextView.getLayout();
    // If it contains layouts                                                                                                     
    if (layout != null) {
        int lines = layout.getLineCount();
        // Check if it contains text                                                                                                      
        if (lines > 0) {
            // Check if the last line has been elipsized                                                                                  
            if (layout.getEllipsisCount(lines-1) > 0)
                return true;
        return false;

StackOverFlow - How to reset Android textview Maxlines
StackOverFlow - Check if textview is ellipsized in android

Wednesday, 21 May 2014

Action bar - Back to the home screen

In the action bar, native or ActionBar Sherlock, there are several way to create the up button and set it to come back to the previous screen. Here I have listed them.

Mainly there are two groups: natives and not natives. For each one of them, there could be static back and dynamic back

1. Native Back to home
For new version of Android, it comes with native action bar. It appears from Android 3.0.x HoneyComb (API 11). All the version of Android which is previous to HoneyComb cannot use the native ActionBar.

1.1 Dynamic Back to home
To add dynamically the back to home function, no extra manifest code need to be added. Instead, the java code should be used:

First of all, the home button must be called in the onCreate method

// Display the up button

Then, the code must override the method onOptionsItemSelected when the item id is

public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == {
        // Back to the previous activity
       return true;
    } else {
        return super.onOptionsItemSelected(item);

Note I have used the notation @SuppressLint("NewApi") to avoid the error of new api because the min API of the example is 8, so the user cannot use this function on devices with API previous to 11, even when you can install this app on it.

1.2 Static Back to home
To create the static back to home the coder just have to add the follow code in the Android manifest file, following by the declaration of the activity.


For example, if my activity is called "NativeStaticBackActivity" and the home activity is called "HomeActivity", this would be the code in the manifest.

    android:parentActivityName="com.jiahaoliuliu.backtohome.HomeActivity" ></activity>

Check this example for more information:

2. Not native Back to home
The problem about the native back to home is the minimum API required is 11. If you want your app to run on devices of previous versions, you must use an externa action bar.

For this example, I have used the ActionBarSherlock, a wonderful lib created by Jake Wharton, from Square.

2.1 Dynamic Back to home
The case of dynamic back to home is the same as the dynamic back to home for native action bar. First you should ask the action bar to show the up icon by adding the follow code into onCreate method:

// Display the up button

And then, override the method onOptionsItemSelected as follow:

public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == {
        // Back to the previous activity
       return true;
    } else {
        return super.onOptionsItemSelected(item);

You can find an example here:

2.2 Static Back to home
In this case, both XML code in Android Manifest file and java code should be added.

2.2.1 Android manifest
The first thing to add is the same as the native action bar: The parent activity name.


The second thing is a metadata before close the activity of where the parent is

    android:value="com.jiahaoliuliu.backtohome.HomeActivity" />

2.2.2 Java code
First, the code must ask the action bar to show the up button for devices with API lower than 11:

// Display the up button

Second, the method onOptionsItemSelected must be overridden again. Note that this time the code is using the method navigateUpFromSameTask of the class This is what the android developer page states:

To navigate up when the user presses the app icon, you can use the NavUtils class's static method,navigateUpFromSameTask(). When you call this method, it finishes the current activity and starts (or resumes) the appropriate parent activity. If the target parent activity is in the task's back stack, it is brought forward as defined by FLAG_ACTIVITY_CLEAR_TOP.

public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == {
        return true;
    return super.onOptionsItemSelected(item);

You can find an example here:


The action bar has stablished as a pattern for mobile apps, such as Drawer or Sliding menus. It is very important to provide a clean up navigation to not confuse the user.

The use of static back to home method is good if from one activity it just goes to one specific activity. Other wise, if one activity is called by several different activities, it is better use the dynamic back to home method because it is impossible to do it with static back to home method.

Also the minimum API supported by the native action bar is 11, which means if you want to reach most of the people (at the time of writing there are still nearly 17% of the users who has a device with API lower than 11), an external library must be used. I have used ActionBarSherlock, but the new ActionBar compat could be used too.

You can find the example here:

For more information: