What's New Here?


Android XML Binding with Simple Framework Tutorial

XML is still important in the area of web services even though REST has gained significant attention lately. Exposed APIs via web services is the main reason I have to manipulate XML content in my Android applications. For that reason I need to parse XML documents even though it is a tedious procedure. In the past, I showed you how to parse XML using the SAX approach and how to boost your Android XML parsing with XML Pull. Both these techniques work, but are rather boring since they qualify as “plumbing code”. In this tutorial I am going to show you how to perform XML binding in Android using the Simple framework. XML data binding is quite popular in Java and there are multiple frameworks that allow binding. Solutions like JAXB and XStream are well established and heavily used. However, these libraries come with a large footprint, something that makes them inappropriate for use in the resources constraint world of mobiles. The good news is that there is a new kid on the block, the Simple framework. As its name implies, it strives to bring some simplicity in the bloated world of XML. From the official Simple framework site:Simple is a high performance XML serialization and configuration framework for Java. Its goal is to provide an XML framework that enables rapid development of XML configuration and communication systems. This framework aids the development of XML systems with minimal effort and reduced errors. It offers full object serialization and deserialization, maintaining each reference encountered. Very nice. You can get started with the framework by visiting the documentation page and you should also read how does JAXB compare to Simple. Simple could change the way you handle XML in your Java applications, give it a try. The big question is whether Simple is supported in Android’s JVM. Android uses Dalvik, a specialized virtual machine optimized for mobile devices. Additionally, Dalvik use a subset of Apache’s Harmony project for the core of its Class Library. Not all Java core classes are supported. For example, some of the javax.xml.* subpackages are not included. Well, Simple CAN work with Android. More specifically, I managed to use version 2.3.2 which can be found in Simple’s download page. The corresponding JAR has a size of 287KB. The release notes for that version mention:Addition of DOM provider so that StAX is not a required dependency Fix made to ensure property defaults are applied correctly to classesThe first issue is very important because the StAX API is not included in Android’s SDK. Note that the latest versions of Simple (after v2.3.2) also work and can be used for our purposes. Let’s cut to the chase and see how to perform the binding. As an example I will use an XML document that is returned as a response from the TMDb API which I use in the sample full Android application I build. Here is the document: Movies search for “Transformers” and (year) “2007” The response example can also be found here. First of all download Simple version 2.3.2 and include it in your project’s classpath. Then take a quick look at the Simple framework Javadocs. The most important thing is to create our model objects and map the appropriately to the XML formatted document. If we take a look at the XML file, we shall see that the root element is called OpenSearchDescription and it includes a Query element, a “totalResults” element and a number of movies. Here how our main model class looks like: package com.javacodegeeks.xml.bind.model;import java.util.List;import org.simpleframework.xml.Element; import org.simpleframework.xml.ElementList; import org.simpleframework.xml.Root;@Root public class OpenSearchDescription { @Element(name="Query") public Query query; @Element public int totalResults; @ElementList public List<Movie> movies;}The Root annotation denotes that the specific class represents a root XML element. We also use the Element and ElementList annotations for the nested elements. Note that Simple can handle both “getters/setters” and “public fields” approaches. I use the latter in this example. One thing to be aware of is that we use the name field (for “Query”) in order to provide the corresponding XML element name. This should be done when the XML element has a different name than the Java field, since Simple by default looks for an element with the same name as the field. Let’s now see the Query class: package com.javacodegeeks.xml.bind.model;import org.simpleframework.xml.Attribute; import org.simpleframework.xml.Element;@Element public class Query { @Attribute public String searchTerms; }This class contains only an attribute called “searchTerms” so the relevant field is annotated with Attribute. Very easy until now. Let’s check the Movie class: package com.javacodegeeks.xml.bind.model;import java.util.List;import org.simpleframework.xml.Element; import org.simpleframework.xml.ElementList;@Element(name="movie") public class Movie { @Element(required=false) public String score; @Element(required=false) public String popularity; @Element(required=false) public String name; @Element(required=false) public String id; @Element(required=false) public String biography; @Element(required=false) public String url; @Element(required=false) public String version; @Element(required=false) public String lastModifiedAt; @ElementList public List<Image> images;}The only new thing is that the required field is used in order to declare that a field is not required (can be null). This is done because some fields are empty in the API response. Let’s see the Image class: package com.javacodegeeks.xml.bind.model;import org.simpleframework.xml.Attribute; import org.simpleframework.xml.Element;@Element(name="image") public class Image {@Attribute public String type; @Attribute public String url; @Attribute public String size; @Attribute public int width; @Attribute public int height; @Attribute public String id;}This class includes only attributes so we annotate the fields accordingly. The final step is to read the source XML and let Simple wire all the classes and populate the fields. This is done by using the Persister class which provides an implementation for the Serializer interface. We shall use its read method which reads the contents of the XML document from a provided source and convert it into an object of the specified type. Note that we have disabled the strict mode. Here is how it looks inside an Android Activity: package com.javacodegeeks.xml.bind;import java.io.IOException; import java.io.Reader; import java.io.StringReader;import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.simpleframework.xml.Serializer; import org.simpleframework.xml.core.Persister;import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.widget.Toast;import com.javacodegeeks.xml.bind.model.OpenSearchDescription;public class SimpleExampleActivity extends Activity { private static final String url = "http://dl.dropbox.com/u/7215751/JavaCodeGeeks/AndroidFullAppTutorialPart03/Transformers+2007.xml"; private DefaultHttpClient client = new DefaultHttpClient(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); try { String xmlData = retrieve(url); Serializer serializer = new Persister(); Reader reader = new StringReader(xmlData); OpenSearchDescription osd = serializer.read(OpenSearchDescription.class, reader, false); Log.d(SimpleExampleActivity.class.getSimpleName(), osd.toString()); } catch (Exception e) { Toast.makeText(this, "Error Occured", Toast.LENGTH_LONG).show(); } } public String retrieve(String url) {HttpGet getRequest = new HttpGet(url);try {HttpResponse getResponse = client.execute(getRequest); final int statusCode = getResponse.getStatusLine().getStatusCode();if (statusCode != HttpStatus.SC_OK) { return null; }HttpEntity getResponseEntity = getResponse.getEntity();if (getResponseEntity != null) { return EntityUtils.toString(getResponseEntity); }} catch (IOException e) { getRequest.abort(); Log.w(getClass().getSimpleName(), "Error for URL " + url, e); }return null;} }This is a typical Android Activity. We retrieve the XML document as an internet resource (check my tutorial on how to use the HTTP API) and then create a StringReader from the response. We feed the Serializer with that and then let Simple perform its magic and return as a full class with the appropriate fields and embedded classes all populated. The specific app will just dump the classes string representations to the system’s log, which can be monitored in the DDMS view. That’s all guys. No more manual XML parsing for me. As always, you can download the Eclipse project created for this tutorial. Happy Android coding! And don’t forget to share! Related Articles:“Android Full Application Tutorial” series Boost your Android XML parsing with XML Pull Android Text-To-Speech Application Android Location Based Services Application – GPS location Install Android OS on your PC with VirtualBox...

