Category Archives: Développement

Some Gradle Tips for your Android development

As most of you know, Android released the beta of their new IDE called Android Studio (Check the Google I/O session to see why it is so much better that what you are currently using). With it comes the new Android SDK Build System (Same deal, here is the corresponding Google I/O session).
It was released a few weeks ago at Google I/O and it’s just awesome. A little more work that the current build system but so much more possibilities offered to us developers :)

The new build system is based on gradle. You can use it partly from Android Studio but as it’s often the case you may have to use it from the command line to do more complex tasks. Here are some tips if you use it from the command line.

For example to compile your project, you have to use gradle assemble. But you can also just write gradle a.
As long as there is no other task sharing the part you write after gradle, it will autocomplete it for you.

gradle check can therefore be reduced to gradle ch. You can’t reduce it to gradle c however as there is also gradle clean which also starts with a c

Ok. That’s a good start. But let’s make it even better.

Open a terminal and try the following command
$ g (Just a ‘g’, nothing else)
You should get the following output:
-bash: g: command not found
If you already have a command called g, you can use gr or gra instead

If that’s the case, go to your .bashrc file and add the following line:
alias g='gradle'

Open a new terminal so that the .bashrc is read again with the new line.
Now you just have to write g a

In 5 minutes we jumped from gradle assemble to g a

You still want more tips ?!
The gradle completion is camelCase based. Which means gradle deviceCheck can be reduced to g dC !

(Thanks +Xavier Ducrohet for showing me the completion part of these tips ^^)

ContentProviderCodeGenerator or how to create your ContentProviders easily

There are multiple ways to store data persistently in Android, like for example the SharedPreferences. One of them is to use a ContentProvider.

A ContentProvider is one of primary building blocks of Android applications, providing content to applications. You can for example use it to open some of your data to other applications.
You can also use it to just store your data and not export it to other applications (by setting the flag android:exported="false" in your Android Manifest).

Write your first ContentProvider can be a challenging task as there are a good number of methods to implement and it’s not always clear how to do it.
That was one of the reason why I released with DataDroid (my local and remote data management library) some skeletons explaining how to do it by just following a bunch of TODOs to follow.

However you still have a lot of code to write, most of it just being copy/paste all over the classes. And when you start having multiple versions of your ContentProvider with new columns or tables, it begins to be really annoying to have to maintain that…

Which brings us to ContentProviderCodeGenerator !!

Like every lazy software engineer, it was bothering me and so I took/found some time and wrote a code generator ! :)

You can find all the information on its GitHub page, but here is a short explanation :

  • You clone the repository and import the Java project in Eclipse (or your favorite IDE)
  • You write a JSON file defining your tables and their columns in the input folder. Examples are provided to learn the syntax
  • You run the project as a Java Project
  • All the needed files are “magically” generated in the output folder ready for you to copy them in your project

It’s really easy to use (and if needed I can help you)
It makes adding a column or a table so easy it’s not even funny.
It just works. (yes I know I just used an Apple slogan on an Android blog) (and if it doesn’t work, I’ll fix it)

Last important thing : the project license. As all my other projects, it is released under the Beerware license :

You can do whatever you want with this stuff. If we meet some day, and you think this stuff is worth it, you can buy me a beer in return.

TimePickerDialog and AM/PM vs 24 Hour format

Just a short article to maybe help other people not spend 1 hour searching the web for the answer like I did.

The Android SDK provides you with 2 really well made dialog pickers for respectively a date and a time : DatePickerDialog and TimePickerDialog.

The constructors for DatePickerDialog are pretty much straight-forward.
However the one for TimePickerDialog has a small problem :

As you can see in the screenshot above, you need to specify through the is24HourView parameter whether you want to display a time with hours from 0 to 23 (used in France and Germany for example) or you want to display a time with hours from 1 to 12 and also AM/PM selector (used in the USA for example).

The main problem is that I don’t want to choose that in my code. I want it to be linked to the user locale settings like everythink else.
I don’t want why it was coded like that but here is how to link this parameter to the user locale :

    new TimePickerDialog(this, mOnTimeSetListener, time.hour, time.minute, DateFormat.is24HourFormat(this));

The method is24HourFormat from DateFormat allows us to retrieve the user setting.

Small issue with ADT 20 and SDK 16 and how to fix it

The latest version of the Android Developer Tools (ADT) brought a lot of improvements for us developers. Sadly there is a little quirk coming with it too.

If you have a project targeting API 16/Jelly Bean and you are using ADT 20, you might have some problems with the Graphical Layout tool. Instead of displaying the UI, you may end up with the following screen :

