SQLite存取图片并列表显示

一:数据库表的创建

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",null,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, 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",null,values); 
    }
   
     }

//更新数据
    public void update(Person person){
    SQLiteDatabase db=dbHelper.getReadableDatabase();
    db.execSQL("update person set name=?,age=? where personid=?", new Object[]{person.getName(),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,0,in.length);           
  
    return new Person(name,age,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,0,in.length);           
     
       Person person = new Person(name,age,bmpout,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,age,photo from person limit ?,?",new String[]{String.valueOf(offer),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,photo,null);
  Person person3 = new Person("yuan1",13,photo,null);
  Person person4 = new Person("ming1",14,photo,null);
  Person person5 = new Person("qing1",15,photo,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
    + "]";
 }
 
 

}

 

 

运行效果图:

  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值