Hibernate mapped collections performance problems

First things first, this article was inspired after Burt Beckwith‘s presentation about Advanced GORM – Performance, Customization and Monitoring at SpringOne 2GX on Jan 27, 2011. In short, Burt Beckwith discusses potential performance problems using mapped collections and Hibernate 2nd-level cache in GORM, along with strategies for avoiding such performance penalties. Nevertheless the performance issues regarding mapped collections that Burt Beckwith pinpoints in his presentation apply for every Hibernate enabled application in general. That’s why after watching his presentation I came to realize that what he proposes is exactly what I myself have been doing, and dictated my colleagues to do when developing using mapped collections in Hibernate. Below are the 5 things to consider when working with Hibernate mapped collections : Lets consider the following classic “Library – Visit” example : The following Library class has a collection of Visit instances: package eg; import java.util.Set;public class Library { private long id; private Set visits;public long getId() { return id; } private void setId(long id) { this.id=id; }private Set getVisits() { return visits; } private void setVisits(Set visits) { this.visits=visits; }.... .... }Following is the Visit class: package eg; import java.util.Set;public class Visit { private long id; private String personName;public long getId() { return id; } private void setId(long id) { this.id=id; }private String getPersonName() { return personName; } private void setPersonName(String personName) { this.personName=personName; }.... .... }Assuming that a library has multiple unique visits and that every visit correlates with a distinct library, a unidirectional one-to-many association like the one shown below can be used: <hibernate-mapping><class name="Library"> <id name="id"> <generator class="sequence"/> </id> <set name="visits"> <key column="library_id" not-null="true"/> <one-to-many class="Visit"/> </set> </class><class name="Visit"> <id name="id"> <generator class="sequence"/> </id> <property name="personName"/> </class></hibernate-mapping>I will also provide an example of Table definitions for the schema described above : create table library (id bigint not null primary key ) create table visit(id bigint not null primary key, personName varchar(255), library_id bigint not null) alter table visit add constraint visitfk0 (library_id) references librarySo what’s wrong with this picture? Potential performance bottlenecks will arise when you will try to add to the mapped collection. As you can see the collection is implemented as a Set. Sets guarantee uniqueness among their contained elements. So how Hibernate will know that a new item is unique so as to add it to the Set? Well do not be surprised; adding to the Set requires loading all available items from the database. Hibernate compares each and every one of them with the new one just to guarantee uniqueness. Moreover the above is standard behavior that we cannot bypass even if we know, because of business rules, that the new item is unique! Using a List implementation for our mapped collection will not solve the performance bottleneck problem when adding items to it either. Although Lists do not guarantee uniqueness they do guarantee item order. So to maintain the correct item order in our mapped List, Hibernate has to pull the entire collection even if we are adding to the end of the list. To my opinion, its a long way just to add one new Visit to the Library don’t you agree? Additionally, the above example works well in development where we only have a few number of visits. In production environments where each library may have millions of visits, just imagine the performance penalty when you try to add one more! To overcome the above performance problems we could map the collection as a Bag, which is just a regular collection with no ordering or uniqueness guarantees, but before doing so just consider my last point below. When you remove/add an object from/to a collection, the version number of the collection owner is incremented. Thus there is a high risk of artificial optimistic locking exceptions on the Library object when simultaneous Visit creations occur. We characterize the optimistic locking exceptions as “artificial” because they happen on the collection owner object (Library) which we do not feel we are editing (but we are!) when we are adding/removing an item from the Visits collection. Let me pinpoint that the same rules apply for a many-to-many association type. So what’s the solution? The solution is simple, remove the mapped collection from the owner (Library) object, and perform insertions and deletions for the Visit items “manually”. The proposed solution affects usage in the following ways :To add a Visit to a Library we must create a new Visit item, associate it with a Library item and persist it in the database explicitly. To remove a Visit from a Library we must search the “visit” table, find the exact record we need and delete it. With the proposed solution, no cascading is supported. To delete a Library you need to delete (disassociate) all its Visit records first.To keep things clean and ordered you can restore a “visits” pseudo – collection back to the Library object by implementing a helper method that will query the database and return all Visit objects associated with the specific Library. Furthermore you can implement a couple of helper methods that will perform the actual insertion and deletion of visit records, at the Visit item. Below we provide updated versions of the Library class, the Visit class and the Hibernate mapping so as to comply to our proposed solution : First the updated Library class : package eg; import java.util.Set;public class Library { private long id;public long getId() { return id; } private void setId(long id) { this.id=id; }public Set getVisits() { // TODO : return select * from visit where visit.library_id=this.id } .... .... }As you can see, we have removed the mapped collection and introduced the method “getVisits()” that should be used to return all the Visit items for the specific Library instance (the TODO comment is in pseudo-code). Following is the updated Visit class: package eg; import java.util.Set;public class Visit { private long id; private String personName; private long library_id;public long getId() { return id; } private void setId(long id) { this.id=id; }private String getPersonName() { return personName; } private void setPersonName(String personName) { this.personName=personName; }private long getLibrary_id() { return library_id; } private void setLibrary_id(long library_id) { this. library_id =library_id; }.... .... }As you can see we have added the “library_id” field to the Visit object so as to be able to correlate it with a Library item. Last is the updated Hibernate mapping : <hibernate-mapping><class name="Library"> <id name="id"> <generator class="sequence"/> </id> </class><class name="Visit"> <id name="id"> <generator class="sequence"/> </id> <property name="personName"/> <property name="library_id"/> </class></hibernate-mapping>So, never use mapped collections in Hibernate? Well, to be honest, No. You need to examine each case so as to decide what to do. The standard approach is fine if the collections are reasonable small – both sides in the case of a many to many association scheme. Additionally the collections will contain proxies, so they are smaller than real instances until initialized. Happy Coding! Don’t forget to share! Justin P.S. After a relatively long debate about this article on TheServerSide, one or our readers Eb Bras provided a useful list of Hibernate “tips and tricks”, lets see what he has to say : Here are a few of my Hibernate tips and tricks that I documented a long the way: inverse=”true” Use this as much as possible in a one-to-many parent-child association (to another entity or value-type that is used as an entity). This property is set on the collection tag like “set” and mean that the many-to-one owns the association and is responsible for all db inserts/updates/deletes. It makes the association part of the child. It will save an db update for the foreign key as it will occur directly when inserting the child. Especially when using “set” as mapping type, it can gains performance as the child don’t need to be added to the parent collection which can save the loading of the complete collection. That is: due to the nature of a set-mapping, the whole collection must always be loaded when adding a new child as that’s the only way hibernate can guarantee that the new entry isn’t a duplicate which is a feature of the JRE Set interface. In case it concerns a component collection (= collection containing only pure value types), inverse=true is ignored and makes no sense as Hibernate has full control of the objects and will choose the best way to perform his crud actions. If it concern detached DTO objects (not containing any hibernate objects), hibernate will delete all value-type child’s and then insert them as it doesn’t know which object is new or existent because it was completely detached. Hibernate treats it as it is a new collection. lazy Set.getChilds() is evil Be careful using getChilds() that returns a Set and will lazy load all child’s. Don’t use this when you want to add or remove just a child as it will first always implement equals/hashcode Make sure to always implement the equals/hashcode for every object that is managed by Hibernate, even if it doesn’t seem important.  This counts also for Value type objects. If the object doesn’t contain properties that are candidates for the equals/hashcode, use a surrogate key, that consists of a UUID for example. Hibernate uses the equals/hashcode to find out if an object is already present in the db. If it concerns an existing object but Hibernate thinks that it’s a new object because the equals/hashcode isn’t implemented correctly, Hibernate will perform an insert and possible a delete of the old value. Especially for value types in Set’s is important and must be tested as it saves db traffic. The idea: you are giving Hibernate more knowledge such it can use it to optimize his actions. use of version Always use the version property with an entity or a value type that is used as an entity. This results in less db traffic as Hibernate uses this information to discover if it concerns a new or existing object. If this property isn’t present, it will have to hit the db to find out if it concerns a new or existing object. eager fetching Not-lazy collections (child’s) are by default loaded through an extra select query that is just performed just after the parent is loaded from the db. The child’s can be loaded in the same query as loading the parent by enabling eager fetching which is done by setting the attribute “fetch=join” on the collection mapping tag. If enabled, the child’s are loaded through a left outer join. Test if this improves the performance. In case many join’s occur or if it concerns a table with many columns the performance will get worse instead of better. use surrogate key in value type child object Hibernate will construct the primary key in a value-type child of a parent-child relation that consists of all not-null columns. This can lead to strange primary key combinations, especially when a date column is involved. A date column shouldn’t be part of a primary key as it’s millisecond part will result to primary key’s that are almost never the same. This results in strange and probably poor performance db indexes. To improve this we use a surrogate key in all child value-type objects, that is the only not-null property. Hibernate will then construct a primary key that consists of the foreign key and surrogate key, which is logic and performs well. Note that the surrogate key is only used for database optimization and it’s not required to be used in the equals/hashcode which should consists of business logic if possible.Related Articles :Java Best Practices – High performance Serialization Java Best Practices – Vector vs ArrayList vs HashSet Java Best Practices – String performance and Exact String Matching Java Best Practices – Queue battle and the Linked ConcurrentHashMap Java Best Practices – Char to Byte and Byte to Char conversions How to Do 100K TPS at Less than 1ms Latency Revving Up Your Hibernate Engine Cajo, the easiest way to accomplish distributed computing in Java...

Android Animations – Quick Guide

A quick guide in the world of animations in Android from Chandan, one of our JCG partners. (NOTE: The original post has been slightly edited to improve readability) Setting animations to a layout programmatically is described below. Here we go: Create an XML file named for example “bottom_out.xml” and place it in a folder called “anim” inside the “res” folder. The contents of the “bottom_out.xml” file should be as follows: <?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="@android:anim/accelerate_interpolator"> <translate android:fromYDelta="0%" android:toYDelta="60%" android:duration="700"> </translate> </set>The values indicate the percentage relative to the parent layout. An Interpolator is used in order to indicate how the animation should proceed. It essentially defines the rate of change of an animation. This allows the basic animation effects (alpha, scale, translate, rotate) to be accelerated, decelerated, repeated, etc. For example, here we use a AccelerateInterpolator, thus the animation will be accelerated during the end. Another interpolator we could use is the LinearInterpolator, where the rate of change is constant. Let’s see how this can be used inside an Android class. private void startAnimationPopOut() { LinearLayout myLayout = (LinearLayout) findViewById(R.id.anim_layout);Animation animation = AnimationUtils.loadAnimation(this,R.anim.bottom_out);animation.setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(Animation animation) {}@Override public void onAnimationRepeat(Animation animation) {}@Override public void onAnimationEnd(Animation animation) {} });myLayout.clearAnimation(); myLayout.startAnimation(animation);}The “myLayout” variable (pointing to R.id.anim_layout) is a simple LinearLayout defined in xml file under “layout” folder. The AnimationUtils class can be used to load an Animation object from a resource. We also can attach AnimationListeners and be notified in the various stages of the animation. Note that it is generally a good practice to clear any previously set animations prior to set new animation, as shown in the end of the snippet. Below are some of the samples I would like to share: Sinking in: <translate android:fromYDelta="70%" android:toYDelta="0%" android:duration="700"> </translate>Slide from left side: <translate android:fromXDelta="-100%p" android:toXDelta="0%" android:duration="600"> </translate>Slide from right side: <translate android:fromXDelta="100%p" android:toXDelta="0%p" android:duration="600"> </translate>Rotate from 0 to 180 degree: <rotate android:fromDegrees="180" android:toDegrees="0" android:pivotX="50%" android:pivotY="50%" android:duration="600"> </rotate>Here pivotX and PivotY are the x and y coordinates of center around which you wish the view to rotate. Scale (here it is zooming in): <scale android:toXScale="1.1" android:fromXScale="1.0" android:toYScale="1.1" android:fromYScale="1.0" android:pivotX="0%" android:pivotY="0%" android:startOffset="100" android:duration="2000"> </scale>Here 1.0 implies original view size; as the pivot is set 0, the view will be scaled taking its origin as the center. Find more in the Animation Resources page. Happy coding! Related Articles:“Android Full Application Tutorial” series Android JSON Parsing with Gson Tutorial Android Quick Preferences Tutorial Boost your Android XML parsing with XML Pull Android Text-To-Speech Application...

Best Of The Week – 2011 – W05

Hello all, I would like to introduce a new JavaCodeGeeks idea with this post. Every Sunday we are going to provide a list of useful articles and tutorials from the week that passed. They can definitely serve your Sunday morning reading over coffee! Here are some links that drew JavaCodeGeeks’ attention during the past week: * Visualizing Garbage Collection in the JVM: A very nice introduction to garbage collection in the JVM accompanied with a little application that allows you to visually monitor the GC’s activity using the JVisualVM tool. * 10 things to become an outstanding Java developer: Siva, one of our JCG Partners, suggests 10 things to become an outstanding Java developer. * Stack Overflow Search — Now 81% Less Crappy: The guys at StackOverflow describe how they improved their site’s searching by dropping SQL server’s full text search in favor of Lucene.NET! Apache Lucene is a kick ass product and I suggest taking a look at An Introduction to Apache Lucene for Full-Text Search and “Did you mean” feature with Apache Lucene Spell-Checker. * How to explain growing Worker Threads under Load: I am sure every developer is concerned about application performance so here is a post about worker threads and how they behave under load. The example is real and affected a JBoss installation. * Abusing HTTP Status Codes to Expose Private Information: This is a very interesting post about abusing the HTTP protocol behind the scenes of a web site in order to extract private information about the site’s visitors. It shows how we can find out very easily if the visitor is currently logged in some of the most known sites (Facebook, GMail etc.). * Apache Solr: Get Started, Get Excited!: A detailed overview of the Apache Solr open source search server. Solr is built on top of Lucene, as you might have guessed. The article touches pretty much everything about Solr from installation to how it is used in various big applications. * JavaScript must die: A bold title for a post describing many of the security holes in Javascript. It explains that end users have very little in the way of protection against malicious Javascript and provides numerous real life examples. Check out the presentation. That’s all for this week. Stay tuned for more, here at JavaCodeGeeks. ...