The error message is java.util.LinkedHashMap.eldest()Ljava/util/Map$Entry; which is totally clear… or not.
By looking inside Eclipse, we can find the corresponding complete Stacktrace :

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
java.lang.NoSuchMethodError: java.util.LinkedHashMap.eldest()Ljava/util/Map$Entry;
	at android.util.LruCache.trimToSize(LruCache.java:206)
	at android.util.LruCache.evictAll(LruCache.java:306)
	at android.widget.SpellChecker.resetSession(SpellChecker.java:141)
	at android.widget.SpellChecker.setLocale(SpellChecker.java:147)
	at android.widget.SpellChecker.<init>(SpellChecker.java:112)
	at android.widget.Editor.updateSpellCheckSpans(Editor.java:461)
	at android.widget.Editor.onAttachedToWindow(Editor.java:212)
	at android.widget.TextView.onAttachedToWindow(TextView.java:4455)
	at android.view.View.dispatchAttachedToWindow(View.java:11755)
	at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2424)
	at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2424)
	at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2424)
	at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2424)
	at android.view.ViewGroup.dispatchAttachedToWindow(ViewGroup.java:2424)
	at android.view.AttachInfo_Accessor.setAttachInfo(AttachInfo_Accessor.java:37)
	at com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate(RenderSessionImpl.java:329)
	at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:331)
	at com.android.ide.common.rendering.LayoutLibrary.createSession(LayoutLibrary.java:325)
	at com.android.ide.eclipse.adt.internal.editors.layout.gle2.RenderService.createRenderSession(RenderService.java:372)
	at com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart.renderWithBridge(GraphicalEditorPart.java:1640)
	at com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart.recomputeLayout(GraphicalEditorPart.java:1391)
	at com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart.activated(GraphicalEditorPart.java:1165)
	at com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate.delegatePageChange(LayoutEditorDelegate.java:679)
	at com.android.ide.eclipse.adt.internal.editors.common.CommonXmlEditor.pageChange(CommonXmlEditor.java:359)
	at org.eclipse.ui.part.MultiPageEditorPart.setActivePage(MultiPageEditorPart.java:1067)

After some research, I found a temporary solution on StackOverflow until this bug is fixed in the next patch of ADT.

The problem seems to be linked to the use of EditText with suggestions in Jelly Bean. On a phone there is no problem but in the Graphical Layout tool it breaks.
We have 2 solutions :

  • Disable the suggestions in the EditText with the inputType textNoSuggestions
    • It fixes the bug but it prevents the users from using the completion in your app. So let’s forget about it and look at the other solution
  • Switch the Graphical Layout to a different API (for example ICS/15 which is nearly the same as JB in terms of UI)

To do that, you just need to use the little droid on the top right and switch to 15 as shown in the screenshot below.

And voila ! :)

Update :
Xavier Ducrohet (who is working on the ADT tool) replied to my post on Google + and told me that the issue doesn’t come from ADT 20 but from the rendering library of Jelly Bean. So if I understand right, we need to wait for an update of JB to have a fix.

Update 2 :
The fix is available in ADT 20.0.1 ! So update the following elements and it will be good :

  • ADT Plugin in version 20.0.1
  • Android SDK Tools 20.0.1
  • Android SDL 16 rev 2

If you don’t see them, clear the cache of the SDK manager in the options

How to add autocompletion to an EditText

Finally after months and months of saying that I would add development articles to my blog, here is the first one :)

EditText is a component that everybody knows and it is the primary way to get user input in an Android application.
What is really less known is its cousin : AutoCompleteTextView. It’s a subclass of EditText that allows you to display possible autocompletions to the user depending on what he/she already entered in the EditText.

This article will focus on how to use this component and how to bind different data sources to provide the completions.

1 – Presentation of AutoCompleteTextView and simple autocompletion

AutoCompleteTextView is used exactly the same way as an EditText in your layouts (as it’s a subclass of EditText). You just need to replace your EditText by an AutoCompleteTextView and this part is done !

Now that our layout is ready, let’s look at the code.

For this first example we are going to use a really simple example (based on the documentation of AutoCompleteTextView class in the Android SDK). The possible autocompletions are going to be a fixed list of countries.

1
2
3
4
5
6
7
8
private static final String[] COUNTRIES = new String[] {
	"Belgium", "France", "Italy", "Germany", "Spain"
};
 
// In the onCreate method
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.actv_country);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, COUNTRIES);
textView.setAdapter(adapter);

We just have an array of Strings as the data source and we just bind via an ArrayAdapter the list of countries> The component will manage them by itself.

Now let’s look at a little more complex example.

2 – Email autocompletion

Let’s say we have a login screen in our application where the login is an email. An email is quite long and really annoying to type in, especially with a virtual keyboard.

We don’t know all the email addresses the user could potentially have. What we know however from his phone is all the email addresses he/she used as an account (Google, Facebook, Twitter, …).
We can use them as a data source to provide completion.

1
2
3
4
5
6
7
8
9
10
11
12
private static final Pattern EMAIL_PATTERN = Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$", Pattern.CASE_INSENSITIVE);
 
