Introducing SectionedActionBarList

This Android library allows you to replace the drop down navigation list with a custom list where the items in the list are grouped by sections. It was inspired from the Google I/O 2014 app how sessions are grouped in the ActionBar list.

While the new Material Design movement discourages the use of ActionBar lists, in some situations it can be the best available option.

At the moment the library is not available on a repository, you have to include it as a source library in your project, but that will be fixed soon.

Github project page: https://github.com/vgrec/SectionedActionBarList

Example
List
<Section> sections = new ArrayList
<Section>();
 
Section themes = new Section("Themes");
themes.add("Design");
themes.add("Develop");
themes.add("Distribute");
sections.add(themes);
 
Section topics = new Section("Topics");
topics.add("Android");
topics.add("Chrome / Web");
topics.add("Cloud Services");
topics.add("Media");
topics.add("Location");
topics.add("Performance");
sections.add(topics);
 
Section types = new Section("Types");
types.add("Sessions");
types.add("App Reviews");
types.add("Box Talks");
sections.add(topics);
 
SectionedActionBarList actionBarList = new SectionedActionBarList(this).from(sections);
actionBarList.setItemSelectedListener(new ItemSelectedListener() {
  @Override
  public void onItemSelected(AdapterView<?> parent, View view, int position, long id, String sectionName, String itemName) {
      Toast.makeText(MainActivity.this, "Section: " + sectionName + ", Item: " + itemName, Toast.LENGTH_LONG).show();
  }
});

The SectionedActionBarList accepts a list of sections List<Section> sections, and every Section has a name and some associated items.

sectioned actionbar list

Configuration

Small customizations can be done to fit with your application design:

ListConfiguration configuration = new ListConfiguration(this);
configuration.setActionBarItemColorResource(R.color.brown);
configuration.setIndicatorDrawableResource(R.drawable.spinner_indicator_dark);
configuration.setSectionTitleColorResource(R.color.teal);
configuration.setDropdownItemColorResources(R.color.light_blue, R.color.dark_grey);

SectionedActionBarSpinner actionBarSpinner = new SectionedActionBarSpinner(this, configuration).from(sections);
// ....

actionbar list

Thanks to Webucator, a provider of Android classes, for producing the below video illustrating the integration of the SectionedActionbarList.


Advertisement

Android Volley Tutorial

Volley is an android library released by Google that can make your life easier when dealing with network operations. In this blog post I will mention the main features of the library and show a few example usages, in particular, how to make a request, how to download images, and how to use the cache.

Features of Volley library

a) Automatically schedules the network requests

b) Supports request prioritization. This means that you can load content depending of priorities, for example the main content could have a high priority, but the images a low priority.

c) Provides transparent disk and memory cache that allows for quick reloading of data. Transparent cache means that the caller doesn’t have to know about the existence of the cache. That is, the cache is implemented automatically. You do, however, have the possibility to disable the caching.

d) Provides a good API for canceling requests. You can cancel a single request, or cancel requests depending on some filters.

Besides the great features that Volley comes with, you don’t have to use it for everything. Volley is great for RPC-style network operations that populate UI, a typical example would be loading thumbnail images into a ListView, but not very good for streaming operations like downloading a video or mp3.

Getting started with Volley

1. Clone the Volley project:
git clone https://android.googlesource.com/platform/frameworks/volley
2. Import the library into your project

The most frequent classes of Volley that you will work with are RequestQueue and Request, and ImageLoader when dealing with images loading.

RequestQueue is used for dispatching requests to the network. It is recommended to create it early and use it as a Singleton.
Request is the base class for creating network requests (GET, POST).
ImageLoader is a helper class that handles loading and caching images from remote URLs.

Step 1: VolleySingleton.java

As recommended, lets create first a Singleton class that will return on demand an instance of RequestQueue and one of ImageLoader.

public class VolleySingleton {

    private static VolleySingleton instance;
    private RequestQueue requestQueue;
    private ImageLoader imageLoader;

