操作数据库之一(实现SQLiteOpenHelper绑定ListView)

 
实现的效果是页面上有个EditText和一个ListView,menu中添加了三个按钮,分别是add、update、delete。
初始化页面时绑定ListView.
(1)新增:当EditText写好内容后,点击add,实现保存到数据库中,并同时刷新ListView(EditText为空时不保存)。
(2)修改:点击ListView中的某一项,内容显示在EditText中,修改后点击Menu中的Update实现保存;
(3)删除:点击ListView中的一项,点击Menu中的delete按钮,实现删除。
很简单,代码贴出来,直接可以运行的。

SimpleCursorAdapter:程序使用了适配器SimpleCursorAdapter,它的五个参数依次是:this,布局文件,Cursor实例,一个包含数据库的列的String型数组,一个包含布局文件中对应组件id的int型数组。 SimpleCursorAdapter做的工作就是自动的将String型数组所表示的每一列数据映射到布局文件对应id的组件上。

Cursor类似于java.sql.ResultSet,很多方法名称不一样,但是功能不一样。


操作数据库的类DBOperation.java

package test.shi;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;


public class DBOperation extends SQLiteOpenHelper {

private final static  String DATABASE_NAME="betty_db1";
private final static  int DATABASE_VERSION=1;
private final static  String TABLE_NAME="betty_table1";

//因为SimpleCursorAdapter构造中必须有个字段是_id,否则会报错
//所以此处使用_id
public final static  String FIELD_ID="_id";
public final static  String FIELD_TEXT="betty_text";

public DBOperation(Context context) {
super(context,DATABASE_NAME,null,DATABASE_VERSION);
// TODO Auto-generated constructor stub

}

@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String sql="create table "+TABLE_NAME+" ("+FIELD_ID
+" integer primary key autoincrement,"+
""+FIELD_TEXT+" text)";


db.execSQL(sql);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldversion, int newversion) {
// TODO Auto-generated method stub
String sql ="drop table if exists "+TABLE_NAME;
db.execSQL(sql);
onCreate(db);
}

public Cursor select()
{
SQLiteDatabase db=this.getReadableDatabase();
Cursor cursor=db.query(TABLE_NAME, null, null, null, null, null, null);
return cursor;

}

public long insert(String text)
{
SQLiteDatabase db=this.getWritableDatabase();
ContentValues cv=new ContentValues();

cv.put(FIELD_TEXT,text);
long row=db.insert(TABLE_NAME, null,cv);
return row;
}

public void update(int _id,String text)
{
SQLiteDatabase db=this.getWritableDatabase();
String where=FIELD_ID+"=?";
String[] strwhere={Integer.toString(_id)};
ContentValues cv=new ContentValues();
cv.put(FIELD_TEXT, text);
db.update(TABLE_NAME, cv, where, strwhere);
}

public void delete(int _id)
{
SQLiteDatabase db=this.getWritableDatabase();
String where=FIELD_ID+"=?";
String[] strwhere={Integer.toString(_id)};
db.delete(TABLE_NAME, where,strwhere);

}

}

主程序类文件DBTest.java

package test.shi;

import test.toshiba.R;
import android.app.Activity;
import android.database.*;
import android.database.sqlite.*;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.*;

public class DBTest extends Activity {

private DBOperation myDBOperation;
private Cursor myCursor;
private ListView myListView;
private EditText myEditText;
private int _id;
private final static int MENU_ADD = Menu.FIRST;
private final static int MENU_UPDATE = Menu.FIRST + 1;
private final static int MENU_DELETE = Menu.FIRST + 2;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);

try {
setContentView(R.layout.dboperationlayout);

myListView = (ListView) findViewById(R.id.myListView);
myEditText = (EditText) findViewById(R.id.myEditText);

myDBOperation = new DBOperation(this);
myCursor = myDBOperation.select();

//必须有个字段是_id,否则会报错
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.lstview_simple_layout, myCursor,
new String[] { DBOperation.FIELD_TEXT },
new int[] { R.id.ItemText });

myListView.setAdapter(adapter);

myListView
.setOnItemClickListener(new AdapterView.OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
myCursor.moveToPosition(arg2);
_id = myCursor.getInt(0);
myEditText.setText(myCursor.getString(1));
}

});

myListView
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

@Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub

SQLiteCursor sc = (SQLiteCursor) arg0
.getSelectedItem();
_id = sc.getInt(0);
myEditText.setText(sc.getString(1));
Log.d("shi","setOnItemSelectedListener:");
}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub

}

});
} catch (Exception ex) {
Log.e("shi", "ex:" + ex.toString());
ex.printStackTrace();
}
}

private void addTodb() {
try {
if (myEditText.getText().toString().equals(""))
return;
myDBOperation.insert(myEditText.getText().toString());
myCursor.requery();
myListView.invalidateViews();
myEditText.setText("");
_id = 0;
} catch (Exception ex) {
Log.d("shi", ex.toString());
ex.printStackTrace();

}
}

private void editdb() {
try {
if (_id == 0)
return;
myDBOperation.update(_id, myEditText.getText().toString());
myCursor.requery();
myListView.invalidateViews();
myEditText.setText("");
_id = 0;
} catch (Exception ex) {
Log.e("shi", "editdb():" + ex.toString());
ex.printStackTrace();
}
}

private void deletedb() {
try {
if (_id == 0)
return;
myDBOperation.delete(_id);
myCursor.requery();
myListView.invalidateViews();
myEditText.setText("");
_id = 0;
} catch (Exception ex) {
Log.e("shi", "deletedb:" + ex.toString());
ex.printStackTrace();
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
super.onCreateOptionsMenu(menu);
menu.add(Menu.NONE, MENU_ADD, 0, "add");
menu.add(Menu.NONE, MENU_UPDATE, 0, "update");
menu.add(Menu.NONE, MENU_DELETE, 0, "delete");
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case MENU_ADD:
addTodb();
break;
case MENU_UPDATE:
editdb();
break;
case MENU_DELETE:
deletedb();
break;
default:
break;

}

return true;

}

}


布局页面dboperationlayout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:id="@+id/myEditText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"

</EditText>
<ListView
android:id="@+id/myListView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
></ListView>

</LinearLayout>

ListView式样页面lstview_simple_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content" android:layout_height="wrap_content">
<TextView android:text="TextView02" android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:id="@+id/ItemText" />
</LinearLayout>




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值