Blog


Stop GPS Listener from Pining GPS: Android

When an activity has a registered a LocationListener, sometimes when the back button is pressed the listener does not stop pinging the GPS, draining the battery life. We can stop this by overwriting the onPause() method of that activity like so.

@Override
	protected void onPause() {
		locationManager.removeUpdates(locationListener);
		super.onPause();
	}



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?