- HtmlUnit is an open source java library for creating HTTP calls which imitate the browser functionality.
- HtmlUnit is mostly used for integration testing upon Unit test frameworks such as JUnit or TestNG. This is done by requesting web pages and asserting the results.
Simple Example
@Test
public void testGoogle(){
WebClient webClient = new WebClient();
HtmlPage currentPage = webClient.getPage("http://www.google.com/");
assertEquals("Google", currentPage.getTitleText());
}
WebClient
- As you can see in the example, the WebClient is the starting point. It is the browser simulator.
- WebClient.getPage() is just like typing an address in the browser. It returns an HtmlPage object.
HtmlPage
- HtmlPage represents a single web page along with all of it’s client’s data (HTML, JavaScript, CSS …).
- The HtmlPage lets you access to many of a web page content:
Page source
- You can receive the page source as text or as XML.
HtmlPage currentPage =
webClient.getPage("http://www.google.com/");
String textSource = currentPage.asText();
String xmlSource = currentPage.asXml();
HTML Elements
- HtmlPage lets you ability to access any of the page HTML elements and all of their attributes and sub elements. This includes tables, images, input fields, divs or any other Html element you may imagine.
- Use the function getHtmlElementById() to get any of the page elements.
WebClient webClient = new WebClient();
HtmlPage currentPage = webClient.getPage("http://www.google.com/");
HtmlImage imgElement = (HtmlImage)currentPage.getHtmlElementById("logo");
System.out.println(imgElement.getAttribute("src"));
Anchors
- Anchor is the representation of the Html tag <a href=”…” >link</a>.
- Use the functions getAnchorByName(), getAnchorByHref() and getAnchorByText() to easily access any of the anchors in the page.
WebClient webClient = new WebClient();
HtmlPage currentPage = webClient.getPage("http://www.google.com/");
HtmlAnchor advancedSearchAn =
currentPage.getAnchorByText("Advanced Search");
currentPage = advancedSearchAn.click();
assertEquals("Google Advanced Search",currentPage.getTitleText());
Dom elements by XPath
- You can access any of the page elements by using XPath.
WebClient webClient = new WebClient();
HtmlPage currentPage =
webClient.getPage("http://www.google.com/search?q=avi");
//Using XPath to get the first result in Google query
HtmlElement element = (HtmlElement)currentPage.getByXPath("//h3").get(0);
DomNode result = element.getChildNodes().get(0);
Form control
- A large part of controlling your HTML page is to control the form elements:
- HtmlForm
- HtmlTextInput
- HtmlSubmitInput
- HtmlCheckBoxInput
- HtmlHiddenInput
- HtmlPasswordInput
- HtmlRadioButtonInput
- HtmlFileInput
WebClient webClient = new WebClient();
HtmlPage currentPage = webClient.getPage("http://www.google.com/");
//Get the query input text
HtmlInput queryInput = currentPage.getElementByName("q");
queryInput.setValueAttribute("aviyehuda");
//Submit the form by pressing the submit button
HtmlSubmitInput submitBtn = currentPage.getElementByName("btnG");
currentPage = submitBtn.click();
Tables
currentPage = webClient.getPage("http://www.google.com/search?q=htmlunit");
final HtmlTable table = currentPage.getHtmlElementById("nav");
for (final HtmlTableRow row : table.getRows()) {
System.out.println("Found row");
for (final HtmlTableCell cell : row.getCells()) {
System.out.println(" Found cell: " + cell.asText());
}
}
JavaScript support
- HtmlUnit uses the Mozilla Rhino JavaScript engine.
- This lets you the ability to run pages with JavaScript or even run JavaScript code by command.
ScriptResult result = currentPage.executeJavaScript(JavaScriptCode);
- By default JavaScript exceptions will crash your tests. If you wish to ignore JavaScript exceptions use this:
webClient().setThrowExceptionOnScriptError(false);
- If you would like to turn off the JavaScript all together, use this:
currentPage.getWebClient().setJavaScriptEnabled(false);
HTTP elements
URL
WebClient webClient = new WebClient();
HtmlPage currentPage =
webClient.getPage("http://www.google.co.uk/search?q=htmlunit");
URL url = currentPage.getWebResponse().getRequestSettings().getUrl()
Response status
WebClient webClient = new WebClient();
HtmlPage currentPage = webClient.getPage("http://www.google.com/");
assertEquals(200,currentPage.getWebResponse().getStatusCode());
assertEquals("OK",currentPage.getWebResponse().getStatusMessage());
Cookies
Set<Cookie> cookies = webClient.getCookieManager().getCookies();
for (Cookie cookie : cookies) {
System.out.println(cookie.getName() + " = " + cookie.getValue());
}
Response headers
WebClient webClient = new WebClient();
HtmlPage currentPage =
webClient.getPage("http://www.google.com/search?q=htmlunit");
List<NameValuePair> headers =
currentPage.getWebResponse().getResponseHeaders();
for (NameValuePair header : headers) {
System.out.println(header.getName() + " = " + header.getValue());
}
Request parameters
List<NameValuePair> parameters =
currentPage.getWebResponse().getRequestSettings().getRequestParameters();
for (NameValuePair parameter : parameters) {
System.out.println(parameter.getName() + " = " + parameter.getValue());
}
Making assertions
- HtmlUnit comes with a set of assetions:
assertTitleEquals(HtmlPage, String) assertTitleContains(HtmlPage, String) assertTitleMatches(HtmlPage, String) assertElementPresent(HtmlPage, String) assertElementPresentByXPath(HtmlPage, String) assertElementNotPresent(HtmlPage, String) assertElementNotPresentByXPath(HtmlPage, String) assertTextPresent(HtmlPage, String) assertTextPresentInElement(HtmlPage, String, String) assertTextNotPresent(HtmlPage, String) assertTextNotPresentInElement(HtmlPage, String, String) assertLinkPresent(HtmlPage, String) assertLinkNotPresent(HtmlPage, String) assertLinkPresentWithText(HtmlPage, String) assertLinkNotPresentWithText(HtmlPage, String) assertFormPresent(HtmlPage, String) assertFormNotPresent(HtmlPage, String) assertInputPresent(HtmlPage, String) assertInputNotPresent(HtmlPage, String) assertInputContainsValue(HtmlPage, String, String) assertInputDoesNotContainValue(HtmlPage, String, String)
- You can still of course use the framework’s assertions. For example, if you are using JUnit, you can still use assertTrue() and so on.
- Here are a few examples:
WebClient webClient = new WebClient();
HtmlPage currentPage =
webClient.getPage("http://www.google.com/search?q=htmlunit");
assertEquals(200,currentPage.getWebResponse().getStatusCode());
assertEquals("OK",currentPage.getWebResponse().getStatusMessage());
WebAssert.assertTextPresent(currentPage, "htmlunit");
WebAssert.assertTitleContains(currentPage, "htmlunit");
WebAssert.assertLinkPresentWithText(currentPage, "Advanced search");
assertTrue(currentPage.getByXPath("//h3").size()>0); //result number
assertNotNull(webClient.getCookieManager().getCookie("NID"));
See also
![]() |
If you have ever developed an application for mobile, most chances are you have found yourself wanting to create a settings page. The user uses the settings page to set configuration parameters and these parameters are saved even after the program is closed. In this post I will explain how to create a settings page very easily. All code examples are available to download at the bottom. |
Android designers have developed a framework to make the developers life a lot easier.
Preference Framework is a framework composed of a hierarchy of preference objects which are translated to UI objects.
This mechanism is built on top of the shared preferences mechanism which stores the values.
Shared Preferences Mechanism
Before we can explain how to build a settings page with the preferences framework we need to get to know the shared preferences mechanism.
Shared Preferences is a simple key-value storage mechanism of primitive types and Strings.
These values are stored even if the program is terminated.
Use it to store simple variables you wish to save between sessions of the program.
public class MyActivity extends Activity {
@Override
protected void onCreate(Bundle state){
super.onCreate(state);
// Restore preferences
SharedPreferences settings = getSharedPreferences(“MyParams”, 0); // zero is the default
boolean booleanParam = settings.getBoolean("booleanParam", false); //false is the defaulr
}
@Override
protected void onStop(){
super.onStop();
// Change preferences
SharedPreferences settings = getSharedPreferences(“MyParams”, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("booleanParam", true);
// Save changes
editor.commit();
}
}
Preferences Framework
As mentioned, the preference framework is a framework which is built on top of the shared preferences mechanism.
But opposed to what you have seen above, in this case you don’t even have to save and load the data every time, the OS does that for you.
Furthermore, this framework offers UI objects that hold persistent preferences.
Types of preferences objects
- CheckBoxPreference – displays a checkbox and stores boolean values
- EditTextPreference – displays a edit text box and stores string values
- ListPreference – displays a drop down list.
- RingtonePreference – displays a list of existing ringtones in the system.
Step 1 – Creating XML preferences menu
First we will create the XML file which represents our settings page.
<?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" android:title="Settings"> <PreferenceCategory android:title="First Category"> <CheckBoxPreference android:key="MyBoolean" android:title="Boolean Value"></CheckBoxPreference> <EditTextPreference android:key="MyText" android:title="String Value" android:dialogTitle="Edit this text" android:dependency="MyBoolean"></EditTextPreference> </PreferenceCategory> <PreferenceCategory android:title="Seconed Category"> <RingtonePreference android:showDefault="true" android:key="Audio" android:title="Select sound" android:ringtoneType="notification"> </RingtonePreference> <ListPreference android:title="Group Choice Test " android:entries="@array/PreferencesGroupItems" android:entryValues="@array/PreferencesGroupValues" android:dialogTitle="Choose an option please"> </ListPreference> </PreferenceCategory> </PreferenceScreen>
*Notice:
- You can create categories to divide the preferences to groups according to the context. Here we have created 2 categories.
- ListPreference requires 2 arrays, one for the values and one for the labels. Both are taken from values/strings.xml.
- You can create dependency between prefrences by using the dependency field. For example, I have made the text field depended on the checkbox, which means, it will be disabled if the checkbox is not checked.
- Put this xml file under /res/xml/my_prefrences.xml
Step 2 – Extending the PrefrencesActivity
public class PreferencesActivity extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.my_prefrences);
}
}
- As you see, all this activity does is to load the preferences xml file.
Step 3 – Calling the PrefrencesActivity
Now we will create a button in our main activity that will trigger the preferences activity.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
((Button)findViewById(R.id.Button01))
.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent settingsActivity = new Intent(getBaseContext(),
PreferencesActivityTest.class);
startActivity(settingsActivity);
}
});
}
Step 4 – Using the preferences
We can now use the preferences values anywhere in our main Activity.
SharedPreferences preferences =
PreferenceManager.getDefaultSharedPreferences(this);
String myText = preferences.getString("MyText", "default value");
boolean MyBoolean = preferences.getBoolean("MyBoolean", false);

Custom Preference
You also have the option to add your own customized preference item.
We will talk about this in another post.
| Linkify is a class that lets you create links from a TextView or a Spannable. You can create links not just to web pages, but also to locations on the map, emails and even phone numbers. |
*Note: the examples bellow may not always work in the emulator.
Web address:
TextView myWebSite = new TextView(this);
myWebSite .setText("http://http://www.dzone.com/");
Linkify.addLinks(myWebSite , Linkify.WEB_URLS);

Phone number:
TextView myPhone = (TextView) findViewById(R.id.my_web_site); myPhone .setText(“5552323233”); Linkify.addLinks(myPhone , Linkify.PHONE_NUMBERS);

Map address:
TextView myLocation = new TextView(this);
myLocation.setText("436 Mayfield Ave, Stanford, CA");
Linkify.addLinks(myLocation , Linkify.MAP_ADDRESSES);
mainLayout.addView(myLocation);

Email address:
TextView myEmail= (TextView) findViewById(R.id.my_web_site); myEmail.setText(“aviyehuda@gmail.com”); Linkify.addLinks(myEmail , Linkify.EMAIL_ADDRESSES);

Auto detect:
Use Linkify.ALL to automatically detect the link type.
Linkify.addLinks(myTextView , Linkify.ALL);
More than one option:
You can choose more than a single option for the link type.
Linkify.addLinks(myTextView, Linkify.PHONE_NUMBERS | Linkify.WEB_URLS);
Using pattern:
You can use a regular expression for detecting text parts and transform only them to links instead of the whole text.
TextView myCustomLink = new TextView(this);
Pattern pattern = Pattern.compile("[a-zA-Z]+&");
myCustomLink.setText("press Linkify& or on Android& to search it on google");
Linkify.addLinks(myCustomLink,pattern, "http://www.google.ie/search?q=");
mainLayout.addView(myCustomLink);