    private VolleySingleton(Context context) {
        requestQueue = Volley.newRequestQueue(context);

        imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() {
            private final LruCache<String, Bitmap> cache = new LruCache<String, Bitmap>(20);


            @Override
            public Bitmap getBitmap(String url) {
                return cache.get(url);
            }

            @Override
            public void putBitmap(String url, Bitmap bitmap) {
                cache.put(url, bitmap);
            }
        });
    }


    public static VolleySingleton getInstance(Context context) {
        if (instance == null) {
            instance = new VolleySingleton(context);
        }
        return instance;
    }

    public RequestQueue getRequestQueue() {
        return requestQueue;
    }

    public ImageLoader getImageLoader() {
        return imageLoader;
    }
}
Step 2: Add internet permission
<uses-permission android:name="android.permission.INTERNET" /> 
Step 3: Create an instance of RequestQueue
RequestQueue queue = VolleySingleton.getInstance(this).getRequestQueue();
Step 4: Create the request

Volley comes with a class called JsonRequest that you can use to make requests to a server that returns a json response.
However, in this example we will query an RSS feed which returns a response in XML format. Volley does not include a similar class for handling xml responses, like JsonRequest, but it has StringRequest class that can be used to retrieve the response body as a String.

There are two ways to construct a StringRequest:

StringRequest(int method, String url, Listener<String> listener,
            ErrorListener errorListener)

or

StringRequest(String url, Listener<String> listener, ErrorListener errorListener)

The second constructor does not take the request method as a parameter, when not specified, a GET request is created.

Listener is a callback interface for delivering the result, and
ErrorListener is a callback interface for delivering error responses.

Example:

String url = "http://www.pcworld.com/index.rss";
StringRequest request = new StringRequest(url, new Listener<String>() {

            @Override
            public void onResponse(String response) {
                // we got the response, now our job is to handle it 
                parseXmlResponse(response); 
            }
        }, new ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
               //something happened, treat the error.
            }
        });
Step 6: Execute the request
queue.add(request);

And that is all! The execution of the request implies its addition to the RequestQueue.

Step 7: Loading thumbnail images

Loading images can be done easy if you replace the android’s ImageView with Volley’s NetworkImageView:

<com.android.volley.toolbox.NetworkImageView
        android:id="@+id/icon"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:src="@drawable/default_placeholder" />

then use setImageUrl() and you are done!

String url = "..."; // URL of the image
ImageView imageView = (ImageView)view.findViewById(R.id.image);
ImageLoader imageLoader = VolleySingleton.getImageLoader(); 
imageView.setImageUrl(url, imageLoader); 

If, for some reason, you don’t want or can’t use NetworkImageView, then there’s an alternate method.
You can use the get() method of ImageLoader class which accepts the image url and an instance of ImageListener:

ImageLoader imageLoader = VolleySingleton.getImageLoader(); 
imageLoader.get(url, new ImageListener() {
             
            public void onErrorResponse(VolleyError error) {
                imageView.setImageResource(R.drawable.icon_error); // set an error image if the download fails
            }
             
            public void onResponse(ImageContainer response, boolean arg1) {
                if (response.getBitmap() != null) {
                    imageView.setImageBitmap(response.getBitmap());
                } 
            }
        });
Reading from cache

One of the Volley’s features is that it provides transparent disk and memory cache. The cache is implemented automatically for classes that extends Request, such as JsonRequest and StringRequest.

To read the cache:

Entry entry = queue.getCache().get(url);
if(entry!=null){
     String data = new String(entry.data, "UTF-8");
     // process data
}

To turn off the cache:

request.setShouldCache(false);

to remove the cache for a specific request:

queue.getCache().remove(url);

to clear all cache:

queue.getCache().clear();

to invalidate the cache: this will allow to display the cached data until the response is received. When the response is received, it will automatically override the cached data.

queue.getCache().invalidate(url, true);

For more details about Volley you can watch the full video at: https://developers.google.com/events/io/sessions/325304728

Google Maps API V2 Android Tutorial

In this tutorial we will walk through the process of integrating Google Maps API V2 into an Android project.

(Source code available on GitHub)

Android Google Maps API V2

The necessary steps in order to integrate the Google Maps V2 are :

1. Install Google Play services

The version 2 of Google Maps now is part of the Google Play services SDK, that is why google-play-services lib should be installed first.

Start the Android SDK Manager and choose to install Google Play services from the Extras category:
android sdk manager

After the sdk manager completes the installation, go to <android_sdk_folder>/extras/google/google_play_services/libproject and copy the google-play-services_lib to the location where you maintain your Android projects.

Then import the library project into your workspace, and reference it in your Android project.

2. Get the Google Maps API Key

In order to use Google Maps API in your project you need a valid Google Maps API key. The key can be obtained via the Google APIs Console. You will have to provide the SHA-1 fingerprint and the package name of your application.

