您的位置:首页 > 数据库

关系型数据库sqlite之图书管理系统

2015-08-26 23:50 441 查看
大家好,今天给大家带来一个重头戏,用关系型数据库sqlite打造的图书管理系统,代码量多,设计的知识点,废话不多讲,小编开始激情讲解了。先上本次运行成功的界面。



看到这界面,相信大家肯定非常感兴趣,接下来小编一步一步为大家详解。

1.res/layout两个文件

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical"

android:paddingLeft="5dp"

android:paddingRight="5dp" >

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_gravity="center_horizontal"

android:text="图书管理系统"

android:textColor="#3300cc"

android:textSize="27sp" />

<LinearLayout

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:gravity="center_vertical"

android:orientation="horizontal" >

<TextView

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_weight="1"

android:text="编号"

android:textColor="#0066cc"

android:textSize="20sp" />

<TextView

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_weight="1"

android:text="书名"

android:textColor="#0066cc"

android:textSize="20sp" />

<TextView

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_weight="1"

android:text="价格"

android:textColor="#0066cc"

android:textSize="20sp" />

<ImageView

android:layout_width="30dp"

android:layout_height="30dp"

android:src="@drawable/ic_del_dark"

android:visibility="invisible" />

</LinearLayout>

<ListView

android:id="@+id/list"

android:layout_width="match_parent"

android:layout_height="0dp"

android:layout_weight="1"

android:divider="#3300cc"

android:dividerHeight="2dp" />

<LinearLayout

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:gravity="center_horizontal"

android:orientation="horizontal" >

<Button

android:id="@+id/downPage"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="下一页" />

<Button

android:id="@+id/upPage"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="上一页" />

</LinearLayout>

<LinearLayout

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:orientation="horizontal" >

<EditText

android:id="@+id/name_et"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_weight="2"

android:hint="书名" />

<EditText

android:id="@+id/price_et"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_weight="1"

android:hint="价格" />

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:onClick="add"

android:text="添加" />

</LinearLayout>

</LinearLayout>

item_list.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical"

android:paddingLeft="5dp"

android:paddingRight="5dp" >

<LinearLayout

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:gravity="center_vertical"

android:orientation="horizontal" >

<TextView

android:id="@+id/id_tv"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_weight="1"

android:text="编号"

android:textColor="#00ff33"

android:textSize="16sp" />

<TextView

android:id="@+id/name_tv"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_weight="2"

android:text="书名"

android:textColor="#00ff33"

android:textSize="16sp" />

<TextView

android:id="@+id/price_tv"

android:layout_width="0dp"

android:layout_height="wrap_content"

android:layout_weight="1"

android:text="价格"

android:textColor="#00ff33"

android:textSize="16sp" />

<TextView

android:id="@+id/delet_tv"

android:layout_width="30dp"

android:layout_height="30dp"

android:background="@drawable/delete_selector"

android:clickable="true"

android:onClick="delete"

android:textColor="#00000000" />

</LinearLayout>

</LinearLayout>

2.com.example.demo0819_sqlite.db

SqliteHelper.java

//继承SQLiteOpenHelper类

public class SqliteHelper extends SQLiteOpenHelper {

//定义变量

private static final String DATABASE_NAME = "book.db";

private static final int VERSION = 1;

//构造方法,参数一:上下文,参数二:数据库名,参数三:游标工厂,参数四:版本号

public SqliteHelper(Context context) {

super(context, DATABASE_NAME, null, VERSION);

}

//创建sql语句和初始化,重点:创建id必须为_id形式

public void onCreate(SQLiteDatabase db) {

String sql="create table t_book(_id integer primary key autoincrement,name text,price integer)";

//执行sql语句

db.execSQL(sql);

}

//版本更新

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

}

2.DBUtils.java

/**

* 方法工具类

*/

public class DBUtils {

//声明变量

public static final String TABLE = "t_book";

public static final String ID = "_id";

public static final String NAME = "name";

public static final String PRICE = "price";

public SqliteHelper dbHelper;

//构造函数,作用:传值

public DBUtils(Context context) {

// 创建sqliteHelper对象

dbHelper = new SqliteHelper(context);

}

/**

* 保存到数据库,保存数据库是通过id插入的,参数为ContentValues

*/

public int save(ContentValues values) {

// 获取数据库

SQLiteDatabase db = dbHelper.getWritableDatabase();

long id = db.insert(TABLE, null, values);

db.close();

//返回数据库id

return (int) id;

}

/**

* 删除数据库,根据id删除 delete from t_book where id=?; ,参数为id

*/

public int delete(int id) {

int effectNum = 0;// 影响行数

SQLiteDatabase db = dbHelper.getWritableDatabase();

//参数一:数据库表明,参数二:删除条件 ,参数三:条件值

effectNum = db.delete(TABLE, ID + "=?",

new String[] { String.valueOf(id) });

db.close();

return effectNum;

}

/**

* 更新数据库,参数为ContentValues

*/

public int update(ContentValues values) {

// 获取内容提供者的Id

String id = values.getAsString(ID);

int effectNum = 0;// 影响行数

SQLiteDatabase db = dbHelper.getWritableDatabase();

//参数三:条件。参数四:条件值,这里可以为空

effectNum = db.update(TABLE, values, ID + "=" + id, null);

db.close();

return effectNum;

}

/**

* 根据游标查询

*/

public Cursor findCursor() {

SQLiteDatabase db = dbHelper.getWritableDatabase();

Cursor cursor = db.query(TABLE, null, null, null, null, null, null);

// 不能关掉,关掉就不能查询

return cursor;

}

/**

* 根据条件查询

*/

public Cursor query(int pageNum, int pageSize) {

SQLiteDatabase db = dbHelper.getWritableDatabase();

Cursor cursor = db.query(TABLE, null, null, null, null, null, null, " "

+ pageNum + " , " + pageSize + " ");

return cursor;

}

//查总页数

public int pageNum(){

Cursor cursorTotal = findCursor();

return cursorTotal.getCount()/10 ;

}

/**

* 根据List查询

*/

public List<Map<String, Object>> find() {

List<Map<String, Object>> data = null;

Map<String, Object> map = null;

SQLiteDatabase db = dbHelper.getWritableDatabase();

Cursor cursor = db.query(TABLE, null, null, null, null, null, null);

if (cursor.getCount() > 0) {

data = new ArrayList<Map<String, Object>>();

}

// 遍历

while (cursor.moveToNext()) {

map = new LinkedHashMap<String, Object>();

map.put(ID, cursor.getInt(cursor.getColumnIndex(ID)));

map.put(NAME, cursor.getShort(cursor.getColumnIndex(NAME)));

map.put(PRICE, cursor.getInt(cursor.getColumnIndex(PRICE)));

data.add(map);

}

return data;

}

public void pay(int fromUser, int toUser, int money) {

SQLiteDatabase db = dbHelper.getWritableDatabase();

db.beginTransaction();

try {

db.execSQL("update t_book set price=price-" + money + " where _id="

+ fromUser);

db.execSQL("update t_book set price=price+" + money + " where _id="

+ toUser);

db.setTransactionSuccessful();

} finally {

db.endTransaction();

db.close();

}

}

}

3.测试类test

/**

* 测试根据工具类,在androidManifest.xml要设置,不然不能测试成功,

这叫单元测试,当全部单元测试通过是,表明数据库操作没有错误了

*/

public class TestDBUtils extends AndroidTestCase {

// 测试保存方法,运行这方法:run as--->android junit test,就可以测试,绿条为测试成功,红条为测试失败,当绿条成功时,这里表示已经插入了50条数据了

public void testSave() {

DBUtils du = new DBUtils(getContext());

ContentValues values = new ContentValues();

for (int i = 1; i < 50; i++) {

values.put("name", "android宝典" + i);

values.put("price", 30 + 2 * i);

du.save(values);

}

}

// 测试删除

public void testDelet() {

DBUtils du = new DBUtils(getContext());

for (int i = 1; i < 100; i++) {

int actual = du.delete(i);

}

}

// 测试更新方法

public void testUpdate() {

DBUtils du = new DBUtils(getContext());

ContentValues values = new ContentValues();

values.put(du.ID, 2);

values.put("name", "哈哈");

values.put("price", 23);

du.update(values);

}

// 测试查询方法

public void find() {

DBUtils du = new DBUtils(getContext());

List<Map<String, Object>> find = du.find();

for (Map map : find) {

System.out.println(map.get("name").toString());

}

}

// 测试查询

public void testSelect() {

DBUtils du = new DBUtils(getContext());

du.query(1, 10);

}

}

4.MainActivity.java代码实现,也是最重要的部分。

