<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Schwiz Logcat &#187; java</title>
	<atom:link href="http://schwiz.net/blog/tag/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://schwiz.net/blog</link>
	<description>Thoughts, feelings, code samples, and more from an aspiring videogame programmer and Android enthusiast.</description>
	<lastBuildDate>Wed, 06 Jul 2011 18:05:05 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Using Scribe with Android</title>
		<link>http://schwiz.net/blog/2011/using-scribe-with-android/</link>
		<comments>http://schwiz.net/blog/2011/using-scribe-with-android/#comments</comments>
		<pubDate>Thu, 14 Apr 2011 02:06:25 +0000</pubDate>
		<dc:creator>Nathan Schwermann</dc:creator>
				<category><![CDATA[android]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[OAuth]]></category>
		<category><![CDATA[sso]]></category>
		<category><![CDATA[twitter]]></category>

		<guid isPermaLink="false">http://schwiz.net/blog/?p=350</guid>
		<description><![CDATA[It just about 80 lines of code we can have the user sign in and verify their account. Of course we have no error handling yet, and the next step would be to move this to the new Fragment API to so you can easily attach it to any Activity to sign in with Twitter.]]></description>
			<content:encoded><![CDATA[<p>Recently I have been working on signing in with social networks with Android applications. I found a great <a href="http://thetechnib.blogspot.com/2011/01/android-sign-in-with-twitter.html">article</a> using Twitter4J to log in with twitter but I would like to expand on that article and rather than relying on an intent-filter and the default android browser I am adding a WebViewClient to handle the callback url.</p>
<p>Using an intent-filter and the default browser has two problems.  One, depending on what browser the user has set as their default browser there is a chance that the browser won&#8217;t initiate an ACTION_VIEW intent but rather just attempt to load the callback url. Secondly, when your app goes into the background and the default browser opens there is a chance that onDestory would be called on the Activity and then onNewIntent wouldn&#8217;t be called. Although that could be handled in a number of different ways. Finally, instead of using Twitter4J I opted for <a href="https://github.com/fernandezpablo85/scribe-java">Scribe</a> instead. Mainly because it is designed to work with and already has support for many other social networks besides Twitter.</p>
<p>It just about 80 lines of code we can have the user sign in and verify their account. Of course we have no error handling yet, and the next step would be to move this to the new <a href="http://developer.android.com/reference/android/app/Fragment.html">Fragment</a> API to so you can easily attach it to any Activity to sign in with Twitter.</p>
<p>&nbsp;</p>
<pre class="brush: java; smart-tabs: true">

package net.schwiz.oauth;

import org.scribe.builder.ServiceBuilder;
import org.scribe.builder.api.TwitterApi;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.model.Verifier;
import org.scribe.oauth.OAuthService;

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

/**
 *Demonstrates how to use the scribe library to login with twitter.
 *
 */
public class Main extends Activity {

	final static String APIKEY = "your api key here";
	final static String APISECRET = "your api secret";
	final static String CALLBACK = "oauth://twitter";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        //set up service and get request token as seen on scribe website
        //https://github.com/fernandezpablo85/scribe-java/wiki/Getting-Started
        final OAuthService s = new ServiceBuilder()
        .provider(TwitterApi.class)
		.apiKey(APIKEY)
		.apiSecret(APISECRET)
		.callback(CALLBACK)
		.build();

		final Token requestToken = s.getRequestToken();
		final String authURL = s.getAuthorizationUrl(requestToken);

		final TextView textView = (TextView)findViewById(R.id.textview);
        final  WebView webview = (WebView) findViewById(R.id.webview);

        //attach WebViewClient to intercept the callback url
        webview.setWebViewClient(new WebViewClient(){
        	@Override
        	public boolean shouldOverrideUrlLoading(WebView view, String url){

        		//check for our custom callback protocol
            //otherwise use default behavior
        		if(url.startsWith("oauth")){
        			//authorization complete hide webview for now.
        			webview.setVisibility(View.GONE);

        			Uri uri = Uri.parse(url);
        			String verifier = uri.getQueryParameter("oauth_verifier");
        			Verifier v = new Verifier(verifier);

        			//save this token for practical use.
        			Token accessToken = s.getAccessToken(requestToken, v);

        			//host twitter detected from callback oauth://twitter
        			if(uri.getHost().equals("twitter")){
        				//requesting xml because its easier
                    //for human to read as it comes back
	        			OAuthRequest req = new OAuthRequest(Verb.GET,
                            "http://api.twitter.com/1/account/verify_credentials.xml");
	        			s.signRequest(accessToken, req);
	        			Response response = req.send();
	        			textView.setText(response.getBody());
        			}

        			return true;
        		}

        		return super.shouldOverrideUrlLoading(view, url);
        	}
        });

        //send user to authorization page
        webview.loadUrl(authURL);
    }
}
</pre>
<p>&nbsp;<br />
Don&#8217;t forget to add the internet permission to your manifest! Also please not you will get a forceclose if you don&#8217;t add your own twitter API key. If you would like the full source code you can find it <a href="http://www.schwiz.net/twitter/TwitterTesting.zip">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://schwiz.net/blog/2011/using-scribe-with-android/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Android &#8211; new line, shmew line</title>
		<link>http://schwiz.net/blog/2010/android-new-line-shmew-line/</link>
		<comments>http://schwiz.net/blog/2010/android-new-line-shmew-line/#comments</comments>
		<pubDate>Wed, 27 Jan 2010 05:33:33 +0000</pubDate>
		<dc:creator>Nathan Schwermann</dc:creator>
				<category><![CDATA[android]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://schwiz.net/blog/?p=185</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>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.  </p>
<p>First your activity or dialog needs to implement OnEditorActionListener, set the onEditorActionListener in onCreate and&#8230;. 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.  </p>
<pre class="brush:java">
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;
	}

}
</pre>
<p>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 &#8216;Next&#8217; 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!<br />
Cheers and happy 2010!</p>
]]></content:encoded>
			<wfw:commentRss>http://schwiz.net/blog/2010/android-new-line-shmew-line/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Android WolframAlpha Launcher</title>
		<link>http://schwiz.net/blog/2009/android-wolframalpha-launcher/</link>
		<comments>http://schwiz.net/blog/2009/android-wolframalpha-launcher/#comments</comments>
		<pubDate>Thu, 17 Sep 2009 05:45:27 +0000</pubDate>
		<dc:creator>Nathan Schwermann</dc:creator>
				<category><![CDATA[android]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[quicklaunch]]></category>
		<category><![CDATA[wolframalpha]]></category>

		<guid isPermaLink="false">http://schwiz.net/blog/?p=160</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>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 <a href="http://www.wolframalpha.com">WolframAlpha</a> 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.</p>
<p>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.</p>
<p>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).<br />
<img class="alignnone size-full wp-image-161" title="WolframAlpha Quicklaunch" src="http://schwiz.net/blog/wp-content/uploads/2009/09/device.png" alt="WolframAlpha Quicklaunch" width="320" height="480" /></p>
<p>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.</p>
<p>In order to pull this off you need to make your own EditText class that inherits from Android&#8217;s EditText class.  Then, you have to override the onKeyDown function for the EditText class.  </p>
<pre class="brush:java">
	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();
		}
	}
</pre>
<p>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</p>
<pre class="brush:xml">
&lt;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">
&lt;/view>
</pre>
<p>Well ok I guess that wasn&#8217;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 <a href="http://code.google.com/p/schwiz-android-apps/source/browse/#svn/trunk/WolframQuickLaunch">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://schwiz.net/blog/2009/android-wolframalpha-launcher/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>text wrapping with JavaME</title>
		<link>http://schwiz.net/blog/2009/text-wrapping-with-javame/</link>
		<comments>http://schwiz.net/blog/2009/text-wrapping-with-javame/#comments</comments>
		<pubDate>Thu, 09 Apr 2009 02:22:32 +0000</pubDate>
		<dc:creator>Nathan Schwermann</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[midp]]></category>
		<category><![CDATA[post mortem]]></category>

		<guid isPermaLink="false">http://schwiz.net/blog/?p=6</guid>
		<description><![CDATA[Recently I had the pleasure of remaking Hunt the Wumpus using JavaME for a school project. I didn&#8217;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&#8217;t take long before I learned the hard way that [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I had the pleasure of remaking Hunt the Wumpus using JavaME for a school project.  I didn&#8217;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&#8217;t take long before I learned the hard way that text doesn&#8217;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.</p>
<p>A quick Google search for &#8216;text wrap midp&#8217; and I found a nice <a href="http://www.devx.com/wireless/Article/21452/1954">article</a> 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&#8217;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.</p>
<table border="0" width="473">
<tbody>
<tr>
<th width="281" scope="col"><img src="http://www.schwiz.net/wumpusME/smallphone.jpg" alt="" width="281" height="618" /></th>
<th width="242" scope="col"><span style="font-weight: normal;">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. </span></th>
</tr>
</tbody>
</table>
<p>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.</p>
<p><code><br />
public void drawDialog(Graphics g, String text, int Y){</code></p>
<p><code>int outerX, innerX , arcValue, Boxwidth, Boxheight, outerY;<br />
outerX = 10; //arbitary<br />
innerX = 12;<br />
arcValue = 5;<br />
Boxwidth = curCanvas.getWidth() - 20;<br />
Boxheight = (g.getFont().stringWidth(text) / Boxwidth ) * g.getFont().getHeight() + g.getFont().getHeight();<br />
outerY = Y - Boxheight - 10;</code></p>
<p><code> </code></p>
<p><code> g.setColor(243, 234, 172);<br />
g.fillRoundRect(outerX, outerY, Boxwidth, Boxheight, arcValue, arcValue);<br />
g.setColor(135, 53, 53);<br />
g.fillRoundRect(innerX, outerY + (innerX - outerX), Boxwidth - (innerX - outerX)*2, Boxheight  - (innerX - outerX)*2, arcValue, arcValue);<br />
g.setColor(255, 255, 255);<br />
</code></p>
<p>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.<br />
<code><br />
Font font = g.getFont();<br />
int fontHeight = font.getHeight();<br />
int idx = 0;<br />
int width = Boxwidth;<br />
int lineWidth = 0;<br />
int wordWidth = 0;<br />
int y = outerY ;<br />
int x = innerX + 1;<br />
String curString;<br />
String words[] = new String[500];<br />
StringTokenizer st = new StringTokenizer(text, ' ');<br />
while(st.hasMoreChars()){ //break text into words<br />
words[idx]=st.nextToken();<br />
idx++;<br />
}<br />
for(int stct = 0; stct &lt; idx; stct++){<br />
curString = words[stct];<br />
//measure the word to draw<br />
wordWidth = font.stringWidth(curString);<br />
lineWidth += wordWidth;<br />
//see if new line is needed<br />
if(lineWidth &gt;= width){<br />
y += fontHeight;<br />
lineWidth = wordWidth;<br />
x = innerX + 1;<br />
}<br />
g.drawString(curString, x, y, Graphics.TOP | Graphics.LEFT);<br />
x =  lineWidth + innerX + 1;<br />
}<br />
</code></p>
<p>This worked great, however since I am new to programming in JavaME and Java all together.  I didn&#8217;t realize that you can&#8217;t use generics in JavaME, I&#8217;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&#8217;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.</p>
<p><code><br />
Font font = g.getFont();<br />
int fontHeight = font.getHeight();<br />
//change string to char data<br />
char[] data = new char;<br />
text.getChars(0, text.length(), data, 0);<br />
int width = Boxwidth;<br />
int lineWidth = 0;<br />
int charWidth = 0;</code></p>
<p><code> </code></p>
<p><code> int y = outerY;<br />
int x = innerX + 1;<br />
char ch;<br />
for(int ccnt=0; ccnt &lt; data.length; ccnt++)<br />
{<br />
ch = data[ccnt];<br />
//measure the char to draw<br />
charWidth = font.charWidth(ch);<br />
lineWidth = lineWidth + charWidth;<br />
//see if a new line is needed<br />
if (lineWidth &gt;= (width - 10) &amp;&amp; ch == ' ')<br />
{<br />
y = y + fontHeight;<br />
lineWidth = charWidth;<br />
x = innerX + 1;<br />
}<br />
//draw the char<br />
g.drawChar(ch, x, y,<br />
Graphics.TOP |Graphics.LEFT);<br />
x = lineWidth + innerX + 1;<br />
}<br />
</code></p>
<p>All in all it was a good learning experience and I&#8217;m happy to share it with all of you.  Thanks for reading.</p>
]]></content:encoded>
			<wfw:commentRss>http://schwiz.net/blog/2009/text-wrapping-with-javame/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

