This tutorial on writing a notepad application gives you a "hands-on" introduction to the Android framework and the tools you use to build applications on it. Starting from a preconfigured project file, it guides you through the process of developing a simple notepad application and provides concrete examples of how to set up the project, develop the application logic and user interface, and then compile and run the application.
这篇关于记事本应用程序的教程让你可以"上手"android 框架,学会使用编写应用程序所需的工具。这篇教程从一个还没有配置好的文件开始,指导你开发一个简单的记事本程序,它提供了关于怎样建立工程,开发应用程序逻辑和用户接口以及编译运行程序的具体的例子。
哎,我还是没耐性,翻译出来怪怪的。擦,不翻译了,直接上代码!
NotesDbAdapter类
public static final String KEY_TITLE = "title";//标题列 public static final String KEY_BODY = "body";//内容列 public static final String KEY_ROWID = "_id";//标识id //建表sql语句 private static final String DATABASE_CREATE = "create table notes (_id integer primary key autoincrement, " + "title text not null, body text not null);"; private static final String DATABASE_NAME = "data";//数据库名 private static final String DATABASE_TABLE = "notes";//表名 private static final int DATABASE_VERSION = 2;//版本号
private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(DATABASE_CREATE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS notes"); onCreate(db); } }
SQliteOpenHelper是一个抽象类,来管理数据库的创建和版本的管理。要使用它必须实现它的onCreate(SQLiteDatabase),onUpgrade(SQLiteDatabase, int, int)方法,onOpen()方法可选
onCreate:当数据库第一次被建立的时候被执行,例如创建表,初始化数据等。
onUpgrade:当数据库需要被更新的时候执行,例如删除久表,创建新表。
关于它,api里解释的很清楚,这段英文读起来也很流畅
A helper class to manage database creation and version management.
You create a subclass implementing onCreate(SQLiteDatabase)
, onUpgrade(SQLiteDatabase, int, int)
and optionallyonOpen(SQLiteDatabase)
, and this class takes care of opening the database if it exists, creating it if it does not, and upgrading it as necessary.
另一个重要的类就是SQLiteDatabase。 Android提供了一个名为SQLiteDatabase的类,它封装了一些操作数据库的API。使用它能实现基本的CRUD操作(CRUD是create, retrieve, update, and delete的缩写),通过getWritableDatabase()和getReadableDatabase()可以获取数据库实例。