Source code snippets (examples)

This is a list of Alvin Alexander's source code snippets (simple source code examples).

A Scala HTTP POST client example (like Java, uses Apache HttpClient)

I created this Scala class as a way to test an HTTP POST request to a web service. Although its written in Scala, it uses the Apache HttpClient Java libraries. I got the NameValuePair code from the URL I've linked to.

import org.apache.commons._
import org.apache.http._
import org.apache.http.client._
import org.apache.http.client.methods.HttpPost
import org.apache.http.impl.client.DefaultHttpClient
import java.util.ArrayList
import org.apache.http.message.BasicNameValuePair
import org.apache.http.client.entity.UrlEncodedFormEntity

object HttpPostTester {

  def main(args: Array[String]) {

    val url = "http://localhost:8080/posttest";

    val post = new HttpPost(url)

    val client = new DefaultHttpClient
    val params = client.getParams
    params.setParameter("foo", "bar")
    val nameValuePairs = new ArrayList[NameValuePair](1)
    nameValuePairs.add(new BasicNameValuePair("registrationid", "123456789"));
    nameValuePairs.add(new BasicNameValuePair("accountType", "GOOGLE"));
    post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    // send the post request
    val response = client.execute(post)
    println("--- HEADERS ---")
    response.getAllHeaders.foreach(arg => println(arg))


Again, the primary reason for creating this HTTP POST client test class is to test the HTTP REST POST listener on the other end. I create these headers, parameters, and name value pairs here, then make sure I can process them properly in my POST server class.

There is some additional HTTP POST "entity" processing at this Apache URL:

How to refer to a built-in Android drawable color in XML

Without looking things up I don’t know when this changed, but ... to refer to a built-in Android color with the android:drawable XML tag, use code like this:

<item android:state_activated="true" android:drawable="@android:color/darker_gray" />
<item android:state_checked="true" android:drawable="@android:color/background_dark" />

From what I’ve seen there used to be a drawable syntax different than @android:color/darker_gray, but I can confirm that this syntax works with Android 5.


Android - How to access a String resource/value from Java code

To access a String resource/value that you’ve defined in an XML file from your Android/Java code, use the Android getString method, like this:

String prefsKeyTimeBetweenNotifications = getString(R.string.prefsKeyTimeBetweenNotifications);

In this example I’ve defined prefsKeyTimeBetweenNotifications as a string resource key in a res/values/strings.xml file, like this:

<?xml version="1.0" encoding="utf-8"?>

    <string name="prefsKeyTimeBetweenNotifications">timeBetweenNotifications</string>


As a word of warning, if you don’t use the getString method you’ll end up retrieving a long value.

What does Android isScrollContainer do? (ScrollView, TextView, EditText)

Android FAQ: What does the Android isScrollContainer XML setting do?

From the Android docs:

Set this if the view will serve as a scrolling container, meaning that it can be resized to shrink its overall window so that there will be space for an input method. If not set, the default value will be true if “scrollbars” has the vertical scrollbar set, else it will be false.

Must be a boolean value, either “true” or “false”.

You set isScrollContainer in the definition of an XML widget like this:

android:isScrollContainer = "true"
android:isScrollContainer = "false"

As a more complete example, I just created an Android EditText component like this:

    android:hint="Type your description here"

isScrollContainer is explained like this on SO:

A scrolling container is one where the size of the container is independent of its content. For instance you can make a ScrollView or ListView of height 100 pixels, but you can fit as much content in as you want.

If a container is scrollable, then Android knows it can shrink the size of the container without rendering parts of the content of the container inaccessible (since the user can just scroll down to see things not on screen). It uses this for when the SoftKeyboard is opened -- if a container is scrollable it will shrink it as much as possible in an attempt to keep all of the elements on screen.

In my example I wanted an EditText field with exactly six lines, and because of my XML definition, that field will scroll if the user types more than that.

Where should the 'assets' directory be when using Android Studio?

Android FAQ: Where should the ’assets’ directory be when using Android Studio?

Solution: If you want to include an assets folder in your project when using Android Studio, create the folder as src/main/assets, i.e., as an assets folder under src/main.

You can later open files in the assets folder using code like this:

InputStream is = getBaseContext().getAssets().open(relativeFilename);

where relativeFilename is the name of your file, like foo.jpg.

Android EditText isScrollContainer example (how to make multiline EditText scrolling)

I just added an editable EditText widget to an Android application, and I needed to make the EditText a certain height, and also make the text in the EditText scroll, in case the user added some really long text. I used the following XML in my Android layout to make this happen:

    android:hint="Type your quote here"

For the stated purposes, these are the most important lines in that EditText XML:


This displays an EditText field that the user can type into, and if they type some text that’s really long, the EditText widget will automatically scroll. (As a result, the EditText field won’t keep getting larger, and hide the text under the keyboard -- and that’s a good thing.)

An Android CheckBox OnClickListener example (and identityHashCode)

Here’s some source code that shows how to add an Android OnClickListener to a CheckBox:

checkBox.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        Log.i(TAG, String.format("checkbox onClick, isSelected: %s, identityHashCode: %s", checkBox.isSelected(), System.identityHashCode(checkBox)));

The OnClickListener code is straightforward, so I won’t explain it; I’m just putting it here so I can find it easily in the future, like a code snippet manager.

One other thing to note is the use of the identityHashCode. I did that because I was having a weird problem working with Android checkboxes. The short story is that I kept trying to use the isSelected method on each CheckBox, which I should have been using isChecked. I used the identityHashCode method to help troubleshoot the problem.

An Android AlertDialog yes/no choice example (and OnClickListener)

Here’s a source code snippet that shows how to create an Android AlertDialog. If I remember right, I got the initial code from Stack Overflow, and then adapted it for my need, which was to confirm that the user wanted to delete an image from an image gallery:

DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int choice) {
        switch (choice) {
            case DialogInterface.BUTTON_POSITIVE:
                try {
                    String rootDir = FileUtils.getImagesDir(getActivity());
                    boolean fileWasDeleted = FileUtils.deleteFile(rootDir + "/" + imageFilename);
                    if (fileWasDeleted) {
                        Toast.makeText(getActivity(), "The file was deleted", Toast.LENGTH_SHORT).show();
                } catch (IOException ioe) {
                    // TODO let the user know the file couldn't be deleted
            case DialogInterface.BUTTON_NEGATIVE:

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Delete this image?")
        .setPositiveButton("Yes", dialogClickListener)
        .setNegativeButton("No", dialogClickListener).show();

If you understand Android programming this code should be pretty straightforward, so I won’t explain it here, other than to say that it looks like typical Java/Android “listener” style programming.

Java source code to get the extension from a filename

While writing some Java code today, I needed a method to get the extension from a filename. This code solved the problem:

public static String getFilenameExtension(String filename) {
    String extension = "NoExtension";
    int i = filename.lastIndexOf('.');
    if (i > 0) {
        extension = filename.substring(i + 1);
    return extension;

Given an input filename like foo.jpg, the getFilenameExtension method returns the “jpg” part as a String.

Warning: I have no idea what this method will do if you pass a null value to it. Don’t do that. (I write my code without null values these days, so I don’t think or account for situations like that.)

A Swift sliderChanged method (handling the Value Changed event)

I’ve seen a few approach to handling a Swift “Value Changed” event, but when you’re only interested in whole number (50, 51, etc.), this approach seems the simplest:

// comes from the Value Changed event
@IBAction func sliderChanged(sender: UISlider) {
    let sliderValue = lroundf(sender.value) //50, 51, ...
    // do something with `sliderValue` ...

I’ve seen people take different approaches to get the slider value, but this approach that uses the lroundf method seems the simplest. With this line of code, sliderValue ends up being an Int.