Please note that if you already hold a map key from the Google Maps Android V1, also known as MapView, you still will need get a new API key, as the old key won’t work with the V2 API.

2.1 Generate SHA-1 certificate fingerprint

To display the SHA-1 fingerprint, first you need to decide for what type of certificate do you need to generate the fingerprint: for the debug certificate, or for the release certificate.
In this example we well consider displaying the fingerprint for the debug certificate.

The file name of debug certificate is called debug.keystore, and it is located on C:\Users\your_user_name\.android\ on Windows, and on ~/.android/ on Linux.

If you are on a Linux, open the terminal and run the following command:
keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android

If you are on a Windows, open the command prompt and run this:
keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android

Copy the SHA1 fingerprint and store it somewhere for later use.
android sha1 certificate fingerprint

(Note that if the command prompt complains that keytool is not a recognizable command, you can find it your java JDK/bin folder. cd there and run the command from that folder.)

2.2 Create an API Project

Navigate to Google APIs Console and create a new project, if you haven’t used Google APIs Console before. Then click on the Services link from the left menu:
google services

and from the presented list of of services toggle Google Maps Android API V2:
google maps android api v2

(Please make sure you namely select “Google Maps Android API V2”, not Google Maps API v2, nor Google Maps API v3)

2.3 Obtain an API Key

a) From the left menu click on API Access
b) Then click on Create New Android Key
c) In the resulting dialog, enter the SHA-1 fingerprint, followed by a semicolon, and then your application package name.
For example:
95:F7:64:E9:3D:D44:70:EF:CB:F9:D9:14:BF:72:88:B4:E8:D7:11:E9;com.example.mapsv2

As a result the page displays a new section entitled Key for Android apps (with certificates), followed by your API key that looks something like this:
AIzaZyAcQKLEyHsamGpNLHdn8wd5-wuCqBnJ3Rk

2.4 Add the API key to AndroidManifest file

Open the AndroidManifest file and add the following element as a child of application tag:

<meta-data
    android:name="com.google.android.maps.v2.API_KEY"
    android:value="YOUR_API_KEY"/>

replacing the YOUR_API_KEY with your real API key.

3. Update the AndroidManifest file with other settings

In order to use Google Maps Android API we need to declare a few permissions and specify that the application requires OpenGL ES version 2:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    //... >

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    
    //...
</manifest>
4. Display a MapFragment

Displaying the maps is as simple as declaring a fragment in the xml layout with the name com.google.android.gms.maps.MapFragment.
If you would like to make your application compatible with older devices, then you’ll have to use the Android Support Library and reference SupportMapFragment instead of MapFragment. The below example uses the Android Support Library.

The activity_main.xml layout:

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/maps_fragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:name="com.google.android.gms.maps.SupportMapFragment" />

and the MainActivity.java:

public class MainActivity extends FragmentActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}
}

If everything was configured correctly, then when running this example you should see a map.

Full source code can be downloaded from GitHub: https://github.com/vgrec/MapsV2Example

Example using ViewPager with ActionBarSherlock tabs

In this post I’m going to show you an example usage of ViewPager in conjunction with ActionBarSherlock tabs.
The final result should look like this:

ActionBar with ViewPager

1. Add the ActionBarSherlock library to your project. (Here’s a short tutorial on how to integrate ABS with a project, in case you need a refresh on this)

2. Change the AndroidManifest file of your project to use one of the predefined themes by ABS:

<application       
        //....
        android:theme="@style/Theme.Sherlock.Light" >
        //.....
</application>

Note that using ActionBarSherlock requires you to use one of these themes: Theme.Sherlock, Theme.Sherlock.Light, Theme.Sherlock.Light.DarkActionBar, or any other derivate, otherwise a RuntimeException exception will be thrown.

3. Create the MainActivity.java:

public class MainActivity extends SherlockFragmentActivity {

