Archive for the ‘tutorial’ Category.

Beginner 2D Drawing In Android

This is a really basic, super dumbed down tutorial for 2D drawing in Android. If you’ve never done it before, this might help. If you’ve ever done it before… you already know this stuff.

And with that out of the way… start a new Android project and put the following into the onCreate method:

setContentView(new MyDrawableView(this));

Near as I can tell, if you want to do any graphics-type drawing in Android, you need to get some level of access to the onDraw method, which resides in the View class. But this means you need to create a new view class. So… create a new class and name it “MyDrawableView”. You should end up with something like this:

public class DrawableView extends View{
Context mContext;

public DrawableView(Context context) {
super
(context);
mContext = context;
}
}

Now, lets add an override for our onDraw method:

@Override

protected void onDraw(Canvas canvas){
Paint myPaint = new Paint();
myPaint.setStrokeWidth(3);
myPaint.setColor(0xFF097286);
canvas.drawCircle(200, 200, 50, myPaint);
canvas.drawBitmap(BitmapFactory.decodeResource(mContext.getResources(), R.drawable.icon), 184, 184, null);
invalidate();
}

What we’ve done here is nothing more than draw a circle and place the application icon in it. The Canvas object holds all the drawing calls (read more about it here) and the draw objects are layered one on top of another in the order that they are called. The “invalidate” method at the end forces a draw on the canvas.

I would provide source code, but I really can’t do much more than recommend that you take a look at source code over at anddev.org for a similar tutorial. They also glance at some very simple procedural animation, so it is definately worth your time if you’re looking a little deeper into basic Android drawing.

Accepting only Numerical Entry in a EditText

This one is really easy.

I’ve been working the last couple weeks with a small crew of developers under the name “Math In Pulbic” developing small math related products for Android. With a name like “Math In Public”, one of the first things we wanted to do was make it so that we could have text entry fields that accepted only numbers. Being somewhat new to Java, I was surprised at how easy this was.

Basically, just grab your EditText widget and add a NumberKeyListener as the default key listener:

MyEditText.setKeyListener(new NumberKeyListener(){
   @Override
   protected char[] getAcceptedChars() {
      char[] numberChars = {’1′,’2′,’3′,’4′,’5′,’6′,’7′,’8′,’9′,’0′,‘.’};
      return numberChars;
   }
});

The getAcceptedChars() method allows you to select specifically which characters you want to allow. So you could allow basic mathematical functions (+, =, -, /, *, etc) with this method as well.

How To Get the Camera Preview To Render Properly in Portrait Mode

OK, so you want to do something with the Android camera, but everytime you pull it up, it has auto-rotated the image 90 degrees and skewed it. And you don’t like this one little bit.

There is help, my friend.

Basically, if you’ve walked yourself through this Camera Preview tutorial and you can’t seem to get your image to display properly in portrait mode (when the keyboard is closed), it’s because the camera is basically hard wired to work in landscape mode (when the keyboard is open).

The simple fix to this is to add this line of code to your opening activity.

this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

This will force a render in landscape mode even though the keyboard is closed. And your problem is solved.

Changing the Background of a Checked Checkbox

View the java file.

Download tutorial files.

My team, Math In Public (website forthcoming), is releasing our first application today and I will do my best to blog about as many problems and tricks that we ran into along the way. Some things will be kept confidential (in the interest of intellectual property and any NDAs we run up against), but if you see something in our applications and you say to yourself, “How did they do that?” just head over to this blog and, if you don’t see the answer, ask.

While we were building the application, we created one screen with a set of checkboxes. I was uncompelled by the difference between the checked and unchecked states, which did not lend itself toward quick browsing of a large set of checkboxes.

clip_image001[4]

So… let’s change this. Let’s make selected items… blue. Blue is a fun color.

First, we need to create the color we want to use as a resource. Right-click on the “values” folder and create a new file called “colors.xml”. Double click on the file and you should see something like this:

clip_image001[6]

Click the “Add…” button and choose “Color” from the resulting menu. Give your color a name (I used “highlightedColor” and a value (I used #FF227A81).

Next, go into the code that manages your CheckBoxes and, in the onCreate method, make an OnCheckedChangeListener that can be used by multiple checkboxes:

privateOnCheckedChangeListener BasicCheckListener;

Next, we need to actually define the OnCheckedChangeListener. Our OnCheckedChangeListener is going to turn the background blue when the box if checked and turn it back into the default background color if it is unchecked.

BasicCheckListener = newOnCheckedChangeListener(){
      @Override
      public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(isChecked){
                  buttonView.setBackgroundResource(R.color.highlightedColor);
            } else {
                  buttonView.setBackgroundColor(android.R.drawable.screen_background_dark);
            }
      }
};

Now, the only thing we have to do is set this listener to our checkBoxes. If you’re only using one CheckBox, you can do it like this:

CheckBox angel = (CheckBox)findViewById(R.id.angel);

angel.setOnCheckedChangeListener(BasicCheckListener);

If you’re doing a group of CheckBoxes, you can create an array of CheckBoxes and assign the listener to them by iterating through the set like so:

CheckBox[] setOfCheckBoxes = new CheckBox[]
      {(CheckBox)findViewById(R.id.angel),
      (CheckBox)findViewById(R.id.buffy),
      (CheckBox)findViewById(R.id.bg),
      (CheckBox)findViewById(R.id.deadwood),
      (CheckBox)findViewById(R.id.firefly),
      (CheckBox)findViewById(R.id.futurama)};

for(int i = 0; i < setOfCheckBoxes.length; i++){
      setOfCheckBoxes[i].setOnCheckedChangeListener(BasicCheckListener);
}

And our resulting CheckBoxes should look like this:

clip_image001[10]

Note: I gave my CheckBoxes a bottom and top margin of 2 so that the colors wouldn’t run together when sequential items are checked.

Viewing Your SQLite Databases in Android

I was working on a project late last night when I started running up against an extremely frustrating error where when I tried to access my SQLite database and got an error something along the lines of:

“database created a never closed”

This was a huge problem because there was nothing else wrong with my code (I say this in retrospect… I didn’t know it at the time). The fact that I had an error one time was apparently making it impossible for me to access my database and really debug my code. I went looking on the Google Groups and the tone there was (how should I put it?) dismissive. So, now that I’ve finally figured it out, I thought it would be nice for a less judgmental method of solving the problem.

First, debug or run your program… basically, get your emulator up and running. Next, in Eclipse (I’m assuming that you’re using Eclipse), go to “Window –> Open Perspectve –> Other…”

clip_image001

You’ll get a couple options, but you want to select the “DDMS" perspective

clip_image001[5]

From there, you’ll be able to see a Devices tab and an Emulator Control tab. Click on the “File Explorer” tab and go to the “data/data/(your project name)” folder.

clip_image001[7]

You should have three folders… databases, files, and lib. In the databases folder, you should be able to see your database. You can export it to a file and take a look at it with the “pull a file from this device” button (clip_image001[9]) and looking at it with a third party SQLite viewer like SQLite Database Browser. To solve my problem, I just had to delete the database and let my program create it from scratch.

A point of note… as a good testing practice, I recommend deleting all files and databases when you’ve finished the rest of your project and are just running tests on it. That is the best way to see if it will run on a fresh device. Those of you who have downloaded a bunch of stuff from the Android market know what I’m talking about… it seems like a good number of developers aren’t testing their projects outside of the emulator.

Styling Custom Spinner Items

Download the source for this tutorial

 View the java file

It took me forever to figure this out, which will cause you to laugh at me when you see how easy it is.

Basically, I was just trying to change the look of my items when they are in my spinner. The standard solution I’ve seen for this populates the spinner with an array resource (I have a post on populating the spinner dynamically over here) and then assigns a simple spinner style like so:

ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
     
R.array.color_array, android.R.layout.simple_spinner_item);

The last part of the createFromResource method is assigning the ArrayAdapter a resource for the display of items. I tried opening up the android.jar package and looking at the simple_spinner_item.xml, but I couldn’t read any of it. Sad for me.

So I asked around at the Android groups and was given this solutions.

Let’s say that we want our selected spinner item to have red text and show up with 14 point font and display on the right side of the spinner.

First, let’s toss in an array so that we have some items to assign to the spinner. Just copy this code into your strings.xml file: 

<string-array name=“color_array”>
      <item name=“red”>red</item>
      <item name=“green”>green</item>
      <item name=“blue”>blue</item>
</
string-array> 

Now, we’ll make a spinner in our main.xml file. 

<Spinner android:id=“@+id/color_spinner”
     
android:layout_height=“wrap_content”
     
android:layout_width=“fill_parent” />

And assign the spinner your array in the onCreate method of your main activity:

 

Spinner localSpinner = (Spinner)findViewById(R.id.color_spinner);

Now, create a new xml file in your res/layout folder. We’ll call ours my_normal_spinner_item_style.xml to differentiate between how the items look when they are being displayed normally vs. when they are displayed in the selection process:
clip_image001

clip_image001[4]

Add the following code to the new xml file:

<?xml version=“1.0″ encoding=“utf-8″?>
<TextView xmlns:android= http://schemas.android.com/apk/res/android 
     
android:layout_width=“fill_parent”
      android:layout_height=“wrap_content”
      android:textSize=“14pt”
      android:id=“@+id/spinnerTarget”
      android:textColor=“#FF8B1500″
      android:gravity=“center”/>

Now, all we have to do is create an ArrayAdapter that uses this view to display the selected spinner item. Back in your onCreate method, add this code:

ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
      R.array.
color_array, R.layout.my_normal_spinner_item_style);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
localSpinner.setAdapter(adapter);

you should be all set and you app should look something like this:

 

Populating a Spinner (ComboBox) Dynamically

Click here to see the complete java file.

Click here to download the complete project.

OK… since I found so little out there on this, I wanted to post a quick tutorial on populating a spinner dynamically. In this tutorial, we’re going to create a program that allows you to add options to your spinner control (which is what the Android team apparently decided to call a combo box) dynamically and clear out your spinner control.

First, create a new project in Eclipse. Go to your “main.xml” file.

Add the following items:

  • EditView
  • Two Buttons
  • Spinner

Your design view should look like this.

Note: I’ve given all the items a 4px margin, which you can do in the xml like this:

android:layout_margin=”4px”

or you can do it in the design view by going to the “Properties” tab and doing this:

OK… our UI looks pretty much the way we want it to look, so let’s move into the code and set up our spinner.

At the top of your project, declare a spinner like so:

private Spinner m_myDynamicSpinner;

If Eclipse doesn’t like you for doing this, hover over the Spinner and click the “Import ‘Spinner’ (android.widget)” link, which will add “import android.widget.Spinner;” into your import packages.

Do the same thing for an EditText and an ArrayAdapter:

private EditText m_addItemText;
private ArrayAdapter<CharSequence> m_adapterForSpinner;

Now, go into your onCreate method type the following:

m_myDynamicSpinner = (Spinner)findViewById(R.id.dynamicSpinner);
m_addItemText = (EditText)findViewById(R.id.newSpinnerItemText);
Button addButton = (Button)findViewById(R.id.AddBtn);
Button clearButton = (Button)findViewById(R.id.ClearBtn);

This hooks all our local variables into the xml UI.

Next we create our ArrayAdapter, assign it to our spinner, and give it a “dummy item”.

m_adapterForSpinner = new ArrayAdapter(this, android.R.layout.simple_spinner_item);        m_adapterForSpinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
m_myDynamicSpinner.setAdapter(m_adapterForSpinner);
m_adapterForSpinner.add(“dummy item”);

Note: This is different from almost every other example I’ve seen using the spinner. If you look at the samples Google provides us, almost all of them create the spinner items from an array resource using ArrayAdapter.createFromResource(…); (see here for an example). That is fine… as long as you don’t want to dynamically add or change items in your spinner. If you create from a resource and then try to add or clear anything, you’ll get a “Source not found” error.

With that out of the way, let’s make our buttons work by adding some listeners:

addButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
addNewSpinnerItem();
}
});

clearButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
clearSpinnerItems();
}
});

And then, outside the onCreate method, we’ll add the missing methods:

private void addNewSpinnerItem() {
CharSequence textHolder = “” + m_addItemText.getText();
m_adapterForSpinner.add(textHolder);
}

private void clearSpinnerItems() {
m_adapterForSpinner.clear();
m_adapterForSpinner.add(“dummy item”);
}

Now, we can type things into the text box, click the “Add To Spinner” button, and dynamically change our spinner items.