Beruflich Dokumente
Kultur Dokumente
The market The market is awesome. It's extremely easy to release and update your applications, and I'll be writing a tutorial all about publishing your apps, how to sign them, how to create a jar keystore, all the fun stuff. Get started already!!1!one! Okay. Enough intro, let's get to some development!
...sorry. No programming yet. We're going to be reading the project template, and I'll be explaining it line for line. It's best to take this stuff slow at first, because it's so different to a lot of "regular" projects. But at least there's code! Create a project, you can call it anything, but I'm going to be following this structure along the series of tutorials:
layout.xml The layout.xml is... sorta important. It's a great way to design your user interfaces, but it's not always necessary: you can create your interfaces through pure Java, which is personally my preferred method... but it's still good
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
to know how to use the xml layouts. They help to keep the code for your activity more organised. (Coming from a C++/wxWidgets background, I'm in the habit of creating my programs through pure code, you may prefer the XML process) Right. Enough rambling. I've analysed the ./res/layout/main.xml, and broken it up, line by line. yep: we just use standard XML to declare the layout: view source print?
1 <?xml version="1.0" encoding="utf-8"?>
We use a LinearLayout to define our layout as being, well... linear: view source print?
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
Note the three properties: android:orientation -- which direction the layout is filled. Contrary to what you may think, this isn't based on the angle of the phone. Using "vertical" simply means "add widget number 2 below widget number 1, add widget number 3 below widget number 2, ... add widget number n below widget number n-1". android:layout_width -- the width of the object. We're going to use "fill_parent" to fill the width of the screen android:layout_height -- the height of the object. We're going to use "fill_parent" again, to fill the height of the screen. Lastly, we're going to close the LinearLayout item. Note we want more items inside the LinearLayout, so we're just going to use > instead of /> view source print?
1>
Next, we're going to define a TextView. The TextView is like a Label in .NET, or a wxStaticText in wxWidgets. It basically puts a static piece of text on the screen. view source print?
1 <TextView 2 android:layout_width="fill_parent" 3 4 5 android:layout_height="wrap_content" android:text="@string/hello" />
You'll notice it's pretty similar to how we defined the LinearLayout. Differences: android:layout_height="wrap_content" -- the TextView will be resized according to the text it displays. The
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
longer the string, the taller the View. android:text="@string/hello" -- the string to display. @string refers to the ./res/values/strings.xml file. (More on this later) /> -- this time, we're not putting any other items inside it, so we can close it off XML stylee. We could just as easily use view source print?
1 <TextView ... ></TextView>
but it seems a little pointless here. Since that's all we want in the LinearLayout, we're going to close our layout off: view source print?
1 </LinearLayout>
strings.xml This one's much simpler. Put simply, this file contains strings which are built in to the application at compile time. Note the hello string, which we referenced in our TextView in ./res/layout/main.xml view source print?
1 <?xml version="1.0" encoding="utf-8"?> 2 <resources> 3 4 <string name="hello">Hello World, dic_tut1!</string> <string name="app_name">dic_tut1</string>
5 </resources>
The Java! Lastly, we're going to put our layout together in the code. I've commented this bit up, so it's easy for you to understand. view source print?
01 package dreamincode.tutorials.part_one; 02 03 import android.app.Activity; // Activity: the "main" part of the application import android.os.Bundle; // Bundle: stores a "saved state" for your app to remember how 04 it was when moved to the background 05 06 public class dic_tut1 extends Activity { // inheriting the Activity class 07 08 09 /** Called when the activity is first created. */ @Override
public void onCreate(Bundle savedInstanceState) { // consider this the "entry point" (main) of your application super.onCreate(savedInstanceState); // call the super to restore the state 10 (does the work for you) setContentView(R.layout.main); // set the main content view to ./res/layout/main.xml 12 } 11
13 }
Basic Layouts and Events Now that we got the basics done, it's time to get into developing our first app. It's not the most impressive application, but it's a great starting point.
This will most likely seem very familiar if you've learned programming on the console in the past. We're going to prompt for a name, and display a customised message. However, we'll have a user interface rather than printing on the console.
We're going to start with the XML. We need a layout which we can program around.
Step 0: Creating the project So we're on the same wavelength, let's use the same project name, package, etc.
Step 1: Putting the UI XML together I'll run through this one element at a time. it's all really simple, and you should recognise a lot of this from part 1.
To start, remember, it's XML:
<?xml version="1.0" encoding="utf-8"?>
We're going to use a linear layout, which fills the parent and has a vertical layout (again)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" >
Next, we're going to the first TextView. Remember, the TextView is like a "Label", from .NET. At this point, all we need to do is set the width, height, and set the text. This time, we're just going to use a static string, rather than linking into the ./res/values/strings.xml file.
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Enter your name:" />
The next thing we need in our LinearLayout is an EditText. This is basically a TextBox.
<EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/txt_name" />
Only one new thing here, we give it an ID. We need to give it an ID so that we can reference it in the actual Java application. android:id="@+id/txt_name" -- I'll call it txt_name, I like to prefix my widgets so they're easier to remember and reference later on. Only two things left now: The Button, and the TextView. Nothing new in either of these now.
<Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/btn_confirm" android:text="Confirm~" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/tv_welcome" />
Note that we don't set the android:text attribute in the final TextView? That's because we're going to give it its text when the user presses the "Confirm" button. (btn_confirm) Lastly, we just need to close off our layout:
</LinearLayout>
Step 2: Bringing it all together in Java This time we're going to write our own Java. We're going to use multiple inheritance (don't be put off, it's really very simple) so that we can make our class both an Activity (the main application) and an onclickListener (to listen for clicks on the button)
First up, remember we're working on a package:
package dreamincode.tutorials.part_two;
Next, we're going to import some stuff. The first two are nothing new:
import android.app.Activity; import android.os.Bundle;
Remember we used both of these in part 1. This is where it gets interesting, though. We're going to import three widgets.
import android.widget.TextView; import android.widget.EditText; import android.widget.Button;
I won't explain them... hopefully your memory is good enough to remember that we used these names in the XML layout earlier. The next two will take a little explaining.
import android.view.View; import android.view.View.onclickListener;
- We import the View because that's the parameter which our onclick event requires. - We import the onclickListener because, well... we want our Activity to be an onclickListener, too. This is where the multiple inheritance comes in. We're calling our class dic_tut2, and it's going to extend Activity, just like we did in part 1. It's also going to implement onclickListener because we're going to be listening for clicks on the button.
public class dic_tut2 extends Activity implements onclickListener {
Now it's time for the onCreate method. Just like we did in part 1, only with a few extra lines (explained afterwards!)
/** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button b = (Button)this.findViewById(R.id.btn_confirm); b.setonclickListener(this); }
Specifically, the last two lines are the new ones. We're going to create a Button from R.id.btn_confirm (remember, that's the ID we used in the XML!) Then we're simply going to set this as the onclickListener for said button. Simple stuff, eh? NOTE: We need to cast the return value of findViewById() to a Button, by default it will return a View. The very last thing we need to do is set our onclick method: the one which is called when the user clicks the button (after we set this as the onclickListener for said button!)
@Override public void onclick(View v) { TextView tv = (TextView)this.findViewById(R.id.tv_welcome); EditText et = (EditText)this.findViewById(R.id.txt_name); String text = "Hello, " + et.getText().toString() + ".\n\n"; text += "Welcome to android development. :)"; tv.setText(text); }
Note that we use findViewById() again to get the TextView for which we're going to set the text, and also the EditText which contains the user's name. Then, all we do is create our string (I hope this is nothing new!) and simply setText() on our TextView which displays the final message. Don't forget to close off your class!
}
public class dic_tut2 extends Activity implements onclickListener { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button b = (Button)this.findViewById(R.id.btn_confirm); b.setonclickListener(this); } @Override public void onclick(View v) { TextView tv = (TextView)this.findViewById(R.id.tv_welcome); EditText et = (EditText)this.findViewById(R.id.txt_name); String text = "Hello, " + et.getText().toString() + ".\n\n"; text += "Welcome to android development. :)"; tv.setText(text); } }
android:id="@+id/txt_name" /> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/btn_confirm" android:text="Confirm~" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/tv_welcome" /> </LinearLayout>
Okay, so let's get started. We won't be touching on events in this tutorial, our app won't actually do anything, per se... it's merely an example of adding stuff dynamically. You'll notice how we set the properties through Java, quite similarly to how we define them in the XML.
Next, we're going to import the usual suspects... Activity and Bundle. view source print?
1 import android.app.Activity; 2 import android.os.Bundle;
The next two are new. One you may recognise from our layouts before... LinearLayout. We're also going to use a ScrollView. The reason we'll be using a ScrollView is that we're going to add a hell of a lot of widgets, and they wouldn't all fit on screen. If we don't put our LinearLayout inside a ScrollView, it simply won't scroll and the user won't be able to reach all the widgets! view source print?
1 import android.widget.ScrollView; 2 import android.widget.LinearLayout;
The last things we need to import are our widgets. We'll be using an EditText, a TextView, a Button and a CheckBox. We've already seen the first three in parts 1 and 2 of this tutorial, but the CheckBox is new. (And I hope the name is selfexplanatory for what it is!) A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
Now it's time to get on with our code. We're only going to extend Activity this time, remember we won't be using events. This bit's nothing new, so I'll just throw in the opening of the class and the opening of the onCreate() method. (Note, if you're not familiar with this, check part 1 and part 2) view source print?
1 public class dic_tut3 extends Activity { 2 3 4 5 /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
Time to get dirty. Dynamic layouts aren't always the most elegant of solutions, but they can be fun, and sometimes easier to implement. They're also really useful for certain occasions (such as SmartCalc*, my app: it uses a dynamic layout to decide how many textboxes are needed at runtime) * No link, it's a paid app and I don't want to look like an ad whore. Code first, explanation afterwards. view source print?
1 ScrollView sv = new ScrollView(this); 2 LinearLayout ll = new LinearLayout(this); 3 ll.setOrientation(LinearLayout.VERTICAL);
4 sv.addView(ll);
LINE 1: Creates a ScrollView object, which is a part of this Activity. LINE 2: Creates a LinearLayout object, which you hopefully remember from the layout.xml we discussed before. LINE 3: Sets the orientation of our LinearLayout. Remember how we used android:orientation="vertical" before? Same principal applies here. LINE 4: Adds the LinearLayout to the ScrollView. Remember, we want to be able to Scroll the LinearLayout View. NOTE: A ScrollView can **only** have one view added to it. If you try to add more than one, your application WILL force close. If you need to reset it, use ScrollView.removeAllViews(); and re-add whatever you need. (This is why we're going to add all our widgets to the LinearLayout as opposed to the ScrollView!) Adding widgets dynamically Actually, this same principal applies to all our widgets. But I'll use a few, just to demonstrate. This one should look relatively familiar, since we played with TextView.setText() in part 2. view source print?
1 TextView tv = new TextView(this); 2 tv.setText("Dynamic layouts ftw!"); 3 ll.addView(tv);
Notice how we use addView() on ll, our LinearLayout, just like we added ll to sv? That's all it takes! Now, let's do a Button and a EditText. Same principal, just like I said: view source print?
1 EditText et = new EditText(this); 2 et.setText("weeeeeeeeeee~!"); 3 ll.addView(et); 4 5 Button b = new Button(this); 6 b.setText("I don't do anything, but I was added dynamically. :)"); 7 ll.addView(b);
(Remember, when you run the application, the button won't actually do anything: We haven't added an onclickListener! If you want, you may want to revisit the button at the end of this tutorial and try adding an event by yourself. (Use part 2 of this series as a reference if you get stuck) The next is still the same principal, but I've added it in a loop. 20 pointless CheckBoxes, coming up! view source print?
1 for(int i = 0; i < 20; i++) { 2 3 4 5} CheckBox cb = new CheckBox(this); cb.setText("I'm dynamic!"); ll.addView(cb);
This is really just to pad out our layout, so we can really see how useful that ScrollView is. The very last thing we need to do is use setContentView() -- similar to how we did before. Remember the this.setContentView(R.layout.main);? Pretty much the same, only now we're going to use the ScrollView we created earlier instead: view source print?
1 this.setContentView(sv);
And lastly, close off the method and class! view source print?
1 2} }
Now, if you run this, you'll get a rather crude, but biiiig layout, complete with all the widgets that we added dynamically. Complete code: A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 } }
Button b = new Button(this); b.setText("I don't do anything, but I was added dynamically. :)"); ll.addView(b);
for(int i = 0; i < 20; i++) { CheckBox cb = new CheckBox(this); cb.setText("I'm dynamic!"); ll.addView(cb); } this.setContentView(sv);
See if you can add an onclickListener to the button, just have a play about with it until you feel fairly confident... I won't be explaining too much about the layouts in the coming tutorials, more on actual features such as SQLite. Complete project: dic_tut3.zip (25.83K) Number of downloads: 898 Be social: http://ohai.im/gabehabe | Does it work in Internet Explorer? ohai.im -- a social portal [feedback] http://gabehabe.com <|--- best website ever. Snippet Manager. Windows only at the moment, slow development but worth a look. :) A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
#2 Guest_dalf*
Reputation:
#3 Guest_tommy*
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
Reputation:
derefence the layout you want and make it find the name you gave in the xml file (RelativeLayout) findViewById(R.id.RelativeLayout01); same with the button but if you make 20 buttons, just drop the xml file and write Button bt0 = new Button(this); bt0.setId(0); Button bt1 = new Button (this); bt.setId(1); don't forget to add the buttons to the view...
Databases and Menus Two for the price of one in this tutorial, actually. We're going to learn about SQLite databases and menus. I'm hoping you'll at least be slightly familiar with databases already, though SQLite is really quite simple. You can pick up the basics, of which we'll be using in this tutorial, at the following links:
CREATE TABLE
create-table-stmt:
column-def:
type-name:
column-constraint:
table-constraint:
foreign-key-clause:
The "CREATE TABLE" command is used to create a new table in an SQLite database. A CREATE TABLE command specifies the following attributes of the new table:
The name of the new table. The database in which the new table is created. Tables may be created in the main database, the temp database, or in any attached database. The name of each column in the table. The declared type of each column in the table. A default value or expression for each column in the table. A default collation sequence to use with each column. Optionally, a PRIMARY KEY for the table. Both single column and composite (multiple column) primary keys are supported. A set of SQL constraints for each table. SQLite supports UNIQUE, NOT NULL, CHECK and FOREIGN KEY constraints.
Every CREATE TABLE statement must specify a name for the new table. Table names that begin with "sqlite_" are reserved for internal use. It is an error to attempt to create a table with a name that starts with "sqlite_". If a <database-name> is specified, it must be either "main", "temp", or the name of an attached database. In this case the new table is created in the named database. If the "TEMP" or "TEMPORARY" keyword occurs between the "CREATE" and "TABLE" then the new table is created in the temp database. It is an error to specify both a <database-name> and the TEMP or TEMPORARY keyword, unless the <database-name> is "temp". If no database name is specified and the TEMP keyword is not present then the table is created in the main database. It is usually an error to attempt to create a new table in a database that already contains a table, index or view of the same name. However, if the "IF NOT EXISTS" clause is specified as part of the CREATE TABLE statement and a table or view of the same name already exists, the CREATE TABLE command simply has no effect (and no error message is returned). An error is still returned if the table cannot be created because of an existing index, even if the "IF NOT EXISTS" clause is specified. It is not an error to create a table that has the same name as an existing trigger. Tables are removed using the DROP TABLE statement.
A table created using CREATE TABLE AS has no PRIMARY KEY and no constraints of any kind. The default value of each column is NULL. The default collation sequence for each column of the new table is BINARY. Tables created using CREATE TABLE AS are initially populated with the rows of data returned by the SELECT statement. Rows are assigned contiguously ascending rowid values, starting with 1, in the order that they are returned by the SELECT statement.
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
Column Definitions
Unless it is a CREATE TABLE ... AS SELECT statement, a CREATE TABLE includes one or more column definitions, optionally followed by a list of table constraints. Each column definition consists of the name of the column, optionally followed by the declared type of the column, then one or more optional column constraints. Included in the definition of "column constraints" for the purposes of the previous statement are the COLLATE and DEFAULT clauses, even though these are not really constraints in the sense that they do not restrict the data that the table may contain. The other constraints - NOT NULL, CHECK, UNIQUE, PRIMARY KEY and FOREIGN KEY constraints - impose restrictions on the tables data, and are are described under SQL Data Constraints below. Unlike most SQL databases, SQLite does not restrict the type of data that may be inserted into a column based on the columns declared type. Instead, SQLite uses dynamic typing. The declared type of a column is used to determine the affinity of the column only. The DEFAULT clause specifies a default value to use for the column if no value is explicitly provided by the user when doing an INSERT. If there is no explicit DEFAULT clause attached to a column definition, then the default value of the column is NULL. An explicit DEFAULT clause may specify that the default value is NULL, a string constant, a blob constant, a signed-number, or any constant expression enclosed in parentheses. An explicit default value may also be one of the special case-independent keywords CURRENT_TIME, CURRENT_DATE or CURRENT_TIMESTAMP. For the purposes of the DEFAULT clause, an expression is considered constant provided that it does not contain any sub-queries or string constants enclosed in double quotes. Each time a row is inserted into the table by an INSERT statement that does not provide explicit values for all table columns the values stored in the new row are determined by their default values, as follows:
If the default value of the column is a constant NULL, text, blob or signed-number value, then that value is used directly in the new row. If the default value of a column is an expression in parentheses, then the expression is evaluated once for each row inserted and the results used in the new row. If the default value of a column is CURRENT_TIME, CURRENT_DATE or CURRENT_DATETIME, then the value used in the new row is a text representation of the current UTC date and/or time. For CURRENT_TIME, the format of the value is "HH:MM:SS". For CURRENT_DATE, "YYYY-MMDD". The format for CURRENT_TIMESTAMP is "YYYY-MM-DD HH:MM:SS".
The COLLATE clause specifies the name of a collating sequence to use as the default collation sequence for the column. If no COLLATE clause is specified, the default collation sequence is BINARY. The number of columns in a table is limited by the SQLITE_MAX_COLUMN compile-time parameter. A single row of a table cannot store more than SQLITE_MAX_LENGTH bytes of data. Both of these limits can be lowered at runtime using the sqlite3_limit() C/C++ interface.
If a table has a single column primary key, and the declared type of that column is "INTEGER", then the column is known as an INTEGER PRIMARY KEY. See below for a description of the special properties and behaviours associated with an INTEGER PRIMARY KEY. Each row in a table with a primary key must feature a unique combination of values in its primary key columns. For the purposes of determining the uniqueness of primary key values, NULL values are considered distinct from all other values, including other NULLs. If an INSERT or UPDATE statement attempts to modify the table content so that two or more rows feature identical primary key values, it is a constraint violation. According to the SQL standard, PRIMARY KEY should always imply NOT NULL. Unfortunately, due to a long-standing coding oversight, this is not the case in SQLite. Unless the column is an INTEGER PRIMARY KEY SQLite allows NULL values in a PRIMARY KEY column. We could change SQLite to conform to the standard (and we might do so in the future), but by the time the oversight was discovered, SQLite was in such wide use that we feared breaking legacy code if we fixed the problem. So for now we have chosen to continue allowing NULLs in PRIMARY KEY columns. Developers should be aware, however, that we may change SQLite to conform to the SQL standard in future and should design new programs accordingly. A UNIQUE constraint is similar to a PRIMARY KEY constraint, except that a single table may have any number of UNIQUE constraints. For each UNIQUE constraint on the table, each row must feature a unique combination of values in the columns identified by the UNIQUE constraint. As with PRIMARY KEY constraints, for the purposes of UNIQUE constraints NULL values are considered distinct from all other values (including other NULLs). If an INSERT or UPDATE statement attempts to modify the table content so that two or more rows feature identical values in a set of columns that are subject to a UNIQUE constraint, it is a constraint violation. INTEGER PRIMARY KEY columns aside, both UNIQUE and PRIMARY KEY constraints are implemented by creating an index in the database (in the same way as a "CREATE UNIQUE INDEX" statement would). Such an index is used like any other index in the database to optimize queries. As a result, there often no advantage (but significant overhead) in creating an index on a set of columns that are already collectively subject to a UNIQUE or PRIMARY KEY constraint. A CHECK constraint may be attached to a column definition or specified as a table constraint. In practice it makes no difference. Each time a new row is inserted into the table or an existing row is updated, the expression associated with each CHECK constraint is evaluated and cast to a NUMERIC value in the same way as a CAST expression. If the result is zero (integer value 0 or real value 0.0), then a constraint violation has occurred. If the CHECK expression evaluates to NULL, or any other non-zero value, it is not a constraint violation. CHECK constraints have been supported since version 3.3.0. Prior to version 3.3.0, CHECK constraints were parsed but not enforced. A NOT NULL constraint may only be attached to a column definition, not specified as a table constraint. Not surprisingly, a NOT NULL constraint dictates that the associated column may not contain a NULL value. Attempting to set the column value to NULL when inserting a new row or updating an existing one causes a constraint violation. Exactly how a constraint violation is dealt with is determined by the constraint conflict resolution algorithm. Each PRIMARY KEY, UNIQUE, NOT NULL and CHECK constraint has a default conflict resolution algorithm. PRIMARY KEY, UNIQUE and NOT NULL constraints may be explicitly assigned a default conflict resolution algorithm by including a conflict-clause in their definitions. Or, if a constraint definition does not include a conflict-clause or it is a CHECK constraint, the default conflict resolution algorithm is
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
ABORT. Different constraints within the same table may have different default conflict resolution algorithms. See the section titled ON CONFLICT for additional information.
But the following declaration does not result in "x" being an alias for the rowid:
CREATE TABLE t(x INTEGER PRIMARY KEY DESC, y, z);
Rowid values may be modified using an UPDATE statement in the same way as any other column value can, either using one of the built-in aliases ("rowid", "oid" or "_rowid_") or by using an alias created by an integer primary key. Similarly, an INSERT statement may provide a value to use as the rowid for each row inserted. Unlike normal SQLite columns, an integer primary key or rowid column must contain integer values. Integer primary key or rowid columns are not able to hold floating point values, strings, BLOBs, or NULLs. If an UPDATE statement attempts to set an integer primary key or rowid column to a NULL or blob value, or to a string or real value that cannot be losslessly converted to an integer, a "datatype mismatch" error occurs and the statement is aborted. If an INSERT statement attempts to insert a blob value, or a string or real value that cannot be losslessly converted to an integer into an integer primary key or rowid column, a "datatype mismatch" error occurs and the statement is aborted.
If an INSERT statement attempts to insert a NULL value into a rowid or integer primary key column, the system chooses an integer value to use as the rowid automatically. A detailed description of how this is done is provided separately. The parent key of a foreign key constraint is not allowed to use the rowid. The parent key must used named columns only.
It may look a little intimidating, but once you get to grips with it, it's actually quite close to English. We won't be creating the most sexy application, but databases are an important aspect of a lot of software design, including android.
Let's get to it. As usual, we're creating a package: view source print?
1 package dreamincode.tutorials.dic_tut4;
print?
1 import android.app.Activity; 2 import android.os.Bundle;
Now there's quite a lot that we're going to import that hasn't already been covered, but do not panic. I'll explain it all as we go along, and it's honestly nothing to worry about. First up, a ListView. This is just another widget, and it's... well, it's a list. view source print?
1 import android.widget.ListView;
Next, we'll import the stuff related to the menu. We'll be using a Menu, and a couple of MenuItems. view source print?
1 import android.view.Menu; 2 import android.view.MenuItem;
The next bits are related to the database. The first is self-explanatory, it's a database. The second is a Cursor. A cursor is a way we can store temporary results from a table in memory. (We select stuff into it, explained a little later... keep reading!) view source print?
1 import android.database.sqlite.SQLiteDatabase; 2 import android.database.Cursor;
And finally, we're going to import an ArrayList to add our results into, and an ArrayAdapter to basically plug our ArrayList into the list. Again, this will be explained later, at this point all we really have is an overview. view source print?
1 import android.widget.ArrayAdapter;
2 import java.util.ArrayList;
On to the main part of the code, now. First off, we'll open up our class and add a few variables. We'll have a ListView, an SQLiteDatabase, and a few ints for the IDs of our menu items. view source print?
1 public class dic_tut4 extends Activity { 2 3 4 5 6 private static final int MENU_ADD = Menu.FIRST; private static final int MENU_QUIT = Menu.FIRST + 1; ListView list; SQLiteDatabase db;
You'll see why we use these a little later. This is where it gets a little different. I'll give you one method at a time, and talk through each line. view source print?
01 /** Called when the activity is first created. */ 02 @Override 03 public void onCreate(Bundle savedInstanceState) { 04 05 06 07 08 09 10 this.db = this.openOrCreateDatabase("dic_tut4", MODE_PRIVATE, null); this.db.execSQL("CREATE TABLE IF NOT EXISTS table_of_dics(value REAL)"); this.list = new ListView(this); setContentView(this.list); super.onCreate(savedInstanceState);
11 12 }
this.update_list();
So, the start is nothing new. Nothing to worry about here. Then we initialise the list. Nothing new here, either. It's exactly the same as when we created a dynamic layout in part 3. Then we do some new things with our database. First we use openOrCreateDatabase("dic_tut4", MODE_PRIVATE, null); -- this creates a database if it doesn't exist, or opens it if it does. -- parameter 1 is the name of the database we're looking to create/open. -- parameter 2 is the mode, doesn't require much explanation at this point. (Don't want to give you an information overload) -- parameter 3, you don't even need to worry about. If you're interested, do some digging on CursorFactory. Then another new line: this.db.execSQL("CREATE TABLE IF NOT EXISTS table_of_dics(value REAL)"); -- this will create a table if it doesn't already exist -- it will add a single field into the table, called value. It is of type REAL, which is just like a double in Java. And finally, this.update_list(); ... this is actually a custom method we'll be writing to query the database and populate the list. More info later, for now let's focus on the menu.
Creating a menu
Simple stuff actually. We use onCreateOptionsMenu(), which is called when the user hits the menu button. view source print?
1 @Override 2 public boolean onCreateOptionsMenu(Menu menu) { 3 4 5 6} menu.add(0, MENU_ADD, 0, "Add").setIcon(android.R.drawable.ic_menu_add); menu.add(0, MENU_QUIT, 0, "Quit").setIcon(android.R.drawable.ic_menu_close_clear_cancel); return super.onCreateOptionsMenu(menu);
We're simply adding 2 items: "Add", and "Quit". We also set the icons for them using some default android resources. If you want a full list, this site is pretty cool. The next method we'll be using is onOptionsItemSelected(), which is called when the user selects an item in the menu. We use the IDs we assigned in onCreateOptionsMenu() MENU_ADD and MENU_QUIT to decide what to do. view source A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
print?
01 @Override 02 public boolean onOptionsItemSelected(MenuItem item) { 03 04 05 06 07 08 09 10 11 12 13 14 } return super.onOptionsItemSelected(item); } switch(item.getItemId()) { case MENU_ADD: db.execSQL("INSERT INTO table_of_dics(value) VALUES(" + String.valueOf(Math.random()) + ")"); this.update_list(); break; case MENU_QUIT: this.db.close(); this.finish();
So, we're using a switch() to find the ID of the menu item which called this method. If it's add, we're going to perform some SQL and insert a random value into the table. Then we'll update the list, just like we did in onCreate(). (Remember, we're defining this method ourselves later) If the user selected the "Quit" option, we'll simple close the database and finish the activity. NOTE: The SQL used here, INSERT INTO will insert a random value into the table. Remember to refer to the links at the beginning if you get stuck on the SQL. Lastly, we're going to define our method for updating the list. It's quite simple, but the code is quite different to what we've done so far. If you've ever done any database work through software/web before, you may notice a few similarities here. We basically execute the query. Then loop through each row in the result, adding it into an ArrayList. Lastly, we set the adapter for the list to display the arraylist we created. The code looks a tad complex, but it's really quite simple: view source print? A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
01 private void update_list() { 02 03 04 0 5 ); 06 07 08 this.list.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, db_results)); } cursor.close(); ArrayList<String> db_results = new ArrayList<String>(); Cursor cursor = db.rawQuery("SELECT value FROM table_of_dics ORDER BY value", null); while(cursor.moveToNext()) { db_results.add(String.valueOf(cursor.getDouble(cursor.getColumnIndex("value")))
09
10 }
I'll break this one up: ArrayList<String> db_results = new ArrayList<String>(); -- create an ArrayList, where we'll store the results to display in the list. Cursor cursor = db.rawQuery("SELECT value FROM table_of_dics ORDER BY value", null); -- create a cursor based on the query (this select statement will return all the values stored in the table, and order them) while(cursor.moveToNext()) { -- while there is still something in the cursor to read (while we still have another row to read) db_results.add(String.valueOf(cursor.getDouble(cursor.getColumnIndex("value")))); -- add the value from the row into the arraylist we created. } -- this is self explanatory, really. cursor.close(); -- close the cursor: we're done with it now. We have all our results in the ArrayList, which we can now set as the adapter: this.list.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, db_results)); -set the adapter. - parameter 1: the activity we want it for - parameter 2: the layout type (we can add multiple widgets to a list item, but simple_list_item_1 is a default in android: simply a single TextView. - parameter 3: the arraylist which we created and populated earlier. A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
And that's it! Don't forget to close off your class view source print?
1}
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
/** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
this.db = this.openOrCreateDatabase("dic_tut5", MODE_PRIVATE, null); this.db.execSQL("CREATE TABLE IF NOT EXISTS table_of_dics(value REAL)"); this.update_list();
setContentView(this.list); }
@Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(0, MENU_ADD, 0, "Add").setIcon(android.R.drawable.ic_menu_add); menu.add(0, MENU_QUIT, 0, "Quit").setIcon(android.R.drawable.ic_menu_close_clear_cancel); return super.onCreateOptionsMenu(menu); }
@Override
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case MENU_ADD: db.execSQL("INSERT INTO table_of_dics(value) VALUES(" + String.valueOf(Math.random()) + ")"); this.update_list(); break; case MENU_QUIT: this.db.close(); this.finish(); }
return super.onOptionsItemSelected(item); }
private void update_list() { ArrayList<String> db_results = new ArrayList<String>(); Cursor cursor = db.rawQuery("SELECT value FROM table_of_dics ORDER BY value", null); while(cursor.moveToNext()) { db_results.add(String.valueOf(cursor.getDouble(cursor.getColumnIndex("value
6 1 ")))); 62 63 64 }
cursor.close();
65
66 67 }
#2 Guest_DimasSup*
Reputation:
#3 Guest_Marc Ellis*
Reputation:
Quote
01 /** Called when the activity is first created. */ 02 @Override 03 public void onCreate(Bundle savedInstanceState) { 04 super.onCreate(savedInstanceState); 05 06 this.list = new ListView(this); 07 setContentView(this.list); 08 09 this.db = this.openOrCreateDatabase("dic_tut4", MODE_PRIVATE, null); 10 this.db.execSQL("CREATE TABLE IF NOT EXISTS table_of_dics(value REAL)"); 11 this.update_list(); 12 }
Quote
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
20 /** Called when the activity is first created. */ 21 @Override 22 public void onCreate(Bundle savedInstanceState) { 23 super.onCreate(savedInstanceState); 24 25 this.list = new ListView(this); 26 this.registerForContextMenu(this.list); 27 28 this.db = this.openOrCreateDatabase("dic_tut5", MODE_PRIVATE, null); 29 this.db.execSQL("CREATE TABLE IF NOT EXISTS table_of_dics(value REAL)"); 30 this.update_list(); 31 32 setContentView(this.list); 33 }
#4 Denis1
D.I.C Head
Reputation: 15
Quote
01 /** Called when the activity is first created. */ 02 @Override 03 public void onCreate(Bundle savedInstanceState) { 04 super.onCreate(savedInstanceState); 05 06 this.list = new ListView(this); 07 setContentView(this.list); 08 09 this.db = this.openOrCreateDatabase("dic_tut4", MODE_PRIVATE, null); 10 this.db.execSQL("CREATE TABLE IF NOT EXISTS table_of_dics(value REAL)"); 11 this.update_list(); 12 }
Quote
20 /** Called when the activity is first created. */ 21 @Override 22 public void onCreate(Bundle savedInstanceState) { 23 super.onCreate(savedInstanceState); 24 25 this.list = new ListView(this); 26 this.registerForContextMenu(this.list); 27 28 this.db = this.openOrCreateDatabase("dic_tut5", MODE_PRIVATE, null); 29 this.db.execSQL("CREATE TABLE IF NOT EXISTS table_of_dics(value REAL)"); 30 this.update_list(); 31 A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
32 setContentView(this.list); 33 }
its a blank screen because there is no data to display. click menu and add data and you will see it on your screen
#5 Guest_xsylus*
Reputation:
#6 Guest_droidster*
Small. Fast. Reliable. Choose any three. About Sitemap Documentation Download License News Support
Search SQ
Go
sql-stmt:
Used by: sql-stmt-list References: alter-table-stmt analyze-stmt attach-stmt begin-stmt commit-stmt create-index-stmt create-tablestmt create-trigger-stmt create-view-stmt create-virtual-table-stmt delete-stmt delete-stmt-limited detachstmt drop-index-stmt drop-table-stmt drop-trigger-stmt drop-view-stmt insert-stmt pragma-stmt reindexstmt release-stmt rollback-stmt savepoint-stmt select-stmt update-stmt update-stmt-limited vacuum-stmt See also: lang.html lang_explain.html
alter-table-stmt:
Used by: sql-stmt See also: lang_savepoint.html lang_transaction.html A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
Used by: sql-stmt References: column-def select-stmt table-constraint See also: lang_createtable.html
column-def:
Used by: alter-table-stmt create-table-stmt References: column-constraint type-name See also: lang_altertable.html lang_createtable.html lang_createtable.html#tablecoldef type-name:
Used by: column-def expr References: signed-number See also: lang_createtable.html column-constraint:
Used by: column-def References: conflict-clause expr foreign-key-clause literal-value signed-number See also: lang_createtable.html lang_createtable.html#tablecoldef signed-number:
table-constraint:
Used by: create-table-stmt References: conflict-clause expr foreign-key-clause indexed-column See also: lang_createtable.html lang_createtable.html#constraints lang_createtable.html#tablecoldef foreign-key-clause:
conflict-clause:
Used by: sql-stmt References: delete-stmt expr insert-stmt select-stmt update-stmt See also: lang_createtrigger.html
create-view-stmt:
Used by: create-trigger-stmt sql-stmt References: expr qualified-table-name See also: lang_delete.html delete-stmt-limited:
Used by: sql-stmt References: expr ordering-term qualified-table-name See also: lang_delete.html
detach-stmt:
expr:
Used by: column-constraint create-trigger-stmt delete-stmt delete-stmt-limited insert-stmt joinconstraint ordering-term result-column select-core table-constraint update-stmt update-stmt-limited References: literal-value raise-function select-stmt type-name See also: lang_expr.html A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
raise-function:
insert-stmt:
Used by: create-trigger-stmt sql-stmt References: expr select-stmt See also: lang_insert.html pragma-stmt:
Used by: sql-stmt See also: lang_reindex.html A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
select-stmt:
Used by: create-table-stmt create-trigger-stmt create-view-stmt expr insert-stmt single-source sql-stmt References: compound-operator ordering-term select-core See also: lang_select.html select-core:
Used by: select-stmt References: expr join-source ordering-term result-column See also: lang_select.html result-column:
join-source:
Used by: select-core single-source References: join-constraint join-op single-source See also: lang_select.html single-source:
Used by: join-source References: join-source select-stmt See also: lang_indexedby.html lang_select.html join-op:
Used by: join-source References: expr See also: lang_select.html lang_select.html#fromclause ordering-term:
Used by: delete-stmt-limited select-core select-stmt update-stmt-limited A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
Used by: create-trigger-stmt sql-stmt References: expr qualified-table-name See also: lang_update.html
update-stmt-limited:
Used by: sql-stmt References: expr ordering-term qualified-table-name See also: lang_update.html qualified-table-name:
Used by: delete-stmt delete-stmt-limited update-stmt update-stmt-limited See also: lang_delete.html lang_indexedby.html lang_update.html vacuum-stmt: Used by: sql-stmt See also: lang_vacuum.html
comment-syntax:
Publishing your apps No code in this tutorial... and this is actually the last in the series. But never fear! I'll be writing more tutorials, I've simply written these 5 to get you familiarised with android. Hopefully, you're feeling quite confident on some of the aspects now, and you could well be on your way to developing the next killer app!
With that said, I'm going to explain how you can publish your app. It's a simple process, but you also have to sign your apk before you can publish it to the market. First off, we need to create a keystore. To do this, you'll need the JDK installed. Open up a command prompt, and change to whereever you want to save the keystore. Then, type the following: keytool -genkey -v -keystore mykeystore.keystore -alias my_alias -keyalg RSA -validity 10000 NOTES: - Replace mykeystore.keystore with whatever_you_want_to_call_it.keystore - Replace my_alias with whatever alias you want to use (example, android) Also, if you get this error: 'keytool' is not recognised as an internal or external command, operable program or batch file. You may want to set the PATH variable. You can do it in the computer properties, but since this isn't exactly a windows tutorial, I won't go into that much detail. Instead, let's do this: PATH="C:\Program Files\Java\jdk1.6.0_14\bin" then try the first command again. NOTE: Replace the path with the path of wherever you installed Java. (Typically you'll find it in C:\Program Files\Java\jdk%.%.%_%%\bin) ANOTHER NOTE: This is of course a windows path. Depending on your operating system, this may vary. After executing the keytool command, it will ask you for various details. Simply enter the values, and it will create your keystore. Make sure you take note of your alias and password, it will ask you for it every time you come to sign an app! For reference, the questions it will ask are:
What is your first and last name? What is the name of your organisational unit? What is the name of your organisation? What is the name of your City or Locality? What is the name of your State or Province? What is the two-letter country code for this unit?
You now have your keystore. When you want to sign an apk, you will need to use the following command: jarsigner -verbose -keystore "/path/to/mykeystore.keystore" "/path/to/myapk.apk" my_alias Enter your password, and you will see some output similar to this: Quote adding: META-INF/ALIAS_NA.SF adding: META-INF/ALIAS_NA.RSA signing: res/drawable/icon.png signing: res/layout/main.xml signing: AndroidManifest.xml signing: resources.arsc signing: classes.dex
Your apk file is now signed! (Note that you need to sign it every time before uploading, since building will reset it)
Publishing your app The next step is of course publishing your newly signed apk file to the android market. Simply navigate your web browser to http://market.android.com/publish/Home and follow the steps to register as a developer. If you want to register to sell your apps, you will also need to go through an additional process to become a "registered seller".
Once you've registered and logged in, you'll reach the page which displays all your registered apps. Of course, if you're following this tutorial, you probably don't yet have any, so you won't have a list of apps to see. NOTE: This page uses a hell of a lot of javascript. Make sure it's turned on. When you're ready, click on "Upload Application". You will then be presented with a form where you can upload the apk and a maximum of two screenshots, a promotional graphic, and fill in various details such as the title, description and price. As soon as you click publish, your application will be on the market -- there's no approval system like the iPhone's app store, so as soon as you search in the market, you should see your app.
I recently wrote my first application for Android, and it was a great learning experience. One of the more "advanced" tasks that I wanted to do was to make the widget icon change depending on whether the LEDs were on or not. I also wanted to allow the user to be able to choose which icons they wanted the widget to use. So I started out using one layout XML file with multiple ImageViews, and was just showing/hiding and changing the source to the image that I wanted to show. I started thinking that this seemed to be very convoluted and that there must be an easier way. I decided to figure out how to create multiple layout XML files and load those dynamically. This would allow me to have each icon in it's own separate XML file so any changes that needed to be made to them would only affect that icon and not the other icons. First, I created the separate layout XML files. I am just going to show two that I did. widget_flame_with_border_off.xml view source print?
01 <?xml version="1.0" encoding="utf-8"?> 02 <LinearLayout android:id="@+id/main" 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 </LinearLayout> 27 </LinearLayout> <ImageView android:id="@+id/img_led" android:layout_height="40dip" android:layout_gravity="center" android:layout_width="40dip" android:src="@drawable/mototorch_led_off" android:scaleType="fitXY" /> <LinearLayout android:id="@+id/btn_led" android:layout_width="52dip" android:layout_height="52dip" android:background="@drawable/appwidget_button_center" android:clickable="true" android:focusable="true" android:gravity="center"> android:gravity="center" android:background="@drawable/widget_frame_portrait1x1_black" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="74dip" android:layout_width="74dip">
With those two layout XML files created, I can now load them dynamically. view source print?
01 @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] 02 appWidgetIds){ 03 04 05 06 07 08 if (ledIsOn){ layoutID = R.layout.widget_flame_with_border_on; int layoutID = 0; RemoteViews views = null;
09 10 11 12 13 14 15 16 17 18 19 20 21 22 }
} else { layoutID = R.layout.widget_flame_with_border_off; } // the layoutID that is passed in the constructor of the // // RemoteViews object is the layout that will be loaded when the widget is updated.
views = new RemoteViews(context.getPackageName(), layoutID); for (int i = 0; i < appWidgetIds.length; i++) { appWidgetManager.updateAppWidget(appWidgetIds[i], views); }
In the constructor for the RemoteViews object, you pass in the layout ID of the layout that you want to use. So simply changing this to a different layout than is currently being used, you can change the layout completely.
Stating this tutorial assumes that you already have Eclipse and the Android SDK installed on your computer. Ok well here we go! To start off we first need to create a new project... In eclipse do File -> New -> Android Project Name the project File Chooser. Select the build target 1.6 For application name put File Chooser For package name put whatever you like. I'm going to name my package com.h3r3t1c.filechooser Make sure Create Activity is checked and type in FileChooser Min SDK Version is 4 Now just select ok. Before we start coding we need to set the permission so we can read and write file on the SD Card so to do this open the AndroidManifest.xml and click on the permissions tab. Click the add button and select Uses Permission. In the drop down menu select android.permission.WRITE_EXTERNAL_STORAGE and click save.
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
Now to start the coding! Expand src and open the file FileChooser.java The first thing you'll notice is that Eclipse auto generated some code for us. This is good but we need to change a few things. First thing we need to change is activity. Rename extends Activity to extends ListActivity. Next we need to remove setContentView(R.layout.main);. You should now have something that looks like this: view source print?
1 public class FileChooser extends ListActivity { 2 /** Called when the activity is first created. */ 3 4 5 6 7 8} } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
Ok the next thing were going to want to do is to start adding our methods. The first method were going to create is called fill. The purpose of fill is to get all the files and folder for the current directory were in. In your FileChooser class create the method: view source print?
1 private void fill(File f) 2{ 3 4}
Now that we have that created were going to want to have it called right away when the activity starts so to do this first we need to create a current directory variable. Above the onCreate() method add this: view source print?
1 private File currentDir;
Note: your going to have to import File! Now going back to the onCreate() method we need to initialize currentDir to the root of the SD Card so to do this add this: view source print?
1 currentDir = new File("/sdcard/)
now under that call the fill method like so: view source print?
1 fill(currentDir);
Right now our class should look like this : view source
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
print?
01 public class FileChooser extends ListActivity { 02 private File currentDir; 03 04 05 06 07 08 09 10 11 12 13 } } } private void fill(File f) { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); currentDir = new File("/sdcard/"); fill(currentDir);
Before we move onto adding the code to we need to create a class to hold our data were going to get from listing all the file and directories so in eclipse right click on your package and select New -> Class. Name this class Option and select ok. Add this code to your Option class: view source print?
01 public class Option implements Comparable<Option>{ 02 private String name; 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 public Option(String n,String d,String p) { name = n; data = d; path = p; } public String getName() { return name; } public String getData() { return data; } public String getPath() { return path; } @Override public int compareTo(Option o) { private String data; private String path;
26 27 28 29 30 31 } }
Ok now that that is done go back to FileChooser.java The fill method is going to work like this: Were going to get an array of all the files and dirs in the current were in. Were going to create 2 ListArrays. One for folders and one for files. Were going to sort files and dirs into the appropriate ListArray. Were going to sort the ListArrays alphabetically and pass to one ListArray. Were going to pass this ListArray to our custom ArrayAdapter So our fill method should look like this: view source print?
01 private void fill(File f) 02 { 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 } } Collections.sort(dir); Collections.sort(fls); dir.addAll(fls); if(!f.getName().equalsIgnoreCase("sdcard")) dir.add(0,new Option("..","Parent Directory",f.getParent())); File[]dirs = f.listFiles(); this.setTitle("Current Dir: "+f.getName()); List<Option>dir = new ArrayList<Option>(); List<Option>fls = new ArrayList<Option>(); try{ for(File ff: dirs) { if(ff.isDirectory()) dir.add(new Option(ff.getName(),"Folder",ff.getAbsolutePath())); else { fls.add(new Option(ff.getName(),"File Size: "+ff.length(),ff.getAbsolutePath())); } } }catch(Exception e) {
Create a new class called FileArrayAdapter. In FileArrayAdapter have it extend ArrayAdapter<Option>, add constructor and add global variables like so: view source print?
01 public class FileArrayAdapter extends ArrayAdapter<Option>{ 02 03 04 05 06 07 08 09 10 11 12 13 14 15 } } public FileArrayAdapter(Context context, int textViewResourceId, List<Option> objects) { super(context, textViewResourceId, objects); c = context; id = textViewResourceId; items = objects; private Context c; private int id; private List<Option>items;
Before we move on we now need to create a View for us to display our data! Click New -> Android XML File For file call it file_view.xml. Click layout and then finish. Replace the xml text in the file with this text: view source print?
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout 3 xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="wrap_content" android:orientation="vertical" 4 android:layout_width="fill_parent"> <TextView android:text="@+id/TextView01" android:id="@+id/TextView01" android:layout_width="wrap_content" android:layout_height="wrap_content" 5 android:singleLine="true" android:textStyle="bold" android:layout_marginTop="5dip" android:layout_marginLeft="5dip"></TextView> <TextView android:text="@+id/TextView02" android:id="@+id/TextView02" 6 android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10dip"></TextView> 7 </LinearLayout>
Now go back to FileArrayAdaper. Were going to do the following: Add method to get item from a location in the List. Override the getView() method Using the getView() method create our custom view from the data in items and use file_view.xml to be the view. Add this code to your FileArrayAdapter: view source
A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
print?
01 public Option getItem(int i) 02 { 03 04 05 06 07 08 09 return items.get(i); } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; if (v == null) {
LayoutInflater vi = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 10 v = vi.inflate(id, null); 11 12 13 14 15 16 17 18 19 20 21 22 23 24 } } return v; if(t1!=null) t1.setText(o.getName()); if(t2!=null) t2.setText(o.getData()); } final Option o = items.get(position); if (o != null) { TextView t1 = (TextView) v.findViewById(R.id.TextView01); TextView t2 = (TextView) v.findViewById(R.id.TextView02);
Now go back to FileChooser and add the global variable private FileArrayAdapter adapter; Now back in fill method add the following code to initialize our adapter: view source print?
1 adapter = new FileArrayAdapter(FileChooser.this,R.layout.file_view,dir); 2 this.setListAdapter(adapter);
At this point you should be able to test it and it should be listing all the folders and files in the root of your SD Card. Now we need to handle users clicking on files and folders! To do this were going to override the onListItemClick method. Add this code to your FileChooser class: view source print?
01 @Override 02 protected void onListItemClick(ListView l, View v, int position, long id) { 03 04 05 06 // TODO Auto-generated method stub super.onListItemClick(l, v, position, id); Option o = adapter.getItem(position); if(o.getData().equalsIgnoreCase("folder")||o.getData().equalsIgnoreCase("parent
At this point we should now be able to move through the directories on the SD Card! Now for our purposes the clicking of files will just show a toast message saying tha a file has been clicked but it will give you and idea of how to handle the files we click! Create a method called onFileClick() and adding the following code: view source print?
1 private void onFileClick(Option o) 2 { 3 4 Toast.makeText(this, "File Clicked: "+o.getName(), Toast.LENGTH_SHORT).show(); }
Then go back up to the onListItemClick() and add this code: view source print?
1 else 2 3 4 { onFileClick(o); }
The onFileClick method could be used to return the path of the file if FileChooser was called with startActivityForResult(). This is what your classes should look like in the end: FileChooser: view source print?
01 import java.io.File; 02 import java.util.ArrayList; 03 import java.util.Collections; 04 import java.util.List; 05 06 import android.app.ListActivity; 07 import android.os.Bundle; 08 import android.view.View; 09 import android.widget.ListView; 10 import android.widget.Toast; 11 12 public class FileChooser extends ListActivity { 13 14 15 private File currentDir; private FileArrayAdapter adapter;
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); currentDir = new File("/sdcard/"); fill(currentDir); } private void fill(File f) { File[]dirs = f.listFiles(); this.setTitle("Current Dir: "+f.getName()); List<Option>dir = new ArrayList<Option>(); List<Option>fls = new ArrayList<Option>(); try{ for(File ff: dirs) { if(ff.isDirectory()) dir.add(new Option(ff.getName(),"Folder",ff.getAbsolutePath())); else {
fls.add(new Option(ff.getName(),"File Size: "+ff.length(),ff.getAbsolutePath())); 36 } 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 } Collections.sort(dir); Collections.sort(fls); dir.addAll(fls); if(!f.getName().equalsIgnoreCase("sdcard")) dir.add(0,new Option("..","Parent Directory",f.getParent())); adapter = new FileArrayAdapter(FileChooser.this,R.layout.file_view,dir); this.setListAdapter(adapter); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { // TODO Auto-generated method stub super.onListItemClick(l, v, position, id); Option o = adapter.getItem(position); } }catch(Exception e) {
60 61 62 63 64 65 66 67 68 }
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 } }
v = vi.inflate(id, null); } final Option o = items.get(position); if (o != null) { TextView t1 = (TextView) v.findViewById(R.id.TextView01); TextView t2 = (TextView) v.findViewById(R.id.TextView02); if(t1!=null) t1.setText(o.getName()); if(t2!=null) t2.setText(o.getData()); } return v;
26 27 28 29 30 31 } }
Next tutorial I will be showing how to add icons for different file types and folders ! The full project can be downloaded here: http://www.sendspace.com/pro/dl/vre5ac