Answer the question
In order to leave comments, you need to log in
How to transfer a picture in the BLOB format of the database field from the service to the ImageView of the android device?
Hello.
I am making the following application:
There is a certain SQlite database on the server, it has a table, and in the table field there is a picture (code below):
CREATE TABLE test (rowid INTEGER PRIMARY KEY AUTOINCREMENT, num1 REAL, num2 REAL, num3 REAL, num4 REAL, picture BLOB);
INSERT INTO test (num1, num2, num3, num4, picture) VALUES(1.1, 1.2, 1.3, 1.4, readfile('download.png'));
private JSONArray getDbDataInJsonArrayFormat() {
String sql = "SELECT rowid, num1, num2, num3, num4, picture FROM test";
try (Connection conn = this.connect();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
JSONArray jsonResult = new JSONArray();
while (rs.next()) {
JSONObject jsonRow = new JSONObject();
jsonRow.accumulate("picture", rs.getString("picture"));
jsonResult.put(jsonRow);
}
return jsonResult;
} catch (SQLException e) {
LOG.error(e.getMessage());
return null;
}
}
try {
db.beginTransaction();
for (int i = 0; i < response.length(); i++) {
JSONObject jsonRow = response.getJSONObject(i);
String picture = jsonRow.getString("picture");
ContentValues values = new ContentValues();
values.put(Test.PICTURE, picture);
db.insert(TEST, null, values);
}
db.setTransactionSuccessful();
} catch (Exception e) {
Log.w("Error: ", e);
} finally {
db.endTransaction();
}
public Cursor getAllDataFromTestTable() {
SQLiteDatabase db = mDbOpenHelper.getWritableDatabase();
String table = TEST;
Cursor c = db.query(table, null,
null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
public static List<ContentValues> getResultStringListAndClose(Cursor c) {
final List<ContentValues> resultStringList = getAllDataFromDB(c);
closeCursor(c);
return resultStringList;
}
private void onDataLoadedFromDb(Cursor c) {
List<ContentValues> resList = DbUtils.getResultStringListAndClose(c);
for (int i = 0; i < resList.size(); ++i) {
ContentValues rowValues = resList.get(i);
// picture
ImageView picture = new ImageView(this);
byte[] encodeByte = rowValues.getAsByteArray(DbContract.Test.PICTURE);
Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
picture.setImageBitmap(Bitmap.createScaledBitmap(bitmap, picture.getWidth(),
picture.getHeight(), false));
}
}
Answer the question
In order to leave comments, you need to log in
All this is crap. Do not store pictures in the database. Store files and paths to them. Especially on Android, the cursor size is limited, and there will be uploads on the main thread, which means brakes. Give the path in json too. Load in Android using special libs. Glide, picasso, fresco, something like that.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question