简体   繁体   English

如何在android SQLite数据库中存储和检索图像并将它们显示在gridview上

[英]how to store and retrieve images in android SQLite database and display them on a gridview

I am new to android. 我是android的新手。 I created a table that has an itemName,Price and image. 我创建了一个具有itemName,Price和image的表。 I am trying to retrieve the image and name fields and display them on a gridview 我正在尝试检索图像和名称字段并将其显示在gridview上

Here is my create Database statement: 这是我的创建数据库语句:

 DBAdapter class onCreate()
 db.execSQL("CREATE TABLE "+ITEMS_TABLE+" ( "+ COLUMN_ITEM_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_ITEM_NAME +" TEXT, "+ COLUMN_ITEM_SPECS +" TEXT, " + COLUMN_ITEM_PRICE +
" NUMBER, " + COLUMN_ITEM_IMAGE + " BLOB, " + COLUMN_ITEM_QTY +" NUMBER)");

void AddItems(ItemsPojo itemsObj) 

{ 
     Log.i("in here", "item fields");           
     SQLiteDatabase db= DBHelper.getWritableDatabase(); 

    if (db==null) 
    { 
        Log.i("nulll", "mnllllsg"); 
    } 
    ContentValues cv=new ContentValues(); 
    cv.put(COLUMN_ITEM_NAME, itemsObj.getItemName()); 
    cv.put(COLUMN_ITEM_SPECS, itemsObj.getItemSpecs());
    cv.put(COLUMN_ITEM_PRICE, itemsObj.getItemPrice());
    cv.put(COLUMN_ITEM_QTY, itemsObj.getItemQty());
    cv.put(COLUMN_ITEM_IMAGE, itemsObj.getItemImg()); 




 long affectedColumnId = db.insert(ITEMS_TABLE, null, cv);
    db.close(); 

} 

public Bitmap  getAllImages() 
 { 
     SQLiteDatabase db=DBHelper.getWritableDatabase(); 




  //Cursor cur= db.rawQuery("Select "+colID+" as _id , "+colName+", "+colAge+" from "+employeeTable, new String [] {}); 
     Cursor cur= db.rawQuery("SELECT * FROM "+ITEMS_TABLE,null); 
     //if(cur.getCount() > 0){
         //Cursor c = mDb.query(" ... "); 
         cur.moveToFirst(); 




 ByteArrayInputStream inputStream = new ByteArrayInputStream(cur.getBlob(cur.getColumnIndex(COLUMN_ITEM_IMAGE))); 
         Bitmap b = BitmapFactory.decodeStream(inputStream); 
    // }
 return b;
 } 

In my Main Oncreate I populate my Database like this: 在我的Main Oncreate中,我填充我的数据库,如下所示:

Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.red_bn);       
        ByteArrayOutputStream out = new ByteArrayOutputStream();      
        image.compress(Bitmap.CompressFormat.PNG, 100, out); 

        byte[] b = out.toByteArray();   
        String name; 
        name="QUEEN_BED1"; 
        String specs = "blaBlaBla";
        double price = 5420;
        int qty = 10;
        ItemsPojo itemsObj = new ItemsPojo(name,specs,price,b,qty); 




    db.AddItems(itemsObj);

I am now stuck, please can anyone help me to retrieve this picture and display it on a gridview? 我现在卡住了,请有人帮我检索这张照片并将其显示在gridview上吗?

The most efficient (and btw, most straight forward approach) is to save a bytearray of the image in your local database. 最有效(也是顺便说一下,最直接的方法)是在本地数据库中保存图像的bytearray。 For that you'll just need to use a TEXT datatype in your database. 为此,您只需要在数据库中使用TEXT数据类型。 Like this: 像这样:

CREATE TABLE IF NOT EXISTS Your_table ( id INTEGER PRIMARY KEY NOT NULL UNIQUE, someOtherField TEXT, pictureData TEXT);

There's one seamless way to avoid dealing with conversions: Just convert to Bitmap and back to bytearray in your setters and getters in such a way that you don't need to care about that in the whole dev cycle. 有一种避免处理转换的无缝方法:只需转换为Bitmap并返回到setter和getter中的bytearray,这样你就不需要在整个开发周期中关心它了。 Let's go for an example. 我们来举个例子吧。 Let's say you have an object user which is stored in your localDB for which you have an avatar. 假设您有一个对象用户,该用户存储在您拥有头像的localDB中。

public class User {

