Blog


Process Dialog: Android

  • August 8, 2010

To display a process dialog in Android you can use the following code:

final ProgressDialog pd = ProgressDialog.show(this,
	"Title",
	"Message",
	true, false);

	new Thread(new Runnable(){
        	public void run(){

        	//Execute code in background here

        	pd.dismiss();
        	}
    	}).start();



Print to console in Android using Eclipse: Android

  • June 4, 2010

For the Java programmer, while the move to Android is for the most part great and smooth, there are a few hiccups that he or she must overcome. The most annoying of which is the seeming inability to view System.out.print messages. These are in fact quite easy to get if we are developing in Eclipse however it goes against best practices to use System.out.print.  Instead in Android we should be using the Log class.  See below the screen shot for an example of the Log class.

In Eclipse:
Window > Show View > Other > Android > LogCat > OK

We can now see the print statements in the LogCat. Side Note: LogCat logs almost everything the phone is doing so you might have to wade through the other data to find your print statements.

LogCat Screen Shot

IF IT DOESN’T SHOW ANYTHING: Sometimes when we first use LogCat, the logs are empty. This is often because the emulator or device doesn’t have focus. To fix that go to the DDMS perspective and click the emulator or device on the top left that you want to have focus. When you go back to the Java perspective you should see your logs.

How to Use the Log Class

If you have any control over the code you should try to use the Log class as much as possible.  An example use of Log would be the following.

import android.util.Log;
Log.i("App_Name", "This is the meet of the log");

Here I use .i to indicate an info level log.  The following levels are availible

  • DEBUG – Log.d
  • ERROR – Log.e
  • INFO – Log.i
  • VERBOSE – Log.v
  • WARN – Log.w

Using the Log class allows us to filter on the tags by the tag name or logging level.  Production tag names will typically be the app name but in my debugging I like to use my last name as the tag.  This allows me to quickly filter on my last name and see only the debugging logs without having my last name clutter up the logs themselves.




Image in JScrollPane: Java Swing

  • June 4, 2010

Getting an image to properly display in a scroll pane in Java swing can be frustrating at times however its really not as difficult as we may think. To do this we create an ImageIcon, put it into a JLabel, and then put that JLabel into the JScrollPane. This can also be used to dynamically update the image if, for example, we want to play through the images. Lets look at the following code example.

import java.awt.Dimension;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;

public class testClass {

	//Fields
	private ImageIcon ii;
	private JLabel imageLabel;
	private JScrollPane scrollPane;
	
	public testClass() {
		//Create the JFrame to display on start
		JFrame jfrm = new JFrame();
		jfrm.setPreferredSize(new Dimension(500,500));
		
		//create and link the fields
		ii = new ImageIcon("someFile.gif");
		imageLabel = new JLabel(ii);
		scrollPane = new JScrollPane(imageLabel);
		
		//set size for the scrollPane
		scrollPane.setPreferredSize(new Dimension(400,400));
		
		//add scrollPane to the JFrame and make the JFrame visible
		jfrm.add(scrollPane);
		jfrm.setVisible(true);
	}
	
	public void changeImage(String newImageFileName) {
		//This will change the image.  We can call this function and the image shown by the scroll
		//pane will change after the function returns.
		ii = new ImageIcon(newImageFileName);
		return;
	}
	
	public static void main(String[] args) {
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
            	testClass tc = new testClass();
            }
        });
	}
}



Android: Hide Virtual Keyboard

If we want to hide the virtual keyboard at any point we can use the following code:

//hide the keyboard
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);

The myEditText can be any view such as a TextView or a Button.

The getWindowToken() function will get a unique token identifying the window that the view is attached to.




Android: Difference between pt, px, dp, sp…

This was taken from Stack Overflow here. When I understand it better I hope to expand on this.

px
Pixels – corresponds to actual pixels on the screen.

in
Inches – based on the physical size of the screen.

mm
Millimeters – based on the physical size of the screen.

pt
Points – 1/72 of an inch based on the physical size of the screen.

dp
Density-independent Pixels – an abstract unit that is based on the physical density of the screen. These units are relative to a 160 dpi screen, so one dp is one pixel on a 160 dpi screen. The ratio of dp-to-pixel will change with the screen density, but not necessarily in direct proportion. Note: The compiler accepts both “dip” and “dp”, though “dp” is more consistent with “sp”.

sp
Scale-independent Pixels – this is like the dp unit, but it is also scaled by the user’s font size preference. It is recommend you use this unit when specifying font sizes, so they will be adjusted for both the screen density and user’s preference.




Android: Using Toast in Worker Classes/Threads

  • May 17, 2010

Toasts can get messed up with the contexts if we are making and displaying it from a worker class and or thread such as inside a button listener.  We can use the Context Object to resolve this:

myButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
 
Context context = getApplicationContext();
String msg = "This is the Toast message";
int duration = Toast.LENGTH_LONG;
Toast.makeText(context, msg, duration).show();
return;
}
});



Database Design Tool

  • April 2, 2010

I have been doing some work with mySQL and found a great data base design tool.  I have installed it on this server here if anyone wants to use it.  I am not enabling the data base save feature but you can save and load XML if you wish.  Feel free to use it.

See the below link for the Google code entry for the project.

http://code.google.com/p/wwwsqldesigner/




Prolog if-then-else and knowledge base notes

  • March 31, 2010

I just finished a wumpus world agent in Prolog so I figured I would put up some little notes about what I learned. Hopefully some other newbies will find it helpful.

Knowledge Base:

In Prolog we can use the knowledge base to hold global variables or flags. To add something to the database we use the following commands:

assert(isPit(2,3)),
assert(isPit(4,3)),
assert(isWumpus(2,1)).

Therefore the knowledge base can then be queried for isPit or isWumpus as such:

isPit(Xp,Yp)

This is true because there is an entry in the knowledge base for isPit. Xp and Xy will be set to the first entry Prolog finds. Note that this is not necessarily in numerical order. Also note that if we want Xp or Xy to be set for use later they MUST be capitalized. The ‘_’ operator could be used for a don’t care value.

To remove the items from the knowledge base we can use the following commands:

retractall(isPit(_,_)),
retract(isWumpus(2,1)).

retractall will remove all isPit entries and retract will remove specific entries.

Note that dynamic entries to the database that will change during execution must be noted at the top of the code.  To do this at the top of the code use the following line:

:- dynamic entryName/x.

where x is the number of parameters.

If-then-else statements:

To express if A then B or C you can say:
(A -> B ; C).

Expressions can be chained together as well such as if A1 and A2 then B or C.
((A1,A2)-> B ; C).

When chaining together knowledge base queries we can use the ‘,’ operator or the ‘->’ operator. If we use the -> operator then this will lock in any choices made before the operator. Therefore if we say:

((location(X,Y)->isSafe(X,Y),isVisited(X,Y))-> do this ; else do this.

We are saying find the first X and Y in the knowledge base which are in a location entry and then check if they are isSafe and isVisited. This can potentially fail if there are two location values and one is safe and visited but the other isn’t. IF the other is grabbed first and locked in by the -> operator then it will not go back and check the safe one. To handle that situation just use commas for everything.

SWI specific commands:

Using SWI prolog there are a few usefull commands.  From the terminal we can issue the command “trace.”  This will allow us to trace through the next program we enter using the return key to move to the next instruction.  To exit trace mode use the command “notrace.”

We can also set spy points on a function by typing “spy(funcName/x).” where x is the number of parameters to that function.  Therefore we can run the program to the spy point and if we press “l” it will skip to the next spy point.  To remove these use “nospy(funcName/x).”




The New Google

  • February 19, 2010

There has been a subtle change happening at Google in the past year or so.  A year ago, Google was an internet giant quietly shaping the internet, piece by piece, without much fan fare.  Today, however, Google is becoming an internet giant loudly shaping the internet, piece by piece, with a greater amount of fan fare.

Founded in 1996 by Larry Page and Sergey Brin, Google has grown to be the most prolific internet company in the world.  They are known for having a “no-evil” policy and a great focus on net-neutrality.  Until about a year ago, Google, as a company, had been relatively quiet.  While Microsoft and Apple beat each other up in the trenches, Google stayed generally quiet, soaking up the profits.  Times have changed.

According to Google’s Financial Reports, in 2007, Google saw a 56% growth, in 2008, this dropped to 31%, and in 2009, Google saw an unprecedented low of only 9% growth.  While 9% annual growth would be a great achievement for most other companies, it is a great disappointment for Google.  It, therefore, should come as no surprise to anyone that Google has become more outspoken and brazen in its marketing campaign.

Over Thanksgiving, Android 2.0 was launched with a flurry of TV advertising on a scale never before seen for a Google product.  The TV blitz was handled by Verizon, keeping with Google’s trend of not advertising, but the Google trend was soon to be broken.  In early November, Google, in a very Ungoogle move, swept in right underneath Apple’s nose and bought Admob, a mobile advertising firm.  Also in November, we saw Google publicly flexing its muscles toward China, accusing them of being behind a hacking attempt on Gmail.  In an unprecedented show of force, Google was so steadfast that, for a short time, they affected international relations between the US and China.  Fast forward to February where Google finally broke their trend and ran an ad during the Super Bowl highlighting how much their search engine affects our lives.  We finally come to the most recent Google news, the release of Buzz.  What makes the Buzz release so interesting is that Google called a very public press release and attempted to make as much noise with the launch as they could.

This is clearly new frontier for Google and they haven’t quite gotten it right.  No one can rival Steve Jobs in introducing a new product, and Google has a long way until they can compete with their releases.  Buzz has been hit hard with major problems and the news about the product didn’t explode the way they would have liked.

It remains to be seen whether or not this new strategy is good for Google.  While common sense tells us that for Google to maintain its phenomenal growth in an economy as battered as the one we live in, they would have to get tougher and more outspoken.  While they have enjoyed a near monopoly in the internet search arena with no serious competitors, Google is now a new and much more serious entrant into the smart phone industry with Android 2.0.  They are a minority player in the mobile market and their base is getting threatened by Bing, which is beginning to slowly take up market share.  Google is, for the first time in a long time, somewhat threatened.

Whether the Google we are seeing is in reaction to lowered growth rates, new competitors, or both, it will be interesting to keep an eye on what happens.  For the most part, we can agree that competition helps the consumer, but do we really need to add a third group of vocal fan boys to the Apple Microsoft fight?




Teach Me Pointers

  • February 17, 2010

Many students have been having trouble with pointers, so I am going to attempt to explain them in a very simplistic version. I will assume you, the student, have had minimal exposure to pointers. The examples presented here are applicable to C++ but to use this in C call the malloc() and free() functions instead of new and delete. The dereferencing will be the same for both.

A small review: Pointers live on what is called the heap or free space. This is memory separate from the program stack where general variables are called for example see the following code.

1 int i = 7; //i lives on the program stack
2 int* p = new int; //create a pointer to an int and allocate enough space on the
//heap to hold an int

3 int *p = new int; //same as above
4 int * p = new int; //same as above

We can see that the location of the ‘*’ does not matter when declaring a pointer. This will hold true for accessing pointers as well.

So what is a pointer?
A pointer, while not exactly true, can be thought of as an address. A pointer is still a variable, meaning that it holds a value.  The value that it holds is an memory location.  Therefore if need be you can think of a pointer simply as an address.

Above, when we declared the pointer p, all we did was allocate, or set aside, enough memory for an int, and get the address of that memory and put it to p. Assuming a 32 bit machine that uses 4 bytes for an int,(most Unix, Linux, and Windows systems use this) p holds the address of the first byte, and since the compiler knows that p is an int pointer, it will know to grab the first byte and the next three, four total, to get the full value of the int. If it was a double pointer the complier would grab the allotted number of bytes for a double(generally 8).

How do I set a value to a pointer?
When declaring a pointer you can also define the pointer.(if you are unclear as to the difference between declarations and definitions click here) See the following code example:

int* p = new int(3); //create a pointer to an int and allocate enough space on
//
the heap to hold an int and places the int 3 inside this space
int *p = new int(3); //same as above
int * p = new int(3); //same as above

Here when we created a the pointer p we set the value held in the heap to be 3. THIS DOES NOT MEAN THAT p==3. p is still a pointer meaning that p is the address to an int in the heap which has the value of 3. If we want the value of p we must dereference the pointer.

See the following code example:

1 int* p = new int(3); //create a pointer to an int and allocate enough space on2 //the heap to hold an int and places the int 3 inside this space
3
4 cout << The address of p = << p << endl; //prints: The address of p = xxxxxxxxx5 //xxxxxxxxx is the address held by p, this will most likely be a huge number over 10^8.
5
6

7 cout << The value of p = << *p << endl; //prints: The value of p = 38 //*p derefences p meaning that it will print the value held at the address p which we set to be equal to 3 when we created p.
We see that on line 7 to print the 3 we had to “dereference” the pointer p. This is done with the * operator. When a dereference is done the following pseudo code will be executed:

1. Go to address held by p
2. Get the int held at p by accessing the four byte(assuming machine uses 4 byte ints)
3. Return this int

How do pointer arrays work?
The memory in computer is in its rawest form one massive array and therefore it easily transfers to pointer arrays. Lets look at some example code:

1 char *myArray = new char[3] //allocate a sequential sector big enough for three chars and put the address of the first char to the pointer array.
2
3 myArray[0] = a; //assign the first char in the array to be ‘a’
4 myArray[1] = b; //assign the second char in the array to be ‘b’
5 myArray[2] = c; //assign the third char in the array to be ‘c’
6
7 cout << “Third element in array = << array[2];
//
Prints: “Second element in array = c”
8
9 cout << “Third element in array = << *(array + 2*sizeof(char));//Prints same as above. See explanation for why this is true.

It is important to note that the [] operator will actually dereference array. This is what allows us to write array[2] = ‘c’ such as in line 5. Before we go into more detail about this lets take a look at line 9 and most specically the part of the statement *(array + 2*sizeof(char)). Lets break this down:

-sizeof(char) returns the size of a char(1 byte)
-2*sizeof(char) will be the amount of memory held by two chars.
-remember that myArray is a pointer to the first element of the array.
-(myArray + 2*sizeof(char)) will return the address two characters away from the begining of the array. This is simply array[2] because is the third position of the array not just two characters away from the first? (if this does not make sense try drawing out the array)
-*(myArray + 2*sizeof(char)) will return the value held at array[2]. Remember that (myArray + 2*sizeof(char)) is the address of the third element so dereferencing that will simply give us the value held at the third index of the array.

When we use the statement myArray[2] the compiler will actually follow the procedure outlined above. The compiler of course will be optimized and to increase readability in your code it is highly advised to use the [] notation instead of incrementing your pointer each time. This will also help reduce errors in the code.

What is the & operator and how does it relate to pointers?
The & operator will actually return the address of the object it is applied to. We say we are “dereferencing” a pointer but the & “references” an object so it does the revers of a dereference. see the following code:

1 int i = 7;2 int *ptr = new int(4);3
4 cout << value of i = << i << address of i = << &i;
5 //prints: “value of i = 7 address of i = xxxxxxxx where xxxxxxxx is the address of i in the stack(most likely above 10^8)
6
7 cout << value of ptr = << *ptr << address of ptr = << ptr<< which is the same as << &(*ptr);8 //prints: value of ptr = 4 address of ptr = xxxxxxxx which is the same as xxxxxxxx
9 //xxxxxxxx is the address held by ptr(most likely above 10^8)

While the first cout statement is pretty strateforward lets look at the second one. Printing the address of ptr the first way has been explained but why is the same as the second verison? Lets break it down.

-ptr is a pointer that points to an address holding the value 4
-(*ptr) will deference the pointer and return the value 4
-&(*ptr) will find the address of the value 4 returned by (*ptr) which is of course the address held by ptr.

What does the -> operator do on function calls?
The -> operator will dereference the pointer then call the function on the object held at that location. See the following code:

1 string *s = new string(pointers rock);
2
3 cout << length of s = << (*s).size();
4 //prints: “length of s = 13
5
6 cout << length of s = << s->size();
7 //prints: “length of s = 13

We see that both statements do exactly the same thing. The -> operator is a shortcut that simply dereferences the pointer then calls the object on the returned pointer.

What is a NULL pointer?A null pointer is a pointer that points to nothing. You cannot dereference a NULL pointer because, again, the pointer doesn’t point to anything. Null pointers are sometimes unavoidable such as in Linked Lists but if the problem can be solved without their use, this method is desired. Lets look at the following code

1 int *i = NULL;//creates an int pointer, i, that doesn’t point to anything
2 int *i = 0;//different same syntax but means the same as above.
3
4 char *c = NULL; //creates a char pointer, c, that doesn’t point to anything
5 char *c = 0;//once again different syntax but it means the same thing
6
7 cout << *c; //ERROR: no value pointed to by c so no value to print

We can see that the word NULL or the number 0 can be used to assign a pointer to null. On line 7 when we try to output the value at c we get an error. This will most likely come in the form of a segmentation fault at run time. The error comes from the fact that there is nothing that c points to so there is nothing to dereference and print. In general you should almost never dereference a null pointer.

What is a void pointer?
A void pointer is a pointer that points to a location in memory but the compiler doesn’t know its type. Recall that when the compiler prints an int it knows to get n=sizeof(int) bytes to construct the int. Therefore you cannot print a void pointer because there is no way of dereferencing it to an object.

Pointer arithmetic is still very valid for void pointers. You can increment and decrement that pointer just as one would move around an int pointer or a char pointer. Lets look at a code example:

1 int *i = new int[3]; //create an array of ints and populate the array
2 i[0] = 10;
3 i[1] = 20;
4 i[2] = 30;
5
6 void* v; //v is a pointer that can point to any object in the heap.
7
8 v = i; //set the address held by v to the address of the first element in i
9 v + 2*sizeof(int); //v now equals the address of the third element in i
10
11 cout << The third element of i = << (int)v; //cast v to an int before a print12 //Prints: “The third element of i = 30

As explained earlier, i is simply an pointer to an array of ints in the heap. On line 6 we create a void pointer v. On line 6 the address of v is assigned to be the address of i. Remember that a void pointer can point to any type so i could have been a char, double, long, or any other type, even user defined types. Now that v points to the first element of i, when v is moved two ints to the right on line 9 it now will point to the same location as v[2]. Finally on line 11 we want to print the value held at the pointer v. To do this we must cast v to be an int pointer. This tells the compiler to grab n=sizeof(int) bytes and construct an int from these bytes. Note that this cast only lasts for this statment. If we were to use v again in another statement it would still be a void pointer.

So now you should have a generally solid feel on pointers. For further information please see this site. It has good information on pointers.