	private ActionBar actionBar;
	private ViewPager viewPager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		viewPager = (ViewPager) findViewById(R.id.pager);
		viewPager.setOnPageChangeListener(onPageChangeListener);
		viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));
		addActionBarTabs();
	}

	private ViewPager.SimpleOnPageChangeListener onPageChangeListener = new ViewPager.SimpleOnPageChangeListener() {
		@Override
		public void onPageSelected(int position) {
			super.onPageSelected(position);
			actionBar.setSelectedNavigationItem(position);
		}
	};

	private void addActionBarTabs() {
		actionBar = getSupportActionBar();
		String[] tabs = { "Tab 1", "Tab 2", "Tab 3" };
		for (String tabTitle : tabs) {
			ActionBar.Tab tab = actionBar.newTab().setText(tabTitle)
					.setTabListener(tabListener);
			actionBar.addTab(tab);
		}
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
	}

	private ActionBar.TabListener tabListener = new ActionBar.TabListener() {
		@Override
		public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
			viewPager.setCurrentItem(tab.getPosition());
		}

		@Override
		public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
		}

		@Override
		public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
		}
	};
}

Another requirement in order to use Sherlock library is that your activity should extend from SherlockFragmentActivity, and this is what MainActivity does first.
Then it takes a reference to the ViewPager and sets the OnPageChangedListener and the PagerAdapter (implementation will be shown below):

viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setOnPageChangeListener(onPageChangeListener);
viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));

In short, a ViewPager is a layout manager that allows you to swipe left and right through pages of data.
It needs to be supplied with an implementation of PagerAdapter in order to generate the pages that the view shows.

Just below the initialization of ViewPager the action bar tabs are added:

private void addActionBarTabs() {
	actionBar = getSupportActionBar();
	String[] tabs = { "Tab 1", "Tab 2", "Tab 3" };
	for (String tabTitle : tabs) {
		ActionBar.Tab tab = actionBar.newTab().setText(tabTitle)
				.setTabListener(tabListener);
		actionBar.addTab(tab);
	}
	actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
}

For every string in the tabs[] array a new ActionBar.Tab is created and added to the ActionBar.

4. And the layout of MainActivity, R.layout.activity_main, which simply defines the ViewPager container.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

5. The implementation of ViewPagerAdapter.java:

public class ViewPagerAdapter extends FragmentStatePagerAdapter {

    private final int PAGES = 3;

    public ViewPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return new TabFragment1();
            case 1:
                return new TabFragment2();
            case 2:
                return new TabFragment3();
            default:
                throw new IllegalArgumentException("The item position should be less or equal to:" + PAGES);
        }
    }

    @Override
    public int getCount() {
        return PAGES;
    }
}

The PagerAdapter helps represent each page as a Fragment.
By extending FragmentStatePagerAdapter two methods should be overrided:
getCount() – which returns the total number of pages the ViewPager will have, and
getItem() – which returns a new fragment for each page.

6. Bellow follows the fragment classes used for representing each page. The minimalistic implementation is to extend from SherlockFragment, and provide a view for the fragment itself.
TabFragment1.java:

public class TabFragment1 extends SherlockFragment {

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_tab_1, container, false);
	}
}

TabFragment2.java:

public class TabFragment2 extends SherlockFragment {

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_tab_2, container, false);
	}
}

TabFragment3.java:

public class TabFragment3 extends SherlockFragment {
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_tab_3, container, false);
	}
}

7. And their corresponding layout files, which in this particular example have just a single TextView element.
fragment_tab_1.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Fragment tab 1" />

</RelativeLayout>

fragment_tab_2.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Fragment tab 2" />

</RelativeLayout>

fragment_tab_3.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Fragment tab 3" />

</RelativeLayout>

Full project can be found on github: https://github.com/vgrec/SherlockActionBarTabs

Using Maven to save the build time in a properties file

Create a folder called build in the root directory of the project, and a file build.properties with the following content:

build.time=@buildtime@

Using the maven replacer plugin we can replace the token @buildtime@ within the build.properties file with the build timestamp value, and then let the Android application read that value and use it.

 
<plugins>
     <plugin>
         <groupId>com.google.code.maven-replacer-plugin</groupId>
         <artifactId>replacer</artifactId>
         <version>1.5.2</version>
         <executions>
            <execution>
               <phase>validate</phase>
               <goals>
                  <goal>replace</goal>
               </goals>
            </execution>
         </executions>
         <configuration>
            <file>build/build.properties</file>
               <outputFile>res/raw/build.properties</outputFile>
               <replacements>
                  <replacement>
                     <token>@buildtime@</token>
                     <value>${maven.build.timestamp}</value>
                  </replacement>
               </replacements>
        </configuration>
   </plugin>
</plugin>

Run this task with mvn validate command. This will do nothing but replace the tokens from build.properties file with the timestamp value, and output the result to a new file in res/raw.

