Last active
August 21, 2018 13:15
-
-
Save OrenBochman/52ad8085bbf19027be921ef6d3c6ac4e to your computer and use it in GitHub Desktop.
Load image and save to sqlite database as blob
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* This code will take a image from url and convert is to a byte array | |
*/ | |
private void getImage(){ | |
byte[] logoImage = getLogoImage(IMAGEURL); | |
} | |
/** | |
* get an image from the web anc conver to byteArray | |
*/ | |
private byte[] getLogoImage(String url){ | |
try { | |
URL imageUrl = new URL(url); | |
URLConnection ucon = imageUrl.openConnection(); | |
InputStream is = ucon.getInputStream(); | |
BufferedInputStream bis = new BufferedInputStream(is); | |
ByteArrayBuffer baf = new ByteArrayBuffer(500); | |
int current = 0; | |
while ((current = bis.read()) != -1) { | |
baf.append((byte) current); | |
} | |
return baf.toByteArray(); | |
} catch (Exception e) { | |
Log.d("ImageManager", "Error: " + e.toString()); | |
} | |
return null; | |
} | |
/** | |
* To save the image to db i used this code | |
*/ | |
public void insertUser(){ | |
SQLiteDatabase db = dbHelper.getWritableDatabase(); | |
String delSql = "DELETE FROM ACCOUNTS"; | |
SQLiteStatement delStmt = db.compileStatement(delSql); | |
delStmt.execute(); | |
String sql = "INSERT INTO ACCOUNTS (account_id,account_name,account_image) VALUES(?,?,?)"; | |
SQLiteStatement insertStmt = db.compileStatement(sql); | |
insertStmt.clearBindings(); | |
insertStmt.bindString(1, Integer.toString(this.accId)); | |
insertStmt.bindString(2,this.accName); | |
insertStmt.bindBlob(3, this.accImage); | |
insertStmt.executeInsert(); | |
db.close(); | |
} | |
//To retrieve the image back this is code i used. | |
public Account getCurrentAccount() { | |
SQLiteDatabase db = dbHelper.getWritableDatabase(); | |
String sql = "SELECT * FROM ACCOUNTS"; | |
Cursor cursor = db.rawQuery(sql, new String[] {}); | |
if(cursor.moveToFirst()){ | |
this.accId = cursor.getInt(0); | |
this.accName = cursor.getString(1); | |
this.accImage = cursor.getBlob(2); | |
} | |
if (cursor != null && !cursor.isClosed()) { | |
cursor.close(); | |
} | |
db.close(); | |
if(cursor.getCount() == 0){ | |
return null; | |
} else { | |
return this; | |
} | |
} | |
/** | |
* Finally to load this image to a imageview | |
*/ | |
public static void setImage(){ | |
logoImage.setImageBitmap(BitmapFactory.decodeByteArray( | |
currentAccount.accImage, | |
0, | |
currentAccount.accImage.length)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment