一:数据库表的创建
public class DatebaseHelper extends sqliteOpenHelper {
public final static String NAME="nyist";
public final static int VERSION=1;
public DatebaseHelper(Context context) {
super(context,NAME,null,VERSION);
}
@Override
public void onCreate(sqliteDatabase db) {
// TODO Auto-generated method stub
db.execsql("CREATE TABLE person (personid integer primary key autoincrement,name varchar(20),age integer,photo blob)");
}
@Override
public void onUpgrade(sqliteDatabase db,int arg1,int arg2) {
// TODO Auto-generated method stub
db.execsql("DROP TABLE IF EXISTS person");
onCreate(db);
}
}
二:数据库的操作
public class DatebaseService {
private DatebaseHelper dbHelper;
public DatebaseService(Context context) {
this.dbHelper = new DatebaseHelper(context);
}
//保存数据。
public void save(Person person){
sqliteDatabase db=dbHelper.getWritableDatabase();
// db.execsql("insert into person(name,age,photo) values(?,?)",new Object[]{person.getName(),person.getAge()});
ContentValues values = new ContentValues();
final ByteArrayOutputStream os = new ByteArrayOutputStream();
Bitmap bmp =person.getPhoto();
bmp.compress(Bitmap.CompressFormat.PNG,100,os);
values.put("photo",os.toByteArray());
/**
* Bitmap.CompressFormat.JPEG 和 Bitmap.CompressFormat.PNG
* JPEG 与 PNG 的是区别在于 JPEG是有损数据图像,PNG使用从LZ77派生的无损数据压缩算法。
* 这里建议使用PNG格式保存
* 100 表示的是质量为100%。当然,也可以改变成你所需要的百分比质量。
* os 是定义的字节输出流
*
* .compress() 方法是将Bitmap压缩成指定格式和质量的输出流
*/
values.put("name",person.getName());
values.put("age",person.getAge());
db.insert("person",values);
}
public void savePersons(List<Person> persons){
for(Person person:persons){
sqliteDatabase db=dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
final ByteArrayOutputStream os = new ByteArrayOutputStream();
Bitmap bmp =person.getPhoto();
bmp.compress(Bitmap.CompressFormat.PNG,values);
}
}
//更新数据
public void update(Person person){
sqliteDatabase db=dbHelper.getReadableDatabase();
db.execsql("update person set name=?,age=? where personid=?",person.getAge(),person.getPersonid()});
}
//查找数据
public Person find(Integer personid){
sqliteDatabase db=dbHelper.getReadableDatabase();
Cursor cursor=db.rawQuery("select * from person where personid=?",new String[]{personid.toString()} );
while(cursor.moveToNext()){
String name=cursor.getString(cursor.getColumnIndex("name"));
Integer age=cursor.getInt(cursor.getColumnIndex("age"));
Integer id=cursor.getInt(cursor.getColumnIndex("personid"));
//从数据库获取图片
byte[] in=cursor.getBlob(cursor.getColumnIndex("photo"));
Bitmap bmpout=BitmapFactory.decodeByteArray(in,in.length);
return new Person(name,bmpout,id);
}
return null;
}
//删除数据
public void delete(Integer personid){
sqliteDatabase db=dbHelper.getReadableDatabase();
db.execsql("delete from person where personid=?",new Object[]{personid});
}
public Long getCount(){
sqliteDatabase db=dbHelper.getReadableDatabase();
Cursor cursor = db.rawQuery("select count(*) from person",null);
cursor.moveToFirst();
return cursor.getLong(0);
}
//分页显示 返回的是List集合
public List<Person> getScrollData(int offer,int maxResult){
List<Person> persons=new ArrayList<Person>();
sqliteDatabase db=dbHelper.getReadableDatabase();
Cursor cursor=db.rawQuery("select * from person limit ?,?",new String[]{String.valueOf(offer),String.valueOf(maxResult)});
while(cursor.moveToNext()){
Integer id=cursor.getInt(cursor.getColumnIndex("personid"));
String name=cursor.getString(cursor.getColumnIndex("name"));
Integer age=cursor.getInt(cursor.getColumnIndex("age"));
byte[] in=cursor.getBlob(cursor.getColumnIndex("photo"));
Bitmap bmpout=BitmapFactory.decodeByteArray(in,in.length);
Person person = new Person(name,id);
persons.add(person);
}
return persons;
}
//分页显示 返回的是Cursor游标
public Cursor getCursorScrollData(int offer,int maxResult){
List<Person> persons=new ArrayList<Person>();
sqliteDatabase db=dbHelper.getReadableDatabase();
Cursor cursor=db.rawQuery("select personid as _id,name,photo from person limit ?,String.valueOf(maxResult)});
return cursor;
}
}
public class MainActivity extends Activity {
private ListView listview;
private List<Person> persons = new ArrayList<Person>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DatebaseService service=new DatebaseService(this);
Bitmap photo = BitmapFactory.decodeResource(this.getResources(),R.drawable.photo);
//将数据存入数据库
Person person1 = new Person("tang1",11,photo,null);
Person person2 = new Person("song1",12,null);
Person person3 = new Person("yuan1",13,null);
Person person4 = new Person("ming1",14,null);
Person person5 = new Person("qing1",15,null);
persons.add(person5);
persons.add(person4);
persons.add(person3);
persons.add(person2);
persons.add(person1);
service.savePersons(persons);
//
listview=(ListView)this.findViewById(R.id.listview);
List<Person> persons= service.getScrollData(0,5);
/*if(persons!=null){
MyListAdapter adapter=new MyListAdapter(MainActivity.this,persons);
listview.setAdapter(adapter);
}*/
//
List<HashMap<String,Object>> data= new ArrayList<HashMap<String,Object>>();
//通过迭代将persons放入data里面
if(persons!=null){
for(Person person:persons){
HashMap<String,Object> items=new HashMap<String,Object>();
items.put("photo",person.getPhoto());
items.put("id",person.getPersonid());
items.put("name",person.getName());
items.put("age",person.getAge());
data.add(items);
}
SimpleAdapter adapter = new SimpleAdapter(this,data,R.layout.list_item,
new String[]{"photo","id","name","age"},new int[]{R.id.photo,R.id.id,R.id.name,R.id.age});
adapter.setViewBinder(new MyViewBinder());
listview.setAdapter(adapter);
}
//
listview.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent,View view,int position,
long id) {
// TODO Auto-generated method stub
ListView lView=(ListView)parent;
HashMap<String,Object> data=(HashMap<String,Object>)lView.getItemAtPosition(position);
Toast.makeText(MainActivity.this,String.valueOf(data.get("id")),Toast.LENGTH_SHORT).show();
}
});
}
}
//实现ViewBinder接口
class MyViewBinder implements ViewBinder
{
/**
* view:要板顶数据的视图
* data:要绑定到视图的数据
* textRepresentation:一个表示所支持数据的安全的字符串,结果是data.toString()或空字符串,但不能是Null
* 返回值:如果数据绑定到视图返回真,否则返回假
*/
@Override
public boolean setViewValue(View view,Object data,
String textRepresentation) {
if((view instanceof ImageView)&(data instanceof Bitmap))
{
ImageView iv = (ImageView)view;
Bitmap bmp = (Bitmap)data;
iv.setImageBitmap(bmp);
return true;
}
return false;
}
}
四:布局文件与实例Person
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/photo"
android:layout_weight="1"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="id"
android:id="@+id/id"
android:layout_weight="1"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="name"
android:id="@+id/name"
android:layout_weight="1"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="age"
android:id="@+id/age"
android:layout_weight="1"
/>
</LinearLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<LinearLayout
android:layout_gravity="fill_horizontal"
android:orientation="horizontal"
android:padding="5dp"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="20dp"
android:text="头像"
android:id="@+id/photo"
android:layout_weight="1"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="编号"
android:id="@+id/id"
android:layout_weight="1"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="姓名"
android:id="@+id/name"
android:layout_weight="1"
/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="年龄"
android:id="@+id/age"
android:layout_weight="1"
/>
</LinearLayout>
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/listview"
android:layout_gravity="fill_horizontal"
/>
</GridLayout>
Person实例
public class Person {
private String name;
private Integer age;
private Bitmap photo;
private Integer personid;
public Person(String name,Integer age,Bitmap photo,Integer personid) {
super();
this.name = name;
this.age = age;
this.photo = photo;
this.personid = personid;
}
public Person() {
super();
// TODO Auto-generated constructor stub
}
public Integer getPersonid() {
return personid;
}
public void setPersonid(Integer personid) {
this.personid = personid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Bitmap getPhoto() {
return photo;
}
public void setPhoto(Bitmap photo) {
this.photo = photo;
}
@Override
public String toString() {
return "Persion [name=" + name + ",age=" + age + ",photo=" + photo
+ "]";
}
}
运行效果图:
原文链接:https://www.f2er.com/sqlite/201247.html