MatchFilter:
MatchFilter is used for more complicated filters.
MatchFilter myMatchFilter = new MatchFilter() {
@Override
public boolean acceptMatch(CharSequence cs, int start, int end) {
return start > 48;
}
};
TextView myCustomLink2 = new TextView(this);
Pattern pattern2 = Pattern.compile("[a-zA-Z]+");
myCustomLink2.setText("press one of these words to search it on google: Android Linkify dzone");
Linkify.addLinks(myCustomLink2,pattern2, "http://www.google.ie/search?q=", myMatchFilter, null);
mainLayout.addView(myCustomLink2);

TransformFilter:
So fat the text we have filtered stayed the same. But sometimes you need the text to be different than the text which is appended to the link.
TransformFilter myTransformFilter = new TransformFilter() {
@Override
public String transformUrl(Matcher match, String url) {
return url.substring(1); //remove the $ sign
}
};
TextView myCustomLink3 = new TextView(this);
Pattern pattern3 = Pattern.compile("\\$[a-zA-Z]+");
myCustomLink3.setText("press $Linkify or on $Android to search it on google");
Linkify.addLinks(myCustomLink3,pattern3, "http://www.google.ie/search?q=", null, myTransformFilter);
mainLayout.addView(myCustomLink3);



Recent Comments
Jules on Android Development – Preferences
Also, I like your wooden Gnome. He is cuteJules on Android Development – Preferences
Hey Avi, Your article was very helpful. I was trying to find something in the API to get a TextView to...mona on Memory Game – Android Application
i tried to run the app on blackberry..mona on Memory Game – Android Application
I tried this app..tis app is really cool....but when i run the game ,the spinner option is appearing even i...dante on Weekend project: Bluetooth multisender
how i send image to the devices from java using bluecove?????, this is part of may final proyect please give...Karol on Android – Multithreading in a UI environment
Hi All the examples I see so far implement the Runnable object as inner class of the main...faisal on Memory Game – Android Application
Hi, You have done excellent job. Very nice. Though I tried to build it but it did not build. Could you please...Avi on How to use fiddler+firefox to download files from streaming sites.
Try searching "Mpeg layer-3" instead.ashi on How to use fiddler+firefox to download files from streaming sites.
hi, i tried above i downloaded fiddler2 and also the script editor... also pasted the code but but i have problem in step...Rui Pedrosa on Android – Multithreading in a UI environment
A simple but very useful explanation! thanks!