2013-12-18 192 views
0

我是Android編程的初學者,我試圖在SQLite中存儲不同書籍的信息和圖像。我從網站獲得了下面的代碼的一部分。我能夠存儲信息,即作者和書名,但不知道如何存儲圖像。我爲Books.java和MySQLiteHelper.java編寫了代碼,但不知道如何使用MainActivity.java中的SQLite語句存儲和插入圖像。有人可以幫忙嗎?在SQLite中存儲圖像

這是我Book.java

public class Book { 
int id; 
String title; 
String author; 
byte[] image; 

public Book(){} 

public Book(int id,String title, String author, byte[] image) { 
    this.id=id; 
    this.title = title; 
    this.author = author; 
    this.image=image; 
} 
public Book(String title, String author,byte[] image) { 
    this.title = title; 
    this.author = author; 
    this.image=image; 
} 

//getters & setters 
// getting ID 
public int getId(){ 
    return this.id; 
} 

// setting id 
public void setId(int id){ 
    this.id = id; 
} 
// getting title 
public String getTitle(){ 
    return this.title; 
} 

// setting title 
public void setTitle(String title){ 
    this.title = title; 
} 

// getting authorname 
public String getAuthor(){ 
    return this.author; 
} 

// setting authorname 
public void setAuthor(String author){ 
    this.author = author; 
} 
//getting image 
public byte[] getImage() { 
return this.image; 
    } 
//setting image 
public void setImage(byte[] image) { 
    this.image = image; 
    } 
} 

這是我MySQLitehelper.java

public class MySQLiteHelper extends SQLiteOpenHelper { 

// Database Version 
private static final int DATABASE_VERSION = 1; 
// Database Name 
private static final String DATABASE_NAME = "BookDB"; 
// Books table name 
private static final String TABLE_BOOKS = "books"; 

// Books Table Columns names 
private static final String KEY_ID = "id"; 
private static final String KEY_TITLE = "title"; 
private static final String KEY_AUTHOR = "author"; 
private static final String KEY_IMAGE = "image"; 
public MySQLiteHelper(Context context) { 
    super(context, DATABASE_NAME, null, DATABASE_VERSION); 
} 
// Creating Tables 
@Override 
public void onCreate(SQLiteDatabase db) { 
    // SQL statement to create book table 
    String CREATE_BOOK_TABLE = "CREATE TABLE" + TABLE_BOOKS+"("+ KEY_ID +" INTEGER PRIMARY KEY,"+ KEY_TITLE+" TEXT,"+ KEY_AUTHOR+ " TEXT," + KEY_IMAGE + " BLOB" + ")";  

    // create books table 
    db.execSQL(CREATE_BOOK_TABLE); 
} 
// Upgrading database 
@Override 
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
    // Drop older books table if existed 
    db.execSQL("DROP TABLE IF EXISTS" + TABLE_BOOKS); 

    // create fresh books table 
    this.onCreate(db); 
} 
//--------------------------------------------------------------------- 
//*** CRUD operations (create "add", read "get", update, delete) book + get all books +  delete all books */ 



private static final String[] COLUMNS = {KEY_ID,KEY_TITLE,KEY_AUTHOR,KEY_IMAGE}; 

public void addBook(Book book){ 
    // 1. get reference to writable DB 
    SQLiteDatabase db = this.getWritableDatabase(); 

    // 2. create ContentValues to add key "column"/value 
    ContentValues values = new ContentValues(); 
    values.put(KEY_TITLE, book.getTitle()); // get title 
    values.put(KEY_AUTHOR, book.getAuthor()); // get author 
    values.put(KEY_IMAGE, book.getImage()); // get author 
    // 3. insert 
    db.insert(TABLE_BOOKS, // table 
      null, //nullColumnHack 
      values); // key/value -> keys = column names/ values = column values 

    // 4. close 
    db.close(); 
} 

public Book getBook(int id){ 

    // 1. get reference to readable DB 
    SQLiteDatabase db = this.getReadableDatabase(); 

    // 2. build query 
    Cursor cursor = 
      db.query(TABLE_BOOKS, // a. table 
      COLUMNS, // b. column names 
      " id = ?", // c. selections 
      new String[] { String.valueOf(id) }, // d. selections args 
      null, // e. group by 
      null, // f. having 
      null, // g. order by 
      null); // h. limit 

    // 3. if we got results get the first one 
    if (cursor != null) 
     cursor.moveToFirst(); 

    // 4. build book object 
    Book book = new Book(); 
    book.setId(Integer.parseInt(cursor.getString(0))); 
    book.setTitle(cursor.getString(1)); 
    book.setAuthor(cursor.getString(2)); 
    book.setImage(cursor.getBlob(3)); 
    // 5. return book 
    return book; 
} 

// Get All Books 
public List<Book> getAllBooks() { 
    List<Book> books = new LinkedList<Book>(); 

    // 1. build the query 
    String query = "SELECT * FROM " + TABLE_BOOKS; 

    // 2. get reference to writable DB 
    SQLiteDatabase db = this.getWritableDatabase(); 
    Cursor cursor = db.rawQuery(query, null); 

    // 3. go over each row, build book and add it to list 
    Book book = null; 
    if (cursor.moveToFirst()) { 
     do { 
      book = new Book(); 
      book.setId(Integer.parseInt(cursor.getString(0))); 
      book.setTitle(cursor.getString(1)); 
      book.setAuthor(cursor.getString(2)); 
      book.setImage(cursor.getBlob(3)); 
      // Add book to books 
      books.add(book); 
     } while (cursor.moveToNext()); 
    } 
    // return books 
    return books; 
} 

// Updating single book 
public int updateBook(Book book) { 

    // 1. get reference to writable DB 
    SQLiteDatabase db = this.getWritableDatabase(); 

    // 2. create ContentValues to add key "column"/value 
    ContentValues values = new ContentValues(); 
    values.put("title", book.getTitle()); // get title 
    values.put("author", book.getAuthor()); // get author 
    values.put("image", book.getImage()); // get image 

    // 3. updating row 
    return db.update(TABLE_BOOKS, //table 
      values, // column/value 
      KEY_ID+" = ?", // selections 
      new String[] { String.valueOf(book.getId()) }); //selection args 

} 

// Deleting single book 
public void deleteBook(Book book) { 

    // 1. get reference to writable DB 
    SQLiteDatabase db = this.getWritableDatabase(); 

    // 2. delete 
    db.delete(TABLE_BOOKS, 
      KEY_ID+" = ?", 
      new String[] { String.valueOf(book.getId()) }); 

    // 3. close 
    db.close(); 
} 
} 

這是我MainActivity.java

public class MainActivity extends Activity { 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    MySQLiteHelper db = new MySQLiteHelper(this); 

    /** 
    * CRUD Operations 
    * */ 
    // add Books 
    Log.d("Inserting: ", "Inserting all Books.."); 
    db.addBook(new Book("Android Application Development Cookbook", "Wei Meng Lee")); 
    db.addBook(new Book("Android Programming: The Big Nerd Ranch Guide", "Bill Phillips and Brian Hardy"));  
    db.addBook(new Book("Learn Android App Development", "Wallace Jackson")); 
    //Reading and getting all books 
    Log.d("Reading: ", "Reading all Books.."); 
    List<Book> list = db.getAllBooks(); 
    for (Book cn:list) { 
     String log = "Id: "+cn.getId()+" ,Title: " + cn.getTitle() + " ,Author: " + cn.getAuthor() + ",Image: "+ cn.getImage(); 
      // Writing Contacts to log 
    Log.d("Name: ", log); 
    // delete one book 
    db.deleteBook(list.get(0)); 

} 
} 
} 
+0

那麼是什麼問題..當你嘗試存儲圖像會發生什麼? –

+0

你有存儲字節數組。這是正確的,但如果你想另一種方式,那麼你可以在Base64中覆蓋字節數組,並存儲在字符串中,這樣你就可以輕鬆搞定 – PankajAndroid

回答

0

對於存儲在數據庫中的圖像,你需要將圖像數據轉換爲二進制格式,將數據存儲在數據庫中,並在檢索需要轉換的圖像時使用將其轉換爲位圖格式,但不建議這樣做,因爲將圖像存儲在數據庫中有點棘手和複雜,或者您可以將圖像存儲在sdcard中的文件夾中,並僅將路徑存儲在數據庫中,無論如何,如果您仍想存儲在數據庫中的圖像,你可以參考this question

+0

在數據庫中存儲圖像有點棘手和複雜.. ..你能否詳細說明這句話? @insomniac – Andrain

+1

參考這個答案http://stackoverflow.com/a/815639/2636887 – insomniac

+0

或這http://stackoverflow.com/a/766058/2636887 – insomniac

0
private String prepareImage(String imagepath) { 
     if (imagepath== null) { 
      return ""; 
     } 

     BitmapFactory.Options options = new BitmapFactory.Options(); 
     options.inPreferredConfig = Bitmap.Config.ARGB_8888; 
     Bitmap bitmap = BitmapFactory.decodeFile(imagepath, options); 
     bitmap = Bitmap.createScaledBitmap(bitmap, 50, 50, true); 
     ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
     bitmap.compress(Bitmap.CompressFormat.PNG, 50, baos); 
     bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos); 

     byte[] byteArray = baos.toByteArray(); 

     String imageString = com.eg_lifestyle.utils.Base64 
       .encodeBytes(byteArray); 
     bitmap = null; 
     System.gc(); 
     Runtime.getRuntime().gc(); 
     return imageString; 
    } 

我希望這是對你有用..

2
public void insertImg(int id , Bitmap img) { 


byte[] data = getBitmapAsByteArray(img); // this is a function 

insertStatement_logo.bindLong(1, id);  
insertStatement_logo.bindBlob(2, data); 

insertStatement_logo.executeInsert(); 
insertStatement_logo.clearBindings() ; 

}

public static byte[] getBitmapAsByteArray(Bitmap bitmap) { 
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); 
bitmap.compress(CompressFormat.PNG, 0, outputStream);  
return outputStream.toByteArray(); 

}

public Bitmap getImage(int i){ 

String qu = "select img from table where feedid=" + i ; 
Cursor cur = db.rawQuery(qu, null); 

if (cur.moveToFirst()){ 
    byte[] imgByte = cur.getBlob(0); 
    cur.close(); 
    return BitmapFactory.decodeByteArray(imgByte, 0, imgByte.length); 
} 
if (cur != null && !cur.isClosed()) { 
    cur.close(); 
}  

return null ; 

}

More

0

此代碼對我來說。你可以得到適當的解決方案

Uri selectedImage = data.getData(); 
    ImageView imageView=(ImageView)this.findViewById(R.id.imageView1); 

    getContentResolver().notifyChange(selectedImage, null); 

    ContentResolver cr = getContentResolver(); 
    Bitmap bitmap; 
    try { 


     bitmap = android.provider.MediaStore.Images.Media 
     .getBitmap(cr, selectedImage); 
     imageView.setImageBitmap(bitmap); 

     ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
     bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); 
     byte[] b = baos.toByteArray(); 
     String encodedImageString = Base64.encodeToString(b, Base64.DEFAULT); 

     byte[] bytarray = Base64.decode(encodedImageString, Base64.DEFAULT); 
     Bitmap bmimage = BitmapFactory.decodeByteArray(bytarray, 0, 
       bytarray.length); 

     myDb.execSQL("INSERT INTO imgtbl VALUES('"+encodedImageString+"');"); 
     Cursor c= myDb.rawQuery("SELECT * FROM imgtbl", null); 

     c.moveToFirst(); 
     String img=c.getString(0); 
     byte[] byarray = Base64.decode(img, Base64.DEFAULT); 
     Bitmap bmimg = BitmapFactory.decodeByteArray(byarray, 0, 
       byarray.length); 

     ImageView iv=(ImageView)findViewById(R.id.img2); 
     ImageView iv1=(ImageView)findViewById(R.id.img3); 

     iv.setImageBitmap(bmimg); 
     iv1.setImageBitmap(bmimg); 


    } catch (Exception e) { 
     Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT) 
       .show(); 

     e.printStackTrace(); 
    }