Android JSON Parsing with Gson Tutorial

Apart from XML, JSON is a very common format used in API responses. Its simplicity has helped to gain quite the adoption in favor of the more verbose XML. Additionally, JSON can easily be combined with REST producing clear and easy to use APIs. Android includes support for JSON in its SDK as someone can find in the JSON package summary. However, using those classes, a developer has to deal with low level JSON parsing, which in my opinion is tedious and boring. For this reason, in this tutorial, I am going to show you how to perform automatic JSON parsing. For this purpose we are going to use the Google Gson library. From the official site: Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of. There are a few open-source projects that can convert Java objects to JSON. However, most of them require that you place Java annotations in your classes something that you can not do if you do not have access to the source-code. Most also do not fully support the use of Java Generics. Gson considers both of these as very important design goals. Excellent, exactly what we need. Before delving into code, you might want to take a look at the Gson User Guide and bookmark the Gson API Javadocs. Let’s get started by downloading Gson, with the current version being 1.6. We need the gson-1.6.jar from the distribution. Let’s proceed with creating an Eclipse project named “AndroidJsonProject” as follows:Add the Gson JAR to your project’s classpath. To illustrate how to use Gson for JSON parsing we are going to parse a JSON response from the Twitter API. Check the Twitter API Documentation for more info. We are going to use the Search API method for performing ad-hoc searches. For example, for searching Twitter about JavaCodeGeeks and retrieving the results in JSON format, here is the corresponding URL: http://search.twitter.com/search.json?q=javacodegeeks This will give a one line JSON response containing all the relevant info. This one liner is quite hard to read, so a JSON editor would be quite handy. I use the Eclipse Json Editor plugin and works really well. Here is how the response looks formatted in my Eclipse IDE:As you can see, we have a number of results and after that we have some other fields, such as “max_id”, “since_id”, “query” etc. Thus, our main model object, named “SearchResponse” will be as follows: package com.javacodegeeks.android.json.model;import java.util.List;import com.google.gson.annotations.SerializedName;public class SearchResponse { public List<Result> results; @SerializedName("max_id") public long maxId; @SerializedName("since_id") public int sinceId; @SerializedName("refresh_url") public String refreshUrl; @SerializedName("next_page") public String nextPage; @SerializedName("results_per_page") public int resultsPerPage; public int page; @SerializedName("completed_in") public double completedIn; @SerializedName("since_id_str") public String sinceIdStr; @SerializedName("max_id_str") public String maxIdStr; public String query; }We provide the various public fields (getter/setters with private fields can also be used) and in those case that the field name does not match the JSON response, we annotate with the SerializedName annotation. Note that we also have a list of results, with the corresponding model class being: package com.javacodegeeks.android.json.model;import com.google.gson.annotations.SerializedName;public class Result { @SerializedName("from_user_id_str") public String fromUserIdStr; @SerializedName("profile_image_url") public String profileImageUrl; @SerializedName("created_at") public String createdAt; @SerializedName("from_user") public String fromUser; @SerializedName("id_str") public String idStr; public Metadata metadata; @SerializedName("to_user_id") public String toUserId; public String text; public long id; @SerializedName("from_user_id") public String from_user_id;@SerializedName("iso_language_code") public String isoLanguageCode;@SerializedName("to_user_id_str") public String toUserIdStr;public String source; }Finally, we have one more class named “Metadata”: package com.javacodegeeks.android.json.model;import com.google.gson.annotations.SerializedName;public class Metadata { @SerializedName("result_type") public String resultType;}Let’s now see how all these get wired using Gson. Here is our Activity: package com.javacodegeeks.android.json;import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.List;import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient;import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.widget.Toast;import com.google.gson.Gson; import com.javacodegeeks.android.json.model.Result; import com.javacodegeeks.android.json.model.SearchResponse;public class JsonParsingActivity extends Activity { String url = "http://search.twitter.com/search.json?q=javacodegeeks"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); InputStream source = retrieveStream(url); Gson gson = new Gson(); Reader reader = new InputStreamReader(source); SearchResponse response = gson.fromJson(reader, SearchResponse.class); Toast.makeText(this, response.query, Toast.LENGTH_SHORT).show(); List<Result> results = response.results; for (Result result : results) { Toast.makeText(this, result.fromUser, Toast.LENGTH_SHORT).show(); } } private InputStream retrieveStream(String url) { DefaultHttpClient client = new DefaultHttpClient(); HttpGet getRequest = new HttpGet(url); try { HttpResponse getResponse = client.execute(getRequest); final int statusCode = getResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { Log.w(getClass().getSimpleName(), "Error " + statusCode + " for URL " + url); return null; }HttpEntity getResponseEntity = getResponse.getEntity(); return getResponseEntity.getContent(); } catch (IOException e) { getRequest.abort(); Log.w(getClass().getSimpleName(), "Error for URL " + url, e); } return null; } }First, we perform an HTTP GET request and retrieve the resource as a stream (if you need more details on this, check my previous tutorial Android Full App, Part 2: Using the HTTP API). We create a Gson instance and use it to perform the JSON parsing and retrieve our model object with all its fields populated. Edit your Android manifest XML file and grant permissions for Internet access and then launch the Eclipse configuration. You shall see notifications of the latest Twitter users that have tweeted about JavaCodeGeeks. That’s all guys, quick JSON parsing in Android with Gson. As always, you can download the Eclipse project created for this tutorial. Happy mobile coding! Don’t forget to share!Related Articles:“Android Full Application Tutorial” series Android Text-To-Speech Application Android Proximity Alerts Tutorial Add JSON capabilities into your GWT applicationRelated Snippets :JSON parsing with Gson Parsing XML with SAX  XML parsing with XML Pull ...

Cajo, the easiest way to accomplish distributed computing in Java