// In the onCreate method
AutoCompleteTextView editTextLogin = (AutoCompleteTextView) findViewById(R.id.actv_login);
Account[] accounts = AccountManager.get(this).getAccounts();
Set<String> emailSet = new HashSet<String>();
for (Account account : accounts) {
	if (EMAIL_PATTERN.matcher(account.name).matches()) {
		emailSet.add(account.name);
	}
}
editTextLogin.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, new ArrayList<String>(emailSet)));

This time instead of using a fixed array of Strings, we load the user accounts through the AccountManager.
As some accounts may not have an email address linked to them, we filter them and keep only the ones who matches an email regex. We also use a Set to remove the duplicates.
Then we use the same way as before to bind them to the AutoCompleteTextView through an ArrayAdapter.

One thing to know if you want to use this snippet of code as is in your project : it requires the permission android.permission.GET_ACCOUNTS to be able to read the user accounts.

You can use this example with any other data source as long as you manage to get an array of Strings to display.

And here is how it looks :

3 – Webservice autocompletion

For the first 2 examples, we only used static data. Now let’s use dynamic data for the auto-completion. The data is going to be returned from a web service which is going to be called every time the user input changes in the field.
For this example, we are going to write the code to add autocompletion to an address field :

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
AutoCompleteTextView editTextAddress = (AutoCompleteTextView)findViewById(R.id.actv_address);
editTextAddress.setAdapter(new AutoCompleteAdapter(this));
 
// And the corresponding Adapter
private class AutoCompleteAdapter extends ArrayAdapter<Address> implements Filterable {
 
	private LayoutInflater mInflater;
	private Geocoder mGeocoder;
	private StringBuilder mSb = new StringBuilder();
 
	public AutoCompleteAdapter(final Context context) {
		super(context, -1);
		mInflater = LayoutInflater.from(context);
		mGeocoder = new Geocoder(context);
	}
 
	@Override
	public View getView(final int position, final View convertView, final ViewGroup parent) {
		final TextView tv;
		if (convertView != null) {
			tv = (TextView) convertView;
		} else {
			tv = (TextView) mInflater.inflate(android.R.layout.simple_dropdown_item_1line, parent, false);
		}
 
		tv.setText(createFormattedAddressFromAddress(getItem(position)));
		return tv;
	}
 
	private String createFormattedAddressFromAddress(final Address address) {
		mSb.setLength(0);
		final int addressLineSize = address.getMaxAddressLineIndex();
		for (int i = 0; i < addressLineSize; i++) {
			mSb.append(address.getAddressLine(i));
			if (i != addressLineSize - 1) {
				mSb.append(", ");
			}
		}
		return mSb.toString();
	}
 
	@Override
	public Filter getFilter() {
		Filter myFilter = new Filter() {
			@Override
			protected FilterResults performFiltering(final CharSequence constraint) {
				List<Address> addressList = null;
				if (constraint != null) {
					try {
						addressList = mGeocoder.getFromLocationName((String) constraint, 5);
					} catch (IOException e) {
					}
				}
				if (addressList == null) {
					addressList = new ArrayList<Address>();
				}
 
				final FilterResults filterResults = new FilterResults();
				filterResults.values = addressList;
				filterResults.count = addressList.size();
 
				return filterResults;
			}
 
			@SuppressWarnings("unchecked")
			@Override
			protected void publishResults(final CharSequence contraint, final FilterResults results) {
				clear();
				for (Address address : (List<Address>) results.values) {
					add(address);
				}
				if (results.count > 0) {
					notifyDataSetChanged();
				} else {
					notifyDataSetInvalidated();
				}
			}
 
			@Override
			public CharSequence convertResultToString(final Object resultValue) {
				return resultValue == null ? "" : ((Address) resultValue).getAddressLine(0);
			}
		};
		return myFilter;
	}
}

As the data is dynamic depending on the current value, we can’t just provide beforehand the list of elements. Instead we create an ArrayAdapter with a special Filter.
Everytime the input changes, the performFiltering method is called and we retrieve in it the corresponding values from the webservice. These values are then transfered through the FilterResults object to the publishResults method where we replace the current elements with the new ones.

In our specific case, our webservice is the SDK Geocoder which calls the Maps server to get possible addresses based on input provided by the user.
As the result type, Address, is a complex object and we only want to display its formatted address while still keeping the object in the Adapter for further use, we also have to override both getView and convertResultToString methods :

  • The first one, getView, to choose how to display our special object in the list of possible autocompletions.
  • convertResultToString is used internally by the AutoCompleteTextView to choose what to display in the EditText field when the user selects one of the completions (in our case, the formatted address).

If the data returned by your webservice is only a String, you don’t need to do that (except if you want a special format, like upper case or something).

One thing to remember, the code in the performFiltering method is executed in a worker thread so we can directly access the webservice (in our case the Geocoder) to get the corresponding results even if it’s a long process.

4 – Conclusion

Normally now you know how to add autocompletion to your applications :)

If you have some questions about it, feel free to comment this article or to contact me via email !

And I have made a small application containing all these examples. Here is the APK and the project source code.

Page optimized by WP Minify WordPress Plugin