package com.changcheng.sqlite.service;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import com.changcheng.sqlite.MyOpenHelper;
import com.changcheng.sqlite.entity.Contact;
public class ContactsService {
private MyOpenHelper openHelper;
public ContactsService(Context context) {
this.openHelper = new MyOpenHelper(context);
}
/**
* 保存
*
* @param contact
*/
public void save(Contact contact) {
String sql = "INSERT INTO contacts (name, phone) VALUES (?, ?)";
Object[] bindArgs = { contact.getName(), contact.getPhone() };
this.openHelper.getWritableDatabase().execSQL(sql, bindArgs);
}
/**
* 查找
*
* @param id
* @return
*/
public Contact find(Integer id) {
String sql = "SELECT _id,name, phone FROM contacts WHERE _id=?";
String[] selectionArgs = { id + "" };
Cursor cursor = this.openHelper.getReadableDatabase().rawQuery(sql,
selectionArgs);
if (cursor.moveToFirst())
return new Contact(cursor.getInt(0), cursor.getString(1), cursor
.getString(2));
return null;
}
/**
* 更新
*
* @param contact
*/
public void update(Contact contact) {
String sql = "UPDATE contacts SET name=?, phone=? WHERE _id=?";
Object[] bindArgs = { contact.getName(), contact.getPhone(),
contact.get_id() };
this.openHelper.getWritableDatabase().execSQL(sql, bindArgs);
}
/**
* 删除
*
* @param id
*/
public void delete(Integer id) {
String sql = "DELETE FROM contacts WHERE _id=?";
Object[] bindArgs = { id };
this.openHelper.getReadableDatabase().execSQL(sql, bindArgs);
}
/**
* 获取记录数量
*
* @return
*/
public long getCount() {
String sql = "SELECT count(*) FROM contacts";
Cursor cursor = this.openHelper.getReadableDatabase().rawQuery(sql,
null);
cursor.moveToFirst();
return cursor.getLong(0);
}
/**
* 获取分页数据
*
* @param startIndex
* @param maxCount
* @return
*/
public List<Contact> getScrollData(long startIndex, long maxCount) {
String sql = "SELECT _id,name,phone FROM contacts LIMIT ?,?";
String[] selectionArgs = { String.valueOf(startIndex),
String.valueOf(maxCount) };
Cursor cursor = this.openHelper.getReadableDatabase().rawQuery(sql,
selectionArgs);
List<Contact> contacts = new ArrayList<Contact>();
while (cursor.moveToNext()) {
Contact contact = new Contact(cursor.getInt(0),
cursor.getString(1), cursor.getString(2));
contacts.add(contact);
}
return contacts;
}
/**
* 获取分页数据,提供给SimpleCursorAdapter使用。
*
* @param startIndex
* @param maxCount
* @return
*/
public Cursor getScrollDataCursor(long startIndex, long maxCount) {
String sql = "SELECT _id,name,phone FROM contacts LIMIT ?,?";
String[] selectionArgs = { String.valueOf(startIndex),
String.valueOf(maxCount) };
Cursor cursor = this.openHelper.getReadableDatabase().rawQuery(sql,
selectionArgs);
return cursor;
}
}
|