Source code snippets (examples)

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

A Scala "open URL as InputStream" method (HttpURLConnection)

As a quick note, I just found this getUrlInputStream method in an old Scala project. It needs to be updated and cleaned-up, but if you are looking for some code to get you started with opening a URL as an InputStream in Scala, this may be helpful:

/**
 * See http://alvinalexander.com/blog/post/java/how-open-url-read-contents-http...
 *
 * Note that this can throw a java.net.UnknownHostException
 *
 */
def getUrlInputStream(url: String,
                     connectTimeout: Int = 5000,
                     readTimeout: Int = 5000,
                     requestMethod: String = "GET") = {
   val u = new URL(url)
   val conn = u.openConnection.asInstanceOf[HttpURLConnection]
   HttpURLConnection.setFollowRedirects(false)
   conn.setConnectTimeout(connectTimeout)
   conn.setReadTimeout(readTimeout)
   conn.setRequestMethod(requestMethod)
   conn.connect
   conn.getInputStream
}

Again, the code isn’t great, but it can serve as a starter if you need some code to read from a URL as an input stream in Scala.

Android: An example onCreateView method in a Fragment class

This Java code shows how to implement a couple of things in an onCreateView method inside a Fragment class:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
    getActivity().getActionBar().setDisplayHomeAsUpEnabled(true);
    View rootView = inflater.inflate(R.layout.fragment_single_image, parent, false);
    ImageView imageView = (ImageView)rootView.findViewById(R.id.currentImage);
    imageView.setImageBitmap(currentImage);
    return rootView;
}

What I’m doing here is:

  1. Enabling the Android Back/Up button in the ActionBar
  2. Getting a reference to the “root view” in my layout file
  3. Getting a reference to an ImageView that I know is in that layout file
  4. Setting a bitmap image on that ImageView

If you wanted to see how to do any of these things in a fragment’s onCreateView method, I hope this source code is helpful.

Android: How to add a click listener to a Button (action listener)

As another quick Android example, this Java source code shows how to add a “click listener” (on click/tap event) to an Android Button:

public class MyActivity extends Activity {

     protected void onCreate(Bundle icicle) {
         super.onCreate(icicle);
         setContentView(R.layout.my_layout_id);

         final Button button = (Button) findViewById(R.id.my_cool_button);
         button.setOnClickListener(new View.OnClickListener() {
             public void onClick(View v) {
                 // your handler code here
             }
         });
     }

}

Important things to know are a) you need to add a listener to the Button, b) the listener you need is called an OnClickListener (not an ActionListener or ButtonClickListener, etc.), c) you add the listener with the setOnClickListener method, and d) that you need to implement the onClick method.

If you needed to see how to add a listener to an Android Button, I hope this example code is helpful.

How to keep an Android display turned on while your app is running

If you want to make sure that your users’ Android display stays on while your app is running -- such as if you are writing a game/gaming app -- use this call and flag in the onCreate method of your Android Activity:

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

Here’s what the Android docs say about the FLAG_KEEP_SCREEN_ON setting:

“As long as this window is visible to the user, keep the device's screen turned on and bright.”

To be clear, you can set this in the onCreate method of an Activity, like this:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // ...
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}

How do I make my Android app display in landscape mode only?

Android FAQ: How do I make my Android app display in landscape mode only?

To get an Android application to display in landscape mode only (to lock it in landscape mode), add this line to your Activity definition in the AndroidManifest.xml file:

android:screenOrientation="landscape"

For example, I’m writing an Android football game right now, and this is the definition for my main activity in the Android manifest file:

<activity
    android:name=".MainActivity"
    android:screenOrientation="landscape"
    android:label="@string/app_name" >
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

Note that per the Android Activity documentation you can specify the mode as “landscape,” “sensorLandscape,” or “userLandscape”:

The documentation provides these definitions:

  • landscape - Landscape orientation (the display is wider than it is tall).
  • sensorLandscape - Landscape orientation, but can be either normal or reverse landscape based on the device sensor.
  • userLandscape - Landscape orientation, but can be either normal or reverse landscape based on the device sensor and the user’s sensor preference. If the user has locked sensor-based rotation, this behaves the same as landscape, otherwise it behaves the same as sensorLandscape.

In summary, if you wanted to see how to lock an Android application so that it’s always in landscape mode, I hope this is helpful.

Android Handler and ProgressBar example

This is an Android Handler and ProgressBar example, from the excellent book, Beginning Android 3. (See the URL that I have linked to.)

/***
	Copyright (c) 2008-2009 CommonsWare, LLC
	
	Licensed under the Apache License, Version 2.0 (the "License"); you may
	not use this file except in compliance with the License. You may obtain
	a copy of the License at
		http://www.apache.org/licenses/LICENSE-2.0
	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
 */

package com.commonsware.android.threads;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ProgressBar;

public class HandlerDemo extends Activity
{
  ProgressBar bar;
  Handler handler = new Handler()
  {
    @Override
    public void handleMessage(Message msg)
    {
      bar.incrementProgressBy(5);
    }
  };
  boolean isRunning = false;

  @Override
  public void onCreate(Bundle icicle)
  {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    bar = (ProgressBar) findViewById(R.id.progress);
  }

  public void onStart()
  {
    super.onStart();
    bar.setProgress(0);

    Thread background = new Thread(new Runnable()
    {
      public void run()
      {
        try
        {
          for (int i = 0; i < 20 && isRunning; i++)
          {
            Thread.sleep(1000);
            handler.sendMessage(handler.obtainMessage());
          }
        }
        catch (Throwable t)
        {
          // just end the background thread
        }
      }
    });

    isRunning = true;
    background.start();
  }

  public void onStop()
  {
    super.onStop();
    isRunning = false;
  }
}

foo

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 java.io._
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)
    post.addHeader("appid","YahooDemo")
    post.addHeader("query","umbrella")
    post.addHeader("results","10")

    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:

http://hc.apache.org/httpcomponents-client-ga/httpclient/examples/org/ap...

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"?>
<resources>

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

</resources>

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:

<EditText
    android:id="@+id/quoteTextArea"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textMultiLine"
    android:isScrollContainer="true"
    android:editable="true"
    android:enabled="true"
    android:minLines="6"
    android:maxLines="6"
    android:hint="Type your description here"
    android:textIsSelectable="true"
    android:focusable="true"
    />

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.