Android – new line, shmew line

Filed Under (android, java, programming | ) by Nathan Schwermann on 26-01-2010

Tagged Under : , ,

In a previous blog post I talked about how to avoid having your users make a new line when the press enter on an EditText view in your Android applications. It was a hack way where you had to make your own EditText class and override onKeyDown. It works just fine but since then I have found a much easier way to achieve the same goal.

First your activity or dialog needs to implement OnEditorActionListener, set the onEditorActionListener in onCreate and…. thats it!!!! Right out of the box the implemented method automatically cancels sends a null character instead of a new line character when you press enter.

public class AdjustStringDialog extends Dialog  implements android.view.View.OnClickListener, OnEditorActionListener{

	private EditText editTextView;

	public AdjustStringDialog(Context context, UnderlinedView mV) {
		super(context);
		setTitle("My Dialog Box");
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.adjuststring);
		retisterViews();
		editTextView.setOnEditorActionListener(this);
	}
	private void retisterViews() {
		editTextView = (EditText)findViewById(R.id.editString);
		findViewById(R.id.finishedAdjustString).setOnClickListener(this);
	}
	@Override
	public void onClick(View v) {
		closeDialog();	

	}
	private void closeDialog() {
		//do what you want with the entered text
		dismiss();
		//update UI with new text if needed
	}
	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		closeDialog();
		return false;
	}

}

Of course you can detect any key that is being pressed aside from the enter key with the event argument, and you can handle cases like the ‘Next’ button with actionId as well. Know any other ways to accomplish this, or care to share something you implemented with onEditorAction feel free to comment!
Cheers and happy 2010!

Android WolframAlpha Launcher

Filed Under (android, java, math, programming | ) by Nathan Schwermann on 16-09-2009

Tagged Under : , , , ,

Ahoy Ahoy it has been way to long I need to write you more often, but I have been busy with school, and before that I had video games to play. Being busy with school is what ultimately let to the project I want to talk about today. Recently, while studying for my Calculus 2 class I found this amazing website WolframAlpha which is what they call a computational engine. It can do all kinds of awesome stuff I have barely scratched the surface on playing with its different capabilities. I mainly use it to quickly look up integrals and sums while doing Calc homework.

Long story short, I ended up using my G1 daily to look up integrals on my phone and I wanted a faster way to do it. After applying for a code to access their online API and never hearing back I decided the next best thing was to just make a quick launcher similar to the one Wolfram released for Vista.

It came together pretty quickly I think its the first program I was able to finish in one day, and bug free to boot (it seems).
WolframAlpha Quicklaunch

It was pretty hassle free but I did run into a little snag I want to talk about. By default when pressing the enter key in the edit text box Android will make a new line, I wanted to launch the website. Getting this behavior was by far the most challenging thing to do in this project.

In order to pull this off you need to make your own EditText class that inherits from Android’s EditText class. Then, you have to override the onKeyDown function for the EditText class.

	public static class MyEditView extends EditText {
		//ref to the nesting the view
		walauncher launcher;

		public MyEditView(Context context, AttributeSet attrs) {
			super(context,attrs);
			this.launcher = (walauncher)context;
		}

		@Override
		public boolean onKeyDown(int keyCode, KeyEvent event) {
			switch(keyCode){
			case KeyEvent.KEYCODE_ENTER:
				launcher.launchWebsite();
				break;
			}
			return super.onKeyDown(keyCode, event);
		}

		@Override
		public Editable getText() {
			// TODO Auto-generated method stub
			return super.getText();
		}
	}

Thats the easy part, what is tricky is how do you actually use it in your XML layout for the app? For starters notice how the class is static in the code above, also it has to be nested inside the Activity class that will be using it. Then in the XML file you need to add a View tag with an attribute called class which equals yourpackage.activityname$nameOfTheCustomClass

<view
	class = "net.schwiz.wolfram.walauncher$MyEditView"
	android:id="@+id/inputID"
	android:text=""
	android:layout_width="fill_parent"
	android:layout_height="wrap_content"
	android:layout_weight="4"
	android:maxLines="1" android:inputType="text|textImeMultiLine">
</view>

Well ok I guess that wasn’t so tuff but it took me a while to find out how to do this on the developers website, they do this in the notepad tutorial though if you want another example. If you want to install my app search for schwiz on the Android Market. I went ahead and released the source, it can be found here.

text wrapping with JavaME

Filed Under (java, programming | ) by Nathan Schwermann on 09-04-2009

Tagged Under : , , ,

Recently I had the pleasure of remaking Hunt the Wumpus using JavaME for a school project. I didn’t think I would run into any big challenges since it is just a text-based adventure game but never-the-less I was excited to program for mobile phones. It didn’t take long before I learned the hard way that text doesn’t automatically wrap around the screen when you draw it. Being that text is the most important part of a text-based game I had to come up with a way to dynamically wrap text around the screen.

A quick Google search for ‘text wrap midp’ and I found a nice article explaining how to do it. I found it was a good starting point, but the example did have some issues. For one, the algorithm they shared didn’t take into account whether or not it started writing on the next line in the middle of a word. Second, their code had a bug in it which would stack the first few characters on top of each other when you went to a new line.

Another issue I had to think about was if the screen was small enough the text would draw right on top of my picture for the current room. So I decided to implement a simple text box for all of my dialog to help the readability. I think that ultimately it turned out looking pretty good.

Lets get down to how it was done. I made a function that took the MIDP graphics reference, a string, and a Y value for where to draw it on the screen. Drawing the box turned out to be fairly easy, MIDP did most of the work for me, other than that I just tweaked the hard coded values till I thought it looked good.


public void drawDialog(Graphics g, String text, int Y){

int outerX, innerX , arcValue, Boxwidth, Boxheight, outerY;
outerX = 10; //arbitary
innerX = 12;
arcValue = 5;
Boxwidth = curCanvas.getWidth() - 20;
Boxheight = (g.getFont().stringWidth(text) / Boxwidth ) * g.getFont().getHeight() + g.getFont().getHeight();
outerY = Y - Boxheight - 10;

g.setColor(243, 234, 172);
g.fillRoundRect(outerX, outerY, Boxwidth, Boxheight, arcValue, arcValue);
g.setColor(135, 53, 53);
g.fillRoundRect(innerX, outerY + (innerX - outerX), Boxwidth - (innerX - outerX)*2, Boxheight - (innerX - outerX)*2, arcValue, arcValue);
g.setColor(255, 255, 255);

Next I decided to use the StringTokenizer class to break my string up into words and use the string length to determine if it is time to draw on the next line yet, instead of characters like the article I found.

Font font = g.getFont();
int fontHeight = font.getHeight();
int idx = 0;
int width = Boxwidth;
int lineWidth = 0;
int wordWidth = 0;
int y = outerY ;
int x = innerX + 1;
String curString;
String words[] = new String[500];
StringTokenizer st = new StringTokenizer(text, ' ');
while(st.hasMoreChars()){ //break text into words
words[idx]=st.nextToken();
idx++;
}
for(int stct = 0; stct < idx; stct++){
curString = words[stct];
//measure the word to draw
wordWidth = font.stringWidth(curString);
lineWidth += wordWidth;
//see if new line is needed
if(lineWidth >= width){
y += fontHeight;
lineWidth = wordWidth;
x = innerX + 1;
}
g.drawString(curString, x, y, Graphics.TOP | Graphics.LEFT);
x = lineWidth + innerX + 1;
}

This worked great, however since I am new to programming in JavaME and Java all together. I didn’t realize that you can’t use generics in JavaME, I’m not sure why NetBeans let it slide, it ran fine in the emulator, but I ran into troubles trying to deploy it to a real cell phone. In fact I couldn’t even compile my project on the Sprint SDK because of including the StringTokenizer class. So ultimately I went back to using individual characters, and I thought of a real easy way to see if I should be drawing on the next line. The only catch is I had to be mindful not to use any words larger than 10 characters, because that was the arbitrary value I chose to check for a new line. At any rate I wish I would have thought of it in the first place because it would have saved me a lot of work.


Font font = g.getFont();
int fontHeight = font.getHeight();
//change string to char data
char[] data = new char[text.length()];
text.getChars(0, text.length(), data, 0);
int width = Boxwidth;
int lineWidth = 0;
int charWidth = 0;

int y = outerY;
int x = innerX + 1;
char ch;
for(int ccnt=0; ccnt < data.length; ccnt++)
{
ch = data[ccnt];
//measure the char to draw
charWidth = font.charWidth(ch);
lineWidth = lineWidth + charWidth;
//see if a new line is needed
if (lineWidth >= (width - 10) && ch == ' ')
{
y = y + fontHeight;
lineWidth = charWidth;
x = innerX + 1;
}
//draw the char
g.drawChar(ch, x, y,
Graphics.TOP |Graphics.LEFT);
x = lineWidth + innerX + 1;
}

All in all it was a good learning experience and I’m happy to share it with all of you. Thanks for reading.