CS 185C/286 - Lecture 2

Cay S. Horstmann
Lecture 2 Quiz 1
Put your answer into Piazza.
What is “detached mode” in Eclipse?
- Executing a program without the debugger attached.
- A view in a separate window.
- A popup that shows content assistance.
- A philosophical approach to contemplating the Eclipse framework.
Lecture 2 Quiz 2
What does the author least like about Eclipse?
- The plugin architecture.
- FindBugs.
- Refactoring.
- The Run As menu.
Today's Lecture
- Catch up with lab 1
- Just enough to do homework 1
- Layouts
- IDs
- Async tasks
- LogCat
- Permissions
Lab

- Bring your laptop to the lab
- You will work with a buddy
- One of you writes code, the other types up answers
- Switch roles each lab
- Submit lab work to git
Layouts
- Java Swing: Programmatic (e.g.
GridBagLayout
)
- HTML: Declarative
- Visual Basic: Drag and Drop
- Android: All of the above
- Easiest approach: Start with Drag and Drop
- Essential to look at the XML
- For now, just use
RelativeLayout
- Pay attention to
android:layout_below
, android:layout_toRightOf
IDs
AsyncTask
- UI activities occur in UI thread
- Your app is called whenever something interesting happens (startup, button press, etc.)
- When it's your turn, do your thing quickly and return from callback
- If you do something time-consuming (e.g. read data from the web), your app (and maybe the phone) could freeze.
- Android suspends apps with unresponsive UI
- Android won't let you do I/O on the UI thread
- Do time-consuming work on a background thread
AsyncTask
convenience class makes this easy.
AsyncTask
class DownloadTextTask extends AsyncTask<URL, Void, String> {
protected String doInBackground(URLs... urls) {
Scanner in = new Scanner(urls[0].openStream());
StringBuilder result = new StringBuilder();
while (in.hasNext()) { result.append(in.next()); result.append("\n"); }
return result;
}
protected void onPostExecute(String result) {
view.setText(result);
}
}
- Start with
new DownloadTextTask().execute(new URL("http://example.com/fred.txt"));
- Makes a new thread that runs
doInBackground
- When that thread is completed, calls
onPostExecute
on the UI thread
- First type parameter is for launch arguments (using varargs)
- Second type parameter is for progress reports (not covered now)
- Third type parameter is result type
LogCat
Permissions
Reading Before Next Class

- Programming Android Ch.3 Concurrency in Android until the end of AsyncTask and the UI Thread (not including Threads in an Android Process)