From here on the file can be accessed as a raw resource and read as a regular properties file.

Reading the properties file:

InputStream rawResource = resources.openRawResource(R.raw.build);
Properties properties = new Properties();
properties.load(rawResource);
String buildTime = properties.getProperty("build.time");

Using Maven in Android to build for different environments (dev, staging, prod, etc)

If you are working on a relatively complex project, chances are that you may need to build the application against different environments, such as a development, a staging, and a production environment. Assuming you are using Maven as a build tool, here’s one solution how Maven could help with this.

For the sake of this example let assume that you are working on an Android app that consumes web services. You have a dedicated development environment where you spent most of the time, but once every two weeks you need to make a version of the app that is built for production.

Let assume that the endpoint for the testing environment is dev.mysite.com, and for the production environment is: prod.mysite.com.
But as an aspiring developer and after reading a bunch of books about best practices, you can no longer accept to just go and manually edit the source files by changing all over the place one environment with another, and you ask yourself if Maven could help with this.

It can, and here’s how.
The main idea is to store all the properties, in this particular example all the urls, in separate resource files. Then, using maven resource plugin copy the corresponding property file into values/environment.xml.

1. In your project root directory create following directory structure:
environment/dev/environment.xml
environment/prod/environment.xml

maven environment

2. Then fill the content of the resource files with appropriate values.
/dev/environment.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="url">http://dev.mysite.com</string>
</resources>

/prod/environment.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="url">http://prod.mysite.com</string>
</resources>

3. Add the maven resource plugin to pom.xml by specifying the phase when the copy action should be executed, the resources, and the output directory:

//...
<plugins>
    <plugin>
        <artifactId>maven-resources-plugin</artifactId>
        <version>2.4.3</version>
        <executions>
             <execution>
                <id>copy-string-resources</id>
                <phase>validate</phase> <!-- when to execute copy operation -->
                <goals>
                    <goal>copy-resources</goal>
                </goals>
                <configuration>
                    <resources>
                        <resource>
                            <directory>environment/${environment}/</directory>
                            <includes>
                               <include>environment.xml</include>
                               <filtering>true</filtering>
                            </includes>
                        </resource>
                    </resources>
                    <overwrite>true</overwrite>
                    <outputDirectory>${basedir}/res/values/</outputDirectory>
                </configuration>
      </plugin>
</plugins>

4.1 From this point on, you can automate the preparation of environment by creating 2 run configurations:
mvn validate -Denvironment=dev
mvn validate -Denvironment=prod

that will do nothing but copy the appropriate resources from evironment/${environment}/environment.xml, into values/environment.xml

Now, every time you’ll need to prepare a build against a specific environment, the only thing you’ll need to do will be to run one of those commands.

4.2 Another option, to make the things even more compact, is instead of passing the environment like this: -Denvironment=dev, would be to create 2 profiles in pom.xml:

<profiles>
   <profile>
       <id>development</id>
       <properties>
           <environment>dev</environment>
       </properties>
   </profile>

   <profile>
       <id>prod</id>
       <properties>
           <environment>prod</environment>
       </properties>
   </profile>
</profiles>

and then create 2 run configurations with appropriate profile:
mvn validate -P development
mvn validate -P prod

For easy access at environment resources you could create a class like this that will return all the environment properties your applications uses:

public class ApplicationEnvironment{
	
	//...
	
	public String getServerUrl(){
		return resources.getString(R.string.url);
	}	
}

Dealing with AsyncTask and Screen Orientation

A common task in Android is to perform some background activity in another thread, meanwhile displaying a ProgressDialog to the user. Example of these tasks include downloading some data from internet, logging into an application, etc. Implementing an AsyncTask is fairly a simple job, the big challenge is how to handle it properly when an orientation change occurs.

In this article I will walk though a series of potential solutions to address the screen orientation issues when using an AsyncTask.

So, lets create a proof of concept application that makes use of an AsyncTask which does not handle configuration changes yet, and then present a few solutions.

Here’s the AsyncTask implementation that we will be using during the tutorial:

public class AsyncTaskExample extends AsyncTask<String, Integer, String> {

	private final TaskListener listener;

	public AsyncTaskExample(TaskListener listener) {
		this.listener = listener;
	}

	@Override
	protected void onPreExecute() {
		listener.onTaskStarted();
	}

	@Override
	protected String doInBackground(String... params) {
		for (int i = 1; i <= 10; i++) {
			Log.d("GREC", "AsyncTask is working: " + i);
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		return "All Done!";
	}

	@Override
	protected void onPostExecute(String result) {
		listener.onTaskFinished(result);
	}
}

doInBackground() – this will be called by the AsyncTask on a background thread, and performs all the heavy work. For the sake of this example, I just wrote a simple loop  with a delay of 1 sec between iterations to simulate a task that takes some time.
– The constructor of the class takes a listener as a parameter. The listener will be used to delegate the work of onPreExecute()/onPostExecute() to the calling Activity.

This is the interface definition used by AsyncTaskExample:

public interface TaskListener {
	void onTaskStarted();

	void onTaskFinished(String result);
}

And here’s the usage of AsyncTaskExample (the problematic case):

public class MainActivity extends Activity implements TaskListener, OnClickListener {

	private ProgressDialog progressDialog;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		findViewById(R.id.start).setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.start) {
			new AsyncTaskExample(this).execute();
		}
	}

	@Override
	public void onTaskStarted() {
		progressDialog = ProgressDialog.show(CopyOfMainActivity.this, "Loading", "Please wait a moment!");
	}

	@Override
	public void onTaskFinished(String result) {
		if (progressDialog != null) {
			progressDialog.dismiss();
		}
	}
}

The Activity implements the TaskListener interface and provides appropriate implementation for its methods,  displaying the ProgressDialog when the task is started, and dismissing it when the task is finished. The AsyncTask is fired when clicking on a button.

Now, if you run this example without changing the screen orientation, the AsyncTask will start and finish its work normally. Problems begin to appear when the device orientation is changed while the AsyncTask is in the middle of the work. The application will crash, and an exception similar to these ones will be thrown: java.lang.IllegalArgumentException: View not attached to window manager, or Activity has leaked window com.android.internal.policy….

The cause relies in the Activity life cycle. A change in device orientation is interpreted as a configuration change which causes the current activity to be destroyed and then recreated. Android calls onPause(), onStop(), and onDestroy() on currently instance of activity, then a new instance of the same activity is recreated calling onCreate(), onStart(), and onResume(). The reason why Android have to do this, is because depending of screen orientation, portrait or landscape, we may need to load and display different resources, and only through re-creation Android can guarantee that all our resources will be re-requested.

But don’t panic, you are not alone, there are several solutions that will help us to deal with this situation.

Solution 1 – Think twice if you really need an AsyncTask.

AsyncTasks are good for performing background work, but they are bound to the Activity which adds some complexity. For things like making HTTP requests to a server perhaps you should consider an IntentService. IntentService used in conjunction with a BroadcastReceiver or ResultReceiver to deliver results, could do a better job than an AsyncTask in certain situations.

Solution 2 – Put the AsyncTask in a Fragment.

Using fragments probably is the cleanest way to handle configuration changes. By default, Android destroys and recreates the fragments just like activities, however, fragments have the ability to retain their instances, simply by calling: setRetainInstance(true), in one of its callback methods, for example in the onCreate().

There’s however one aspect that should be taken in consideration in order to achieve the desired result. Our AsyncTask uses a ProgressDialog to signal when the AsyncTask is started, and dismisses it when the task is done. This complicates a bit the things because even if we are using setRetainInstance(true), we should close all windows and dialogs when the Activity is destroyed, otherwise we will get an: Activity has leaked window com.android.internal.policy…  exception. This happens when you try to show a dialog after you have exited the Activity.

In order to address this issue, we will add some logic to keep track of AsyncTask status (running/not running). We will dismiss the ProgressDialog when the fragment is detached from activity, and check in onActivityCreated() the status of AsyncTask. If the status is “running”, this means we are returning from a screen orientation and we will just re-create and display the ProgressDialog to show that the AsyncTask is still working.

public class ExampleFragment extends Fragment implements TaskListener, OnClickListener {

	private ProgressDialog progressDialog;
	private boolean isTaskRunning = false;
	private AsyncTaskExample asyncTask;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setRetainInstance(true);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		// If we are returning here from a screen orientation
		// and the AsyncTask is still working, re-create and display the
		// progress dialog.
		if (isTaskRunning) {
			progressDialog = ProgressDialog.show(getActivity(), "Loading", "Please wait a moment!");
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_layout, container, false);
		Button button = (Button) view.findViewById(R.id.start);
		button.setOnClickListener(this);
		return view;
	}

	@Override
	public void onClick(View v) {
		if (!isTaskRunning) {
			asyncTask = new AsyncTaskExample(this);
			asyncTask.execute();
		}
	}

	@Override
	public void onTaskStarted() {
		isTaskRunning = true;
		progressDialog = ProgressDialog.show(getActivity(), "Loading", "Please wait a moment!");
	}

	@Override
	public void onTaskFinished(String result) {
		if (progressDialog != null) {
			progressDialog.dismiss();
		}
		isTaskRunning = false;
	}

	@Override
	public void onDetach() {
		// All dialogs should be closed before leaving the activity in order to avoid
		// the: Activity has leaked window com.android.internal.policy... exception
		if (progressDialog != null && progressDialog.isShowing()) {
			progressDialog.dismiss();
		}
		super.onDetach();
	}
}
Solution 3 – Lock the screen orientation

You could do this in 2 ways:

a) permanently locking the screen orientation of the activity, specifying the screenOrientation attribute in the AndroidManifest with “portrait” or “landscape” values:

<activity
   android:screenOrientation="portrait"
   ...  />

b) or, temporarily locking the screen in onPreExecute(), and unlocking it in onPostExecute(), thus preventing any orientation change while the AsyncTask is working:

@Override
public void onTaskStarted() {
	lockScreenOrientation();
	progressDialog = ProgressDialog.show(CopyOfCopyOfMainActivity.this, "Loading", "Please wait a moment!");
}

@Override
public void onTaskFinished(String result) {
	if (progressDialog != null) {
		progressDialog.dismiss();
	}
	unlockScreenOrientation();
}

private void lockScreenOrientation() {
	int currentOrientation = getResources().getConfiguration().orientation;
	if (currentOrientation == Configuration.ORIENTATION_PORTRAIT) {
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
	} else {
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
	}
}

private void unlockScreenOrientation() {
	setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
}
Solution 4 – Prevent the Activity from being recreated.

This is the easiest way to handle configuration changes, but the less advised. The only thing you need to do is to specify the configChanges attribute followed by a list of values that specifies when the activity should prevent itself from restarting.

<activity
   android:configChanges="orientation|keyboardHidden"
   android:name=".MainActivity"
   .... />

Using this approach however, is not recommended, and this is clearly stated in the Android documentation: Using this attribute should be avoided and used only as a last-resort.

You may ask what’s wrong with this approach. Well, if you build the above example against Android 2.2 it will work fine, but if you build it against Android 3.0 and higher, you may notice that the application still crashes on orientation change. This is because starting  with Android 3.0 you need also to handle the screenSize, and smallestScreenSize:

<activity
   android:configChanges="orientation|keyboardHidden|screenSize|smallestScreenSize"
   android:name=".MainActivity"
   .... />

As it turns out, not only a screen orientation causes the Activity to recreate, there are also other events which may produce configuration changes and restart the Activity, and there’s a good chance that we won’t handle them all. This is why the use of this technique is discouraged.

Caching Objects in Android Internal Storage

Android provides several options for persisting application data, such as SQLite Databases, SharedPreferences, internal and external storage.

In this post we’ll take a look how we can use the internal storage to persist application data. By default, files saved to internal storage are private to the application and they cannot be accessed by other applications. When the application is uninstalled, the files are removed.

To create and write a file to internal storage, openFileInput(); should be used. This opens a private file associated with the Context’s application package for writing. If the file does not already exits, then it is first created.

openFileInput() returns a FileInputStream, and we could use its write() method, which accepts a byte array as argument, to write the data. However, in the below example we will wrap the FileInputStream into an ObjectOutputStream which provides 2 convenient methods  for writing and reading objects: writeObject() and readObject().

So, lets  pretend that we need to save a List of some objects. The model class of our object looks like this:

public class Entry implements Serializable{
   private String name;

   public Entry(String name) {
      this.name = name;
   }

   public String getName() {
      return name;
   }
}

Make sure that the model class implements Serializable, otherwise you may get a java.io.NotSerializableException when attempting to write the object on internal storage.

Below is the utility class that provides 2 methods, one for storing objects to internal storage, and another for retrieving objects from internal storage.

public final class InternalStorage{

   private InternalStorage() {}