Derived from the introductory section of Jonas Boner’s article “Distributed Computing Made Easy” posted on TheServerSide.com on May 1st 2006 : “Distributed computing is becoming increasingly important in the world of enterprise application development. Today, developers continuously need to address questions like: How do you enhance scalability by scaling the application beyond a single node? How can you guarantee high-availability, eliminate single points of failure, and make sure that you meet your customer SLAs? For many developers, the most natural way of tackling the problem would be to divide up the architecture into groups of components or services that are distributed among different servers. While this is not surprising, considering the heritage of CORBA, EJB, COM and RMI that most developers carry around, if you decide to go down this path then you are in for a lot of trouble. Most of the time it is not worth the effort and will give you more problems than it solves.” On the other hand, distributed computing and Java go together naturally. As the first language designed from the bottom up with networking in mind, Java makes it very easy for computers to cooperate. Even the simplest applet running in a browser is a distributed application, if you think about it. The client running the browser downloads and executes code that is delivered by some other system. But even this simple applet wouldn’t be possible without Java’s guarantees of portability and security: the applet can run on any platform, and can’t sabotage its host. The cajo project is a small library, enabling powerful dynamic multi-machine cooperation. It is a surprisingly easy to use yet unmatched in performance. It is a uniquely ‘drop-in’ distributed computing framework: meaning it imposes no structural requirements on your applications, nor source changes. It allows multiple remote JVMs to work together seamlessly, as one. The project owner John Catherino claims “King Of the Mountain! ;-)” and challenges everyone who is willing to prove that there exists a distributed computing framework in Java that is equally flexible and as fast as cajo. To tell you the truth, personally I am convinced by John’s saying; and I strongly believe that you will be also if you just let me walk you through this client – server example. You will be amazed of how easy and flexible the cajo framework is : The Server.java import gnu.cajo.Cajo; // The cajo implementation of the Grailpublic class Server {public static class Test { // remotely callable classes must be public // though not necessarily declared in the same class private final String greeting; // no silly requirement to have no-arg constructors public Test(String greeting) { this.greeting = greeting; } // all public methods, instance or static, will be remotely callable public String foo(Object bar, int count) { System.out.println("foo called w/ " + bar + ' ' + count + " count"); return greeting; } public Boolean bar(int count) { System.out.println("bar called w/ " + count + " count"); return Boolean.TRUE; } public boolean baz() { System.out.println("baz called"); return true; } public String other() { // functionality not needed by the test client return "This is extra stuff"; } } // arguments and return objects can be custom or common to server and clientpublic static void main(String args[]) throws Exception { // unit test Cajo cajo = new Cajo(0); System.out.println("Server running"); cajo.export(new Test("Thanks")); } }Compile via: javac -cp cajo.jar;. Server.javaExecute via: java -cp cajo.jar;. ServerAs you can see with just 2 commands : Cajo cajo = new Cajo(0); cajo.export(new Test("Thanks"));we can expose any POJO (Plain Old Java Object) as a distributed service! And now the Client.java import gnu.cajo.Cajo;import java.rmi.RemoteException; // caused by network related errorsinterface SuperSet { // client method sets need not be public void baz() throws RemoteException; } // declaring RemoteException is optional, but a nice reminderinterface ClientSet extends SuperSet { boolean bar(Integer quantum) throws RemoteException; Object foo(String barbaz, int foobar) throws RemoteException; } // the order of the client method set does not matterpublic class Client { public static void main(String args[]) throws Exception { // unit test Cajo cajo = new Cajo(0); if (args.length > 0) { // either approach must work... int port = args.length > 1 ? Integer.parseInt(args[1]) : 1198; cajo.register(args[0], port); // find server by registry address & port, or... } else Thread.currentThread().sleep(100); // allow some discovery timeObject refs[] = cajo.lookup(ClientSet.class); if (refs.length > 0) { // compatible server objects found System.out.println("Found " + refs.length); ClientSet cs = (ClientSet)cajo.proxy(refs[0], ClientSet.class); cs.baz(); System.out.println(cs.bar(new Integer(77))); System.out.println(cs.foo(null, 99)); } else System.out.println("No server objects found"); System.exit(0); // nothing else left to do, so we can shut down } }Compile via: javac -cp cajo.jar;. Client.javaExecute via: java -cp cajo.jar;. ClientThe client can find server objects either by providing the server address and port (if available) or by using multicast. To locate the appropriate server object “Dynamic Client Subtyping” is used. For all of you who do not know what “Dynamic Client Subtyping” stands for, John Catherino explains in his relevant blog post : “Oftentimes service objects implement a large, rich interface. Other times service objects implement several interfaces, grouping their functionality into distinct logical concerns. Quite often, a client needs only to use a small portion of an interface; or perhaps some methods from a few of the logical grouping interfaces, to satisfy its own needs. The ability of a client to define its own interface, from ones defined by the service object, is known as subtyping in Java. (in contrast to subclassing) However, unlike conventional Java subtyping; Dynamic Client Subtyping means creating an entirely different interface. What makes this subtyping dynamic, is that it works with the original, unmodified service object. This can be a very potent technique, for client-side complexity management.” Isn’t that really cool??? We just have to define the interface our client “needs” to use and locate the appropriate server object that complies with the client specification. The following command derived from our example accomplish just that : Object refs[] = cajo.lookup(ClientSet.class);Last but not least we can create a client side “proxy” of the server object and remotely invoke its methods just like an ordinary local object reference, by issuing the following command : ClientSet cs = (ClientSet)cajo.proxy(refs[0], ClientSet.class);That’s it. These allow for complete interoperability between distributed JVMs. It just can’t get any easier than this. As far as performance is concerned, I have conducted some preliminary tests on the provided example and achieved an average score of 12000 TPS on the following system : Sony Vaio with the following characteristics :System : openSUSE 11.1 (x86_64) Processor (CPU) : Intel(R) Core(TM)2 Duo CPU T6670 @ 2.20GHz Processor Speed : 1,200.00 MHz Total memory (RAM) : 2.8 GB Java : OpenJDK 1.6.0_0 64-BitFor your convenience I provide the code snippet that I used to perform the stress test : int repeats = 1000000; long start = System.currentTimeMillis(); for(int i = 0; i < repeats;i ++) cs.baz(); System.out.println("TPS : " + repeats/((System.currentTimeMillis() - start)/1000d));Happy Coding! and Don’t forget to share! Justin Related Articles :Java Best Practices – High performance Serialization Java Best Practices – Vector vs ArrayList vs HashSet Java Best Practices – String performance and Exact String Matching Java Best Practices – Queue battle and the Linked ConcurrentHashMap Java Best Practices – Char to Byte and Byte to Char conversions How to Do 100K TPS at Less than 1ms Latency Revving Up Your Hibernate Engine...

Aspect Oriented Programming with Spring AOP

Aspect Oriented Programming (AOP) refers to the programming paradigm which isolates secondary or supporting functions from the main program’s business logic. AOP is a promising technology for separating crosscutting concerns, something usually hard to do in object-oriented programming. The application’s modularity is increased in that way and its maintenance becomes significantly easier. The most prominent example of a crosscutting concern is logging. Logging is used mainly for debugging and troubleshooting issues mainly by tracing method calls and overall execution flow. It qualifies as a crosscutting concern because a logging strategy necessarily affects every logged part of the system. Logging thereby crosscuts all logged classes and methods. Note that AOP and OOP are not exclusive. In contrary, they complement each other and their combined use can help us produce robust and maintainable software. With AOP, we start by implementing our project using our OO language and then we deal separately with crosscutting concerns in our code by implementing aspects. AOP’s usage and adoption was boosted with the help of our favorite Spring framework. Spring makes AOP easier to integrate in our projects using an non-intrusive approach. Justin has talked before about Spring AOP in his post named “Aspect Oriented Programming with Spring AspectJ and Maven” here at JavaCodeGeeks. However, our latest JCG partner, Siva from SivaLabs, has also written a very nice article on Spring AOP and I wanted to share it with you, so here it is. (NOTE: The original post has been slightly edited to improve readability) While developing software applications for a business we receive the project’s requirements either from the requirements gathering team or from our business analysts. In general, those requirements are functional requirements which represent the activities that the business is doing. However, when developing software applications, apart from the functional requirements, we should also consider some other points like performance, transaction management, security, logging etc. These are called non-functional requirements. Let us consider a BookStore application which provides web access to a book store. A user can browse the various categories of books, add some books to a cart and finally checkout, do payment and get the books. For this app we might receive the requirements from a business analyst as follows:A login/registration screen to enter into BookStore. Users should be able to browse through various categories of books Users should be able to search books by name, author name, publisher Users should be able to add/remove the books to/from their cart Users should be able to see what items currently exist in their cart Users should be able to checkout and pay the corresponding amount through some payment gateway A successful message should be shown to users with all the details of their purchases. A failure message should be shown to users with the cause of failure. A BookStore administrator/manager should be granted access to add/remove/update book details.All the above requirements fall under the “Functional Requirements” category. While implementing the above, we should also take care of the following things even though they are not explicitly mentioned:Role based access to the UI. Here, only Administrators/Managers should have access to add/remove/update book details. [Role based Authorization] Atomicity in Purchasing. Suppose a user logged into the BookStore and added 5 books into his cart, checked out and completed his payment. In the back-end implementation we may need to enter this purchase details in 3 tables. If after inserting the data into 2 tables the system crashed, the whole operation should be rolled-back. [Transaction Management]. No one is perfect and no system is flawless. So if something went wrong and the development team has to figure it out what went wrong, logging will be useful. So, logging should be implemented in such a way that developer should be able to figure out where exactly the application failed and fix it. [Logging]The above implicit requirements are called Non-Functional Requirements. In addition to the above, performance should obviously be a crucial non-functional requirement for all public facing websites. So, with all the above functional requirements we can build the system by decomposing it into various components band taking care of the non-functional requirements through out the components. public class OrderService { private OrderDAO orderDAO; public boolean placeOrder(Order order) { boolean flag = false; logger.info("Entered into OrderService.placeOrder(order) method"); try { flag = orderDAO.saveOrder(order); } catch(Exception e) { logger.error("Error occured in OrderService.placeOrder(order) method"); } logger.info("Exiting from OrderService.placeOrder(order) method"); return flag; } }public class OrderDAO { public boolean saveOrder(Order order) { boolean flag = false; logger.info("Entered into OrderDAO.saveOrder(order) method"); Connection conn = null; try { conn = getConnection();//get database connection conn.setAutoCommit(false); // insert data into orders_master table which generates an order_id // insert order details into order_details table with the generated order_id // insert shipment details into order_shipment table conn.commit(); conn.setAutoCommit(true); flag = true; } catch(Exception e) { logger.error("Error occured in OrderDAO.saveOrder(order) method"); conn.rollback(); } logger.info("Exiting from OrderDAO.saveOrder(order) method"); return flag; } }In the code above , the functional requirement implementation and non-functional requirement implementation are mingled in the same place. Logging is placed across the OrderService and OrderDAO classes. At the same time, transaction management is spanned across DAOs. With this approach we have several issues:The classes need to be changed either to change functional or non-functional requirements. For example: At some point later in the development if the Team decides to log the Method Entry/Exit information along with TimeStamp, we need to change almost all the classes. The Transaction Management code setting the auto-commit to false in the beginning, doing the DB operations, committing/rollbacking the operation logic will be duplicated across all the DAOs.This kind of requirements which span across the modules/components is referred to as Cross Cutting Concerns. To better design the system we should separate these cross cutting concerns from the actual business logic so that it will be easier to change or enhance or maintain the application at a later point. Aspect Oriented Programming is a methodology which enables the separation of the cross cutting concerns from the actual business logic. So, let us follow the AOP methodology and redesign the above two classes separating the cross cutting concerns. public interface IOrderService { public boolean placeOrder(Order order); }public class OrderService implements IOrderService { private OrderDAO orderDAO; public boolean placeOrder(Order order) { return orderDAO.saveOrder(order); } }public class OrderDAO { public boolean saveOrder(Order order) { boolean flag =false; Connectoin conn = null; try { conn = getConnection();//get database connection // insert data into orders_master table which generates an order_id // insert order details into order_details table with the generated order_id // insert shipment details into order_shipment table flag = true; } catch(Exception e) { logger.error(e); } return flag; } }Now lets create a LoggingInterceptor implementing how logging should be done and create a Proxy for OrderService which takes the call from the caller, logs the entry/exit entries using LoggingInterceptor and finally delegates to the actual OrderService. By using Dynamic Proxies we can separate out the implementation of the cross cutting concerns (such as logging) from actual business logic as follows: public class LoggingInterceptor { public void logEntry(Method m) { logger.info("Entered into "+m.getName()+" method"); } public void logExit(Method m) { logger.info("Exiting from "+m.getName()+" method"); } }public class OrderServiceProxy implements IOrderService extends LoggingInterceptor { private OrderService orderService; public boolean placeOrder(Order order) { boolean flag =false; Method m = getThisMethod();//get OrderService.placeOrder() Method object logEntry(m); flag = orderService.placeOrder(order); logExit(m); return flag; } }Now the OrderService caller (OrderController) can get the OrderServiceProxy and place the order as: public class OrderController { public void checkout() { Order order = new Order(); //set the order details IOrderService orderService = getOrderServiceProxy(); orderService.placeOrder(order); } }There are several AOP frameworks which can be used in order to separate the implementation from the cross cutting concerns.Spring AOP AspectJ JBoss AOPLet’s see how we can separate out logging from the actual business logic using Spring AOP. Before that, first we need to understand the following terms:JoinPoint: A joinpoint is a point in the execution of the application where an aspect can be plugged in. This point could be a method being called, an exception being thrown, or even a field being modified. Pointcut: A pointcut definition matches one or more joinpoints at which advice should be woven. Often you specify these pointcuts using explicit class and method names or through regular expressions that define matching class and method name patterns. Aspect: An aspect is the merger of advice and pointcuts. Advice: The job of an aspect is called advice. It is the additional code we apply to the existing model.SpringAOP supports several types of advices, namely:Before: This advice weaves the aspect before method call. AfterReturning: This advice weaves the aspect after method call. AfterThrowing: This advice weaves the aspect when method throws an Exception. Around: This advice weaves the aspect before and after method call.Suppose we have the following ArithmeticCalculator interface and implementation classes. package com.springapp.aop;public interface ArithmeticCalculator { public double add(double a, double b); public double sub(double a, double b); public double mul(double a, double b); public double div(double a, double b); }package com.springapp.aop; import org.springframework.stereotype.Component;@Component("arithmeticCalculator") public class ArithmeticCalculatorImpl implements ArithmeticCalculator { public double add(double a, double b) { double result = a + b; System.out.println(a + " + " + b + " = " + result); return result; }public double sub(double a, double b) { double result = a - b; System.out.println(a + " - " + b + " = " + result); return result; }public double mul(double a, double b) { double result = a * b; System.out.println(a + " * " + b + " = " + result); return result; }public double div(double a, double b) { if(b == 0) { throw new IllegalArgumentException("b value must not be zero."); } double result = a / b; System.out.println(a + " / " + b + " = " + result); return result; } }The following LoggingAspect class shows various bit and pieces of applying Logging Advice using Spring AOP: package com.springapp.aop;import java.util.Arrays; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.AfterThrowing; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component;@Aspect @Component public class LoggingAspect { private Log log = LogFactory.getLog(this.getClass()); @Pointcut("execution(* *.*(..))") protected void loggingOperation() {} @Before("loggingOperation()") @Order(1) public void logJoinPoint(JoinPoint joinPoint) { log.info("Join point kind : " + joinPoint.getKind()); log.info("Signature declaring type : "+ joinPoint.getSignature().getDeclaringTypeName()); log.info("Signature name : " + joinPoint.getSignature().getName()); log.info("Arguments : " + Arrays.toString(joinPoint.getArgs())); log.info("Target class : "+ joinPoint.getTarget().getClass().getName()); log.info("This class : " + joinPoint.getThis().getClass().getName()); } @AfterReturning(pointcut="loggingOperation()", returning = "result") @Order(2) public void logAfter(JoinPoint joinPoint, Object result) { log.info("Exiting from Method :"+joinPoint.getSignature().getName()); log.info("Return value :"+result); } @AfterThrowing(pointcut="execution(* *.*(..))", throwing = "e") @Order(3) public void logAfterThrowing(JoinPoint joinPoint, Throwable e) { log.error("An exception has been thrown in "+ joinPoint.getSignature().getName() + "()"); log.error("Cause :"+e.getCause()); } @Around("execution(* *.*(..))") @Order(4) public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable { log.info("The method " + joinPoint.getSignature().getName()+ "() begins with " + Arrays.toString(joinPoint.getArgs())); try { Object result = joinPoint.proceed(); log.info("The method " + joinPoint.getSignature().getName()+ "() ends with " + result); return result; } catch (IllegalArgumentException e) { log.error("Illegal argument "+ Arrays.toString(joinPoint.getArgs()) + " in "+ joinPoint.getSignature().getName() + "()"); throw e; } } }Here is what our applicationContext.xml should include:And here is a standalone test client to test the functionality. package com.springapp.aop;import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext;public class SpringAOPClient {public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); ArithmeticCalculator calculator = (ArithmeticCalculator) context.getBean("arithmeticCalculator"); double sum = calculator.add(12, 23); System.out.println(sum); double div = calculator.div(1, 10); System.out.println(div); }}The required libraries are the following:Spring.jar (2.5.6 or above) commons-logging.jar aopalliance.jar aspectjrt.jar aspectjweaver.jar cglib-nodep-2.1_3.jarWe can define the type of advice using the annotations @Before, @AfterReturning, @Around etc. We can define pointcuts in different ways. For example: @Around(“execution(* *.*(..))”) means it is an Around advice which will be applied to all classes in all packages and all methods. Suppose that we want to apply the advice only for all the services that reside in the com.myproj.services package. Then the pointcut declaration would be: @Around(“execution(* com.myproj.services.*.*(..))”) In that case, “(..)” means with any type of arguments. If we want to apply same pointcuts for many advices we can define a pointcut on a method and can refer that later as follows. @Pointcut("execution(* *.*(..))") protected void loggingOperation() {}@Before("loggingOperation()") public void logJoinPoint(JoinPoint joinPoint){}If multiple Advices have to be applied on the same pointcut, we can specify the order using the @Order annotation on which advices will be applied. In the previous example, @Before will be applied first. Then, @Around will be applied when the add() method is called. That’s it guys. A very straightforward and explanatory tutorial from Siva, one of our JCG partners. Happy AOP coding. Don’t forget to share! Related Articles:Aspect Oriented Programming with Spring AspectJ and Maven GWT 2 Spring 3 JPA 2 Hibernate 3.5 Tutorial – Eclipse and Maven 2 showcase GWT Spring and Hibernate enter the world of Data Grids JAX–WS with Spring and Maven Tutorial...

Programming Android Online Book

Yesterday I stumbled upon an Android related online book named “Programming Android“. This book is published online while being under development and uses the Open Feedback Publishing System (OFPS). With that system, early readers can provide comments next to any paragraph while reading. It is essentially a nice way to provide direct feedback. I just skimmed through the book, but only from that little time it was apparent that it is well written and it can definitely be a tool to your Android programming toolbox. The main author is Zigurd Mednieks and the book can be found in O’Reilly’s catalog here. Check it out. ...

Android Quick Preferences Tutorial

When developing a mobile application, a common need that arises is the one of storing user’s preferences and using them when the application starts. Since this is a recurring need, Google has created a preferences framework for us. The provided mechanism allows us to show, save and manipulate user’s preferences very easily. Furthermore, the framework has support for automatic UI creation. What I mean is, that, by declaring the type of a user preference, a user interface for manipulating these preferences is automatically generated, without having to write a single line code. How does that sound for rapid application development? In order to make use of the preferences framework, the first step is to extend the PreferenceActivity class. This is just a convenience class that derives from ListActivity and allows to bootstrap the preferences UI from an XML file. Additionally, it automatically saves to SharedPreferences behind the scenes. Don’t forget that SharedPreferences is the interface responsible for accessing and modifying preference data and that we can manually manipulate it by calling the getSharedPreferences method of an Activity. In order to tie together our PreferenceActivity class and the XML layout file, we use the addPreferencesFromResource method. Thus, our onCreate method is very simple and looks like this: ... @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); } ...This assumes that we have already created a file named “preferences.xml” inside the “res/xml” folder. Then, in run-time, the activity will inflate the given XML resource and add the preference hierarchy to the current preference hierarchy. This XML file has a specific format via which we define the types of the preferences. All types derive from the Preference class, which represents the basic preference UI building block and provides the View to be displayed in the activity and the association with a SharedPreferences object to store/retrieve the preference data. Here are some of the most common subclasses that you can directly use:CheckBoxPreference: Provides checkbox widget functionality. Will store a Boolean value. RingtonePreference: Allows the user to choose a ringtone from those on the device. The chosen ringtone’s URI will be persisted as a string. EditTextPreference: Allows for string input. Will store a string into the SharedPreferences. ListPreference: Displays a list of entries as a dialog. This preference will store a string into the SharedPreferences.Also bear in mind that various preferences can be grouped into categories by using the PreferenceCategory class, which groups Preference objects and provides a disabled title above the group. Let’s examine what our XML declaration file will be consisted of. We are going to have two categories. Under the first one, we will have a CheckBoxPreference, which will enable or disable data updates to a hypothetical application and a ListPreference which through which we will define how often we want updates to happen. As you might have guessed, there is a dependency between the two preferences. This can be achieved by using the android:dependency attribute. Finally, under the second category, we will have a EditTextPreference via which a welcome message will be saved and shown when necessary. This is what the XML file looks like: <?xml version="1.0" encoding="utf-8"?><PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"><PreferenceCategory android:title="First Category" android:key="first_category"> <CheckBoxPreference android:key="perform_updates" android:summary="Enable or disable data updates" android:title="Enable updates" android:defaultValue="true" /> <ListPreference android:key="updates_interval" android:title="Updates interval" android:summary="Define how often updates will be performed" android:defaultValue="1000" android:entries="@array/updateInterval" android:entryValues="@array/updateIntervalValues" android:dependency="perform_updates" /> </PreferenceCategory><PreferenceCategory android:title="Second Category" android:key="second_category"><EditTextPreference android:key="welcome_message" android:title="Welcome Message" android:summary="Define the Welcome message to be shown" android:dialogTitle="Welcome Message" android:dialogMessage="Provide a message" android:defaultValue="Default welcome message" /></PreferenceCategory> </PreferenceScreen>Note that for the ListPreference, an android:entries attribute is defined. We use that to load predefined values which are kept in an external XML file under the name “res/values/arrays.xml”. The “updateInterval” and “updateIntervalValue” entries are used from that file. These are actually key-value pairs, so the actual value stored is the one in the second list. Here is what the file looks like: <?xml version="1.0" encoding="utf-8"?><resources><string-array name="updateInterval"> <item name="1000">Every 1 second</item> <item name="5000">Every 5 seconds</item> <item name="30000">Every 30 seconds</item> <item name="60000">Every 1 minute</item> <item name="300000">Every 5 minutes</item> </string-array> <string-array name="updateIntervalValues"> <item name="1000">1000</item> <item name="5000">5000</item> <item name="30000">30000</item> <item name="60000">60000</item> <item name="300000">300000</item> </string-array></resources>As we explained, the persisting part of the equation is handled by the framework. In order to show you how to read the already persisted values, we will create another activity which will be launched from our main one. Let’s first see how the main activity looks like: package com.javacodegeeks.android.preferences;import android.content.Intent; import android.os.Bundle; import android.preference.PreferenceActivity; import android.view.Menu; import android.view.MenuItem;public class QuickPrefsActivity extends PreferenceActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); } @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(Menu.NONE, 0, 0, "Show current settings"); return super.onCreateOptionsMenu(menu); }@Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case 0: startActivity(new Intent(this, ShowSettingsActivity.class)); return true; } return false; } }Nothing special here. We just provide an options menu with only one MenuItem by using the onCreateOptionsMenu method. When the user selects the specific item, we handle its actions inside the onOptionsItemSelected method and we launch a new activity using the startActivity method. If you want to learn more about option menus, check out my older tutorial named “Using options menus and customized dialogs for user interaction”. More information about starting activities can be found in my tutorial “Launching new activities with intents”. Let’s now create the “ShowSettingsActivity”. First, we have to declare it in the Android manifest file, so here what our “AndroidManifest.xml” file looks like: <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.javacodegeeks.android.preferences" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".QuickPrefsActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".ShowSettingsActivity" /> </application> <uses-sdk android:minSdkVersion="3" /></manifest>Here is the code for the activity itself: package com.javacodegeeks.android.preferences;import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.widget.TextView;public class ShowSettingsActivity extends Activity {@Override protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState); setContentView(R.layout.show_settings_layout);SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);StringBuilder builder = new StringBuilder();builder.append("\n" + sharedPrefs.getBoolean("perform_updates", false)); builder.append("\n" + sharedPrefs.getString("updates_interval", "-1")); builder.append("\n" + sharedPrefs.getString("welcome_message", "NULL"));TextView settingsTextView = (TextView) findViewById(R.id.settings_text_view); settingsTextView.setText(builder.toString());}}Inside the activity, we take reference of the SharedPreferences class by using the static method getDefaultSharedPreferences of the PreferenceManager class. Then, depending on the data type of the preference, we use the appropriate getter method, such as getBoolean or getString. Note that the second argument to those is a default value which will be used if a a value has not yet been stored. We use as keys those defined in the original “preferences.xml” file, i.e. “perform_updates”, “updates_interval” and “welcome_message”. The values are concatenated and then presented in a TextView. Here is also the simple layout for the specific activity: <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:id="@+id/settings_text_view" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout>If we now launch the Eclipse configuration, we will get a preferences screen like the following:Clicking on the “Updates Interval” will cause a list of options to appear:Similarly, clicking on the “Welcome Message” preference will cause an edit text to appear:Now let’s read the already persisted values. Hit the “Menu” button on the emulator so that the options menu appears and choose the “Show current settings” item. This will launch our second activity inside which the values are read and presented as follows:That’s it guys. A quick guide on how to leverage the preferences framework provided in the SDK to rapidly manipulate user preferences in your application. You can find the Eclipse project created in this tutorial here. Cheers! Related Articles :“Android Full Application Tutorial” series Boost your Android XML parsing with XML Pull Android Text-To-Speech Application Android Reverse Geocoding with Yahoo API – PlaceFinder Android Location Based Services Application – GPS location Install Android OS on your PC with VirtualBoxRelated Snippets :Prefernces and PreferenceActivity example Android Text-To-Speech Application  Customized dialog ...

Java Swing – Date Picker dialog

Any Swing developers in the house? For those that work with Swing, here is a GUI component that might be helpful to your UI coding endeavors. One of our JCG partners offers a date picker widget. Check it out: Java Swing – Date Picker dialog to select a date ...
Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books