    private String email;
    private String name;
    private Drawable pictureDataDrawable;

    public User() {}

    public void setPictureData(byte[] pictureData) {
        pictureDataDrawable = ImageUtils.byteToDrawable(pictureData);
    }

    public byte[] getPictureData(){
        return ImageUtils.drawableToByteArray(pictureDataDrawable);
    }

}

And wherever you retrieve your data from DB it'll be enough with adding something like that: 无论您从数据库中检索数据,只需添加以下内容即可:

user.setPictureData(cursor.getBlob(cursor.getColumnIndexOrThrow(DB_PICTURE_DATA_KEY)));

For the opposite way (writing the drawable to DB): 以相反的方式(将drawable写入DB):

ContentValues c = new ContentValues();
c.put(DB_PICTURE_DATA_KEY, user.getPictureData());
...

Finally two easy methods in your ImageUtils to convert back and forth: 最后,ImageUtils中有两种简单的方法来回转换:

public static byte[] drawableToByteArray(Drawable d) {

    if (d != null) {
        Bitmap imageBitmap = ((BitmapDrawable) d).getBitmap();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        imageBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] byteData = baos.toByteArray();

        return byteData;
    } else
        return null;

}


public static Drawable byteToDrawable(byte[] data) {

    if (data == null)
        return null;
    else
        return new BitmapDrawable(BitmapFactory.decodeByteArray(data, 0, data.length));
}

And you're good to go. 你很高兴去。

It depends on how you want to store your Image, because you are storing as a byte array here is how to retrieve it 这取决于你想如何存储你的Image,因为你作为字节数组存储这里是如何检索它

  public Cursor fetchAll() {
            return databaseHelper.query(ITEMS_TABLE, new String[] { COLUMN_ITEM_ID,   COLUMN_ITEM_NAME, COLUMN_ITEM_SPECS,COLUMN_ITEM_PRICE, COLUMN_ITEM_IMAGE,COLUMN_ITEM_QTY},null, null, null, null, null);
        }
/*    this method will give you a cursor with all the records of your database table now you need to parse these records on to objects*/

private List<ItemsPojo> parse(Cursor cursor) {
     List<ItemsPojo> toReturn = null;
     toReturn = new ArrayList<SignImage>();
     ItemsPojo obj;
     if (cursor.moveToFirst()) {
          while (cursor.isAfterLast() == false) {
               obj = new ItemsPojo();
               obj.setId(cursor.getInt(0));
               obj.setItemName(cursor.getString(1));
               obj.setItemSpecs(cursor.getString(2));
               obj.setItemPrice(cursor.getDouble(3));
               obj.setItemImg(cursor.getBlob(4));
               obj.setItemQuantity(cursor.getInt(5));
               toReturn.add(obj);
               cursor.moveToNext();
               }
     }return toReturn;
}

now you have a List with all your records on your database, now what you need to do is create a ListActivity and show all your objects on it, If you dont know how to do this please post your comment here or if you have any doubt about the procedure above 现在你有一个包含数据库中所有记录的列表,现在你需要做的是创建一个ListActivity并在其上显示你的所有对象,如果你不知道如何做到这一点,请在这里发表您的评论或如果您有任何疑问关于上述程序

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用Android应用程序将图像从SQLite数据库显示到gridview - How to display images from SQLite database to gridview using Android application 从SQLite数据库获取图像并将其显示到GridView Android Studio中 - Getting images from SQLite database and displaying them into GridView Android Studio 如何在Android的SqLite数据库中存储和检索图像? - How to store and retrive images in SqLite database in Android? 如何从图库中检索图像并将其存储在Android中的SQLite中 - How to Retrieve images from gallery and store in SQLite in android 如何在sqlite android中存储多个日期并获取它们以显示在列表中? - How to store multiple DATES in sqlite android and fetch them to display in a List? 如何从URL中检索多个图像并将其显示在Android的图库中? - How to retrieve mutiple images from url and display them in a gallery in android? 如何在Android的Sqlite数据库中存储和检索日期和时间 - How to store and retrieve date and time in Sqlite database for Android 如何从ImageView检索图像并将其存储在Android的Sqlite数据库中? - How to retrieve an image from an ImageView and store it in an Sqlite Database in Android? 在Android sqlite数据库中存储和检索Vector - store and retrieve Vector in Android sqlite database 如何从Android中的sqlite数据库检索数据并在TextView中显示 - How to retrieve data from sqlite database in android and display it in TextView
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM