1.创建数据库的方法:
public void onCreate(SQLiteDatabase db)
{
String sql = "CREATE TABLE[calendar]("
+"[_id] INTEGER PRIMARY KEY AUTOINCREMENT,"
+"[text] text"+")";
db.execSQL(sql);
}
这样对齐看起来很方便.
2.查询数据库
public Cursor query(String sql ,String[]args)
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(sql,args);
return cursor;
}
3.执行INSERT UPDATE DELETE等SQL语句的函数:
public void execSQL(String sql,Object[]args)
{
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(sql,args);
}
4.SimpleCursorAdapter的使用:
SimpleCursorAdapter simpleCursorAdapter
= new SimpleCursorAdapter(this,android.R.layout.simple_list_item_checked,
myCursor,new String[]{"text"},new int[]{android.R.id.text1} );
myListView.setAdapter(simpleCursorAdapter);
其中android.R.layout.simple_list_item_checked为自带的:<?xml version="1.0" encoding="utf-8"?>
android:id="@android:id/text1"
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:textAppearance="?android:attr/textAppearanceLarge"
android:gravity="center_vertical"
android:checkMark="?android:attr/textCheckMark"
android:paddingLeft="6dip"
android:paddingRight="6dip"
/>
5.add,edit,delete的函数编写:
private void add()
{
if(myEditText.getText().toString().equals(""))
return ;
String sql = "INSERT INTO calendar(text)VALUES(?)";
String value = myEditText.getText().toString();
myDBService.execSQL(sql,new Object[]{value});
myCursor.requery();
myListView.invalidateViews();
myEditText.setText("");
_id=0;
}
private void edit()
{
if(myEditText.getText().toString().equals(""))
return ;
String sql = "UPDATE calendar SET text= ? WHERE _id=?";
String value1 = myEditText.getText().toString();
String value2 = Integer.toString(_id);
myDBService.execSQL(sql,new Object[]{value1,value2});
myCursor.requery();
myListView.invalidateViews();
myEditText.setText("");
_id=0;
}
private void delete()
{
if(_id==0)
return ;
String sql = "DELETE FROM calendar WHERE _id = ?";
String value = Integer.toString(_id);
myDBService.execSQL(sql,new Object[]{value});
myCursor.requery();
myListView.invalidateViews();
myEditText.setText("");
_id=0;
}
}
6.ListView相关:
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView> parent, View view,
int position, long id)
{
myCursor.moveToPosition(position);
_id = myCursor.getInt(0);
myEditText.setText(myCursor.getString(1));
}
});
myListView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView> parent, View view,
int position, long id)
{
SQLiteCursor sc = (SQLiteCursor)parent.getSelectedItem();
_id = sc.getInt(0);
myEditText.setText(sc.getString(1));
}
@Override
public void onNothingSelected(AdapterView> parent)
{
}
});