   public static void writeObject(Context context, String key, Object object) throws IOException {
      FileOutputStream fos = context.openFileOutput(key, Context.MODE_PRIVATE);
      ObjectOutputStream oos = new ObjectOutputStream(fos);
      oos.writeObject(object);
      oos.close();
      fos.close();
   }

   public static Object readObject(Context context, String key) throws IOException,
         ClassNotFoundException {
      FileInputStream fis = context.openFileInput(key);
      ObjectInputStream ois = new ObjectInputStream(fis);
      Object object = ois.readObject();
      return object;
   }
}

An this is how InternalStorage class can be used to persist and retrieve data from internal storage.

// The list that should be saved to internal storage.
List<Entry> entries = new ArrayList<Entry>();
entries.add(new Entry("House"));
entries.add(new Entry("Car"));
entries.add(new Entry("Job"));

try {
   // Save the list of entries to internal storage
   InternalStorage.writeObject(this, KEY, entries);

   // Retrieve the list from internal storage
   List<Entry> cachedEntries = (List<Entry>) InternalStorage.readObject(this, KEY);

   // Display the items from the list retrieved.
   for (Entry entry : cachedEntries) {
     Log.d(TAG, entry.getName());
   }
} catch (IOException e) {
   Log.e(TAG, e.getMessage());
} catch (ClassNotFoundException e) {
   Log.e(TAG, e.getMessage());
}

 

Taking a screenshot of current Activity in Android

In this post I’ll show how you can take a screenshot of your current Activity and save the resulting image on /sdcard.

The idea behind taking a screenshot actually is pretty simple: what we need to do is to get a reference of the root view and  generate a bitmap copy of this view.

screenshot

Considering that we want to take the screenshot when a button is clicked, the code will look like this:

findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
       Bitmap bitmap = takeScreenshot();
       saveBitmap(bitmap);
   }
});

 

First of all we should retrieve the topmost view in the current view hierarchy, then enable the drawing cache, and after that call getDrawingCache().

Calling getDrawingCache(); will return the bitmap representing the view or null if cache is disabled, that’s why setDrawingCacheEnabled(true); should be set to true prior invoking  getDrawingCache().

public Bitmap takeScreenshot() {
   View rootView = findViewById(android.R.id.content).getRootView();
   rootView.setDrawingCacheEnabled(true);
   return rootView.getDrawingCache();
}

 

And the method that saves the bitmap image to external storage:

 public void saveBitmap(Bitmap bitmap) {
    File imagePath = new File(Environment.getExternalStorageDirectory() + "/screenshot.png");
    FileOutputStream fos;
    try {
        fos = new FileOutputStream(imagePath);
        bitmap.compress(CompressFormat.JPEG, 100, fos);
        fos.flush();
        fos.close();
    } catch (FileNotFoundException e) {
        Log.e("GREC", e.getMessage(), e);
    } catch (IOException e) {
        Log.e("GREC", e.getMessage(), e);
    }
}

 

Since the image is saved on external storage, the WRITE_EXTERNAL_STORAGE permission should be added AndroidManifest to file:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Using Custom Fonts in Android

By default Android comes with three standard fonts: Droid Sans (default font), Droid Serif, and Droid Sans Mono. They all can be applied to any view that supports styling, such as TextView, Button, by specifying the “android:typeface” attribute in the XML declaration with any of these values: sans, serif, monospace.


<TextView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Sans"
   android:typeface="sans" />

<TextView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Serif"
   android:typeface="serif" />

<TextView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Monospace"
   android:typeface="monospace" />

android standard fonts

 

Using custom fonts in Android is pretty straightforward. First find a free font and put it in the assets/fonts directory. (It’s not mandatory to have a /fonts directory, but if I have a lot of stuff in the /assets directory I organize them in separate directories). Then get a reference to your TextView and create a Typeface object specifying the font path. Lastly, apply the typeface to the TextView.

In this particular example I used the font: christmaseve.ttf

TextView textView = (TextView) findViewById(R.id.textView);
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/christmaseve.ttf");
textView.setTypeface(tf);

android custom fonts

 

RuntimeException: Native typeface cannot be made

If you get this exception while trying to integrate the custom font into your application, make sure the path to the font file is correct, and the font name is spelled correctly. I noticed I was getting this exception when my font path was misspelled, for example writing “.tff” instead of “.ttf”, or forgetting to add the “fonts/” prefix to the path.

Custom font used in this example provided by: http://bythebutterfly.com