public class MainActivity extends Activity {

private ListView booklist;

private EditText nameEt;

private EditText priceEt;

private Cursor cursor;

private Context context;

private Button downPage;// 下一页

private Button upPage;// 上一页

private SimpleCursorAdapter adapter;

//设定页数条件,必须成员变量

private int i = 0;

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

//去标题

requestWindowFeature(Window.FEATURE_NO_TITLE);

setContentView(R.layout.activity_main);

context = this;

initViews();// 初始化组件

// 根据游标查询数据,查的是,前十条数据

cursor = new DBUtils(context).query(0, 10);

// 3. 游标适配器,记住是游标适配器,而不是简单适配器

adapter = new SimpleCursorAdapter(this, R.layout.item_list, cursor,

new String[] { DBUtils.ID, DBUtils.NAME, DBUtils.PRICE,

DBUtils.ID }, new int[] { R.id.id_tv, R.id.name_tv,

R.id.price_tv, R.id.delet_tv });

// 设置适配器,展出数据

booklist.setAdapter(adapter);

// 下一页

downPage.setOnClickListener(new OnClickListener() {

public void onClick(View v) {

// 获取总页数

DBUtils db = new DBUtils(context);

int page = db.pageNum();

i = i + 1;

// 判断

if (i > page) {

i = page;

}

// 根据游标查询数据

cursor = new DBUtils(context).query(i * 10, 10);

SimpleCursorAdapter adapter = new SimpleCursorAdapter(context,

R.layout.item_list, cursor, new String[] { DBUtils.ID,

DBUtils.NAME, DBUtils.PRICE,

DBUtils.ID }, new int[] { R.id.id_tv,

R.id.name_tv, R.id.price_tv, R.id.delet_tv });

booklist.setAdapter(adapter);

}

});

// 上一页

upPage.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

i = i - 1;

if (i < 0) {

i = 0;

}

// 根据游标查询数据

cursor = new DBUtils(context).query(i * 10, 10);

SimpleCursorAdapter adapter = new SimpleCursorAdapter(context,

R.layout.item_list, cursor, new String[] { DBUtils.ID,

DBUtils.NAME, DBUtils.PRICE,

DBUtils.ID }, new int[] { R.id.id_tv,

R.id.name_tv, R.id.price_tv, R.id.delet_tv });

booklist.setAdapter(adapter);

}

});

// 长按删除,监听每一项列表项

booklist.setOnItemLongClickListener(new OnItemLongClickListener() {

@Override

public boolean onItemLongClick(AdapterView<?> parent, View view,

int position, long id) {

DBUtils dbUtils = new DBUtils(context);

// long id表示数据库中的id

dbUtils.delete((int) id);

// 重新查询

cursor.requery();

// 更新數據,展示数据

adapter.notifyDataSetChanged();

return false;

}

});

}

/**

* 初始化组件

*/

private void initViews() {

booklist = (ListView) findViewById(R.id.list);

nameEt = (EditText) findViewById(R.id.name_et);

priceEt = (EditText) findViewById(R.id.price_et);

downPage = (Button) findViewById(R.id.downPage);

upPage = (Button) findViewById(R.id.upPage);

}

/**

* 添加事件

*/

public void add(View v) {

//获取输入框的值

String nameValue = nameEt.getText().toString().trim();

String priceValue = priceEt.getText().toString().trim();

DBUtils dbUtils = new DBUtils(context);

//创建ContentValues对象,用这个插入数据,和更新数据

ContentValues values = new ContentValues();

values.put(dbUtils.NAME, nameValue);

values.put(dbUtils.PRICE, priceValue);

dbUtils.save(values);

// 重新查询,显示

cursor.requery();

// 更新數據

adapter.notifyDataSetChanged();

//保存之后,输入框为空

nameEt.setText(null);

priceEt.setText(null);

}

/**

* 删除事件,

由于列表项的删除图标是没有绑定数据的,所以在列表项设置监听是实现不了效果的,现在我们想的一个办法就是,把控件ImageView变成第一个TextView控件,列表项第一个控件是由Id的,我们可以把id传 给删除控件,前提是,两个控件必须为TextView,方可传id,我们把ImageView改为TextView就完事了,注意要把textViewd的属性设置为android:clickable="true"可点击

*/

public void delete(View v) {

TextView textView = (TextView) v;

//传id,在游标适配哪里也要设置

String id = textView.getText().toString();

DBUtils dbUtils = new DBUtils(context);

// long id表示数据库中的id

int a = Integer.valueOf(id);

dbUtils.delete(a);

// 重新查询

cursor.requery();

// 更新數據

adapter.notifyDataSetChanged();

}

}

恩,今晚就到这里了,这篇比前几天的要难很多,希望读者好好理解,多敲几次,知识点是在摸索中掌握的,关系型SQlite的实战就告一段落了。差不多休息了,拜拜,晚安。


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: