Posts Tagged ‘ java ’

Android: What does “Volatile” mean?

At work, I’m currently working on a very large project, and a lot of it was previously written by some very experienced programmers, far beyond my level of skill. When I read through it, I often come across weird things I’ve never seen before (a lot of which gives me the content to post here!) One of these I cam across recently was this word:


Its a strange prefix to a variable name, and the first few times I looked it up, I was not able to find a clear or concise answer. When I try to compile it into simple programs, it never yielded any visible differences. I have found this article from Javamex which put together a rather simple table and explanation of what it actually does.

Essentially, volatile is used to indicate that a variable’s value will be modified by different threads.

Briefly, I can tell you it is related to threads and synchronization, so if your programs don’t have a lot of multi thread functionality, this keyword *probably doesn’t affect you. Check out the article here and feel free to toss in any comments to shed light some more light for our readers!

-Kevin Grant

Android: Ain’t no Callerback grl… (Callback functions in Android)

When I learned about callback functions in Android, it literally created a whole new world of possibilities of what I could do withing my apps. For so long I had used callback functions without even knowing it! An example of a callback function we all already use is with buttons and the onClickListener(). Usually when you create a button, you register a listener, and then you put code into it, like so:

Button btn = (Button) findViewById(yada_yada_yada);
btn.setOnclickListener(new OnClickListener(){
	public void onClick(View v){
		// do something

Basically, whenever you press a button, it sends a callback to this listener you set, and your program can do whatever you want in here. What we want to do now is replicate this sort of callback, but not for a button press. We want to replicate this for ANYTHING! In the example code I provide, we can now do things like this:

rst = new RandomSenderThingy();
rst.setRandomThingyListener(new RandomSenderThingyListener(){
	public void onBoolThingChanged(boolean changed) {
		Log.d("DEBUG","Callback Received! It is: " + changed);

The example code makes use of a few various techniques to get the point across, but I’ve clearly commented the parts that you will need to inject into your own code to get this functionality. Good luck and post any questions or comments in the comments section!

Download the source code here

-Kevin Grant

Formatting and Styling Strings (Java/Android)

So, let’s say you’re reading the Android document on formatting and styling strings and come across the line

Hello, %1$s! You have %2$d new messages.

The document explains that %1$s and %2$d are a string and decimal value, respectively. The next chunk of code is

String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);

Now, how does this relate? Well, the 1$ and 2$ means first and second parameter, respectively. So in this case %1$s is replaced with the variable username and %2$d is replaced with mailCount.

Why should you construct strings this way instead of constructing a string with the plus sign? Well, either way is valid, but this is just the “old” way of constructing strings. There was a time where using the plus sign to construct strings required converting decimal numbers to a string or else the compiler would complain. It was an obnoxious intermediate step. With Java though, the plus sign is smart enough to change the datatype of a decimal to a string if the rest of the line contains strings. To make a string (that contains a number) to a decimal, just add “+ 0” to the end and Java will take care of it. Pretty slick, right?

Wtf is a for each loop?

I only learned this a couple months ago. Its actually very simple. Why they didn’t teach this in school, I don’t know. Maybe its more of a java thing than a C++ thing. In any case, heres how you use it.

Simple example, lets add up all of the ints in this array. Normally I would use a regular for loop

int[] intArray = new int[10];
int total;
for (int i = 0; i < 10; i++){
total += intArray[i];

Instead, lets use a for each. Basically, this means “For each int in the intArray…”

for (int tmpInt : intArray){
total += tmpInt;

This work for everything, like Strings, or even objects. It is most commonly used in lists (from what I’ve seen)

ArrayList<String> stringList = new ArrayList<String>();
for (String tmpString : stringList){
// do something with the string

Have questions on wtf a for each loop is? Leave a comment, I’ll try to answer! Have a better explanation of a for each loop? Leave a comment. This is what I came up with off the top of my head. Chances are theres a better way of doing it.

Writing and Deleting on the SD card, simplified

This should be something easy and intuitive. The internet makes this not so. Here you go, functions for writing and deleting on the SD card. Copy and paste these right into your program. Do you want to clutter up your users SD card with unnecessary files? Do you want to delete all files on your users SD cards? Do so to your hearts content! (Please don’t though, its messed up.)

// Saving a file to the SD card
public void writeFile(String filename, String data){
try {
File root = Environment.getExternalStorageDirectory();
if (root.canWrite()){
// This stores the file on the SD card
File locDataForMachines = new File(root, filename + ".txt");
FileWriter machineWriter = new FileWriter(locDataForMachines, true);
BufferedWriter machineOut = new BufferedWriter(machineWriter);
} catch (Exception e) {
// Do whatever you gotta do, maybe use some other exceptions too
// Deleting a file from the SD card, probably used in conjunction with the function above
public void deleteSDFile(String filename){
File deleteMatchingFiles = new File("/sdcard");
if (deleteMatchingFiles != null){
File[] filenames = deleteMatchingFiles.listFiles();
for (File tmpf : filenames){
if (tmpf.getName().startsWith(filename)){ // can change starts with to anything you want to compare with
}catch(Exception e){
// Do whatever you gotta do, maybe use some other exceptions too

Also, add this to your manifest. I hate how people never remind you what to add to the manifest. Its like they want you to fail.

<uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE”>

Post below and let me know how bad you think this implementation is, or let me know how it helped you. Thanks!

addContentView example simplified

Welcome to! You were probably directed here from my portfolio site,, or by some miracle you were looking for some android code on Google and you happened to stumble here. Basically this site is a way I’m contributing back to the internet by sharing the code I’ve created and found to help your android producing experience easier.

Today, for a first post, I will make a simple yet demanded contribution. First, let me type out all of the searches I made before I got close to my answer

addContentView help, addContentView Android, addContentView Code Android, Adding a xml layout onto a canvas android, how to inflate a view with an xml file, multiple layout xml android, etc, etc.

The list goes on, next time I will actually better document what I searched for, so that hopefully those same searches will direct you here! In any case, by reading those searches, maybe you can see what I wanted to do. I want to draw a couple of buttons from an xml layout onto a canvas. This solution will work with drawing any xml layout onto anything else however.

LayoutInflater inflater = getLayoutInflater();
View tmpView;
tmpView = inflater.inflate(R.layout.extra_layout, null);
getWindow().addContentView(tmpView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,

Alternatively, if you want the code to be a little slimmer, just put the inflater return directly into the addcontent function, as so

LayoutInflater inflater = getLayoutInflater();
getWindow().addContentView(inflater.inflate(R.layout.extra_layout, null), new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,

This code goes into your onCreate(Bundle whateever), preferably right underneath where you just called “setContentView(R.layout.main);”

If you found this helpful, leave a comment! I make no claim that this is the best implementation for this idea, but it works!

Buttons xml overlay


-Kevin Grant