android n sdk,Android SDK (phần 6) pptx

摘要:

Working with SQLite Databases❘217LISTING 7-5: Extracting values from a Cursorint GOLD_HOARDED_COLUMN = 2;Cursor myGold = myDatabase.query("GoldHoards", null, null, null, null, null, null);float totalHoard = 0f;// Make sure there is at least one row.if (myGold.moveToFirst()) {// Iterate over each cursor.do {float hoard = myGold.getFloat(GOLD_HOARDED_COLUMN);totalHoard += hoard;} while(myGold.moveToNext());}float averageHoard = totalHoard / myGold.getCount();Because SQLite database columns are loosely typed, you can cast individual values into valid types asrequired. For example, values stored as floats can be read back as strings.Adding, Updating, and Removing RowsTheSQLiteDatabaseclass exposesinsert,delete,andupdatemethods that encapsulate the SQL state-ments required to perform these actions. Additionally, theexecSQLmethod lets you execute any validSQL on your database tables should you want to execute these (or any other) operations manually.Any time you modify the underlying database values, you should callrefreshQueryon each Cursorthat has a view on the affected table.Inserting New RowsTo create a new row, construct aContentValuesobject and use itsputmethods to provide a value foreach column. Insert the new row by passing the Content Values object into theinsertmethod calledon the target database — along with the table name — as shown in Listing 7-6.LISTING 7-6: Inserting new rows into a database// Create a new row of values to insert.ContentValues newValues = new ContentValues();// Assign values for each row.newValues.put(COLUMN_NAME, newValue);[ Repeat for each column ]// Insert the row into your tablemyDatabase.insert(DATABASE_TABLE, null, newValues);218❘CHAPTER 7 DATABASES AND CONTENT PROVIDERSUpdating a RowUpdating rows is also done with Content Values.Create a newContentValuesobject, using theputmethods to assign new values to each column youwant to update. Callupdateon the database, passing in the table name, the updated Content Valuesobject, and a where clause that specifies the row(s) to update as shown in Listing 7-7.LISTING 7-7: Updating a database row// Define the updated row content.ContentValues updatedValues = new ContentValues();// Assign values for each row.newValues.put(COLUMN_NAME, newValue);[ Repeat for each column ]String where = KEY_ID + "=" + rowId;// Update the row with the specified index with the new values.myDatabase.update(DATABASE_TABLE, newValues, where, null);Deleting RowsTo delete a row simply calldeleteon a database, specifying the table name and a where clause thatreturns the rows you want to delete as shown in Listing 7-8.LISTING 7-8: Deleting a database rowmyDatabase.delete(DATABASE_TABLE, KEY_ID + "=" + rowId, null);Saving Your To-Do ListIn Chapter 6 you enhanced the To-Do List example to persist the Activity's UI state across sessions.That was only half the job; in the following example you'll create a database to save the to-do items.1. Start by creating a newToDoDBAdapterclass. It will be used to manage your database inter-actions. Create private variables to store theSQLiteDatabaseobject and the Context of thecalling application. Add a constructor that takes an application Context, and create staticclass variables for the name and version of the database, as well as a name for the to-do itemtable.package com.paad.todolist;import android.content.ContentValues;import android.content.Context;import android.database.Cursor;import android.database.SQLException;import android.database.sqlite.SQLiteException;Working with SQLite Databases❘219import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;import android.util.Log;public class ToDoDBAdapter {private static final String DATABASE_NAME = "todoList.db";private static final String DATABASE_TABLE = "todoItems";private static final int DATABASE_VERSION = 1;private SQLiteDatabase db;private final Context context;public ToDoDBAdapter(Context _context) {this.context = _context;}}2. Create public convenience variables that define the column names: this will make it easier tofind the correct columns when ex

展开

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值