2017-08-02 98 views
0

我想從sqlite的串一個blob,請參閱以下內容:SQLite的圖像斑點串

ArrayList<Sudentdb> list; 

GridView gridView; 

final String[] from = new String[] { SQLiteHelper._ID, 
     SQLiteHelper.NAME, SQLiteHelper.AGE, SQLiteHelper.PROFILE }; 

final int[] to = new int[] { R.id.rowid, R.id.txtName, R.id.studentage, R.id.profileimageV }; 

@Nullable 
@Override 
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 

    View v = inflater.inflate(R.layout.studentfragment, null); 

    gridView = (GridView) v.findViewById(R.id.gridView); 

    DBManager dbManager = new DBManager(getActivity()); 
    dbManager.open(); 

    Cursor cursor = dbManager.fetch(); 

    list = new ArrayList<>(); 
    SimpleCursorAdapter adapter = new SimpleCursorAdapter(getActivity(), R.layout.single_item, cursor, from, to, 0); 

    gridView.setAdapter(adapter); 

我已經測試只返回文本,並將其正確地返回,但與圖片,我收到了錯誤:

android.database.sqlite.SQLiteException: unknown error (code 0): Unable to convert BLOB to string 

我假設我首先必須從數據庫中獲取圖像?任何幫助?

編輯

我明白你爲什麼會覺得這個問題是SimpleCursorAdapter how to show an image?重複,但在這一問題的圖像存儲在繪製文件夾,他被保存和調用一個形象的名稱串入sqlite。在我的情況下,圖像是在圖庫中,我將它作爲blob保存到SQLite(在另一個活動中),現在我試圖從數據庫中獲取blob,並將其顯示在GridView中。

所以在回答下列不會爲我工作:

int resID = getApplicationContext().getResources().getIdentifier(cursor.getString(columnIndex), "drawable", getApplicationContext().getPackageName()); 
IV.setImageDrawable(getApplicationContext().getResources().getDrawable(resID)); 

回答

0

你可以用它來獲取BLOB作爲字節[]從SQLITE

byte[] img = cursor.getBlob(cursor.getColumnIndex(IMG_SRC)); 

然後轉換字節[]爲位圖使用下面的Util方法...

public static Bitmap getbitmap(byte[] img) { 
     return BitmapFactory.decodeByteArray(img, 0, img.length); 
    } 
+0

好吧,我將如何添加每個圖像在特定的視圖?目前,我使用SimpleCursorAdapter在每個視圖中設置文本。 – ClassA

+0

ok只是使用yourholder.imgview.setImageBitmap(bitmap); –

+0

請看我的代碼'final int [] to'圖像位置由SQLite中的行的id確定 – ClassA