Для вставки большого количества данных (например, изображений) в базу данных SQLite можно использовать, конвертируя наш образ в массив байтов и сохраняя его в SQLite.
Здесь мы видим один пример, который магазин Служащий Детали Как
Имя сотрудника
Сотрудник Фото
Сотрудник Возраст
Для Имя Сотрудника мы используем текстовый тип данных и для Emp loyee Age integer datatype. Но хранить данные о сотрудниках, тип данных? в то время мы используем тип данных BLOB.
insertEmpDetails()
Метод, который взят в качестве параметра Employee Class, и хранит всю информацию Сотрудника в таблице сотрудников. Здесь мы можем видеть перед вставкой изображения в базу данных, мы должны преобразовать ваш образ Bitmap в массив байтов, потому что мы используем метод getBytes() класса Utility.
retriveEmpDetails()
метод, который извлекает данные о сотрудниках из базы данных и возвращает объект сотрудника. Чтобы получить все Имя, Фотография, Возраст мы используем Соответствующие методы getXXX(). Во время восстановления фотографии мы получим blob [] массив изображения. В это время нам нужно преобразовать массив байтов в изображение. Для этой цели мы используем метод getPhoto() в классе Utility, который преобразует наш массив блоков в растровое изображение и извлечение растрового изображения.
UI Layout (activity_main.xml)
Этот макет используется для просмотра
Имя сотрудника
Сотрудник Фото
Сотрудник Возраст
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageView
android:id="@+id/ivMain"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scaleType="fitCenter" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="EMPLOYEE_NAME" />
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="25dp"
android:text="NAME" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="EMPLOYEE_PHOTO" />
<ImageView
android:id="@+id/photo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="25dp" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/text3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="EMPLOYEE_AGE" />
<TextView
android:id="@+id/age"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="25dp"
android:text="AGE" />
</LinearLayout>
</LinearLayout>
Android активность (InsertandRetriveBlobData.java)
package com.androidsurya.sqliteexample;
import android.app.Activity;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
public class InsertandRetriveBlobData extends Activity {
private DBhelper DbHelper;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DbHelper = new DBhelper(this);
Employee employee_One = new Employee(BitmapFactory.decodeResource(
getResources(), R.drawable.photo), "Surya", 25);
DbHelper.open();
DbHelper.insertEmpDetails(employee_One);
DbHelper.close();
employee_One = null;
DbHelper.open();
employee_One = DbHelper.retriveEmpDetails();
DbHelper.close();
TextView empname = (TextView) findViewById(R.id.name);
empname.setText(employee_One.getName());
ImageView empphoto = (ImageView) findViewById(R.id.photo);
empphoto.setImageBitmap(employee_One.getBitmap());
TextView empage = (TextView) findViewById(R.id.age);
empage.setText("" + employee_One.getAge());
}
}
DBhelper.java
Это класс базы данных здесь мы объявляем
insertEmpDetails()
метод для вставки детали работника и retriveEmpDetails()
метод извлечения сотрудника Подробнее
package com.androidsurya.sqliteexample;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBhelper {
public static final String EMP_ID = "id";
public static final String EMP_NAME = "name";
public static final String EMP_AGE = "age";
public static final String EMP_PHOTO = "photo";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_NAME = "EmployessDB.db";
private static final int DATABASE_VERSION = 1;
private static final String EMPLOYEES_TABLE = "Employees";
private static final String CREATE_EMPLOYEES_TABLE = "create table "
+ EMPLOYEES_TABLE + " (" + EMP_ID
+ " integer primary key autoincrement, " + EMP_PHOTO
+ " blob not null, " + EMP_NAME + " text not null unique, "
+ EMP_AGE + " integer);";
private final Context mCtx;
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_EMPLOYEES_TABLE);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + EMPLOYEES_TABLE);
onCreate(db);
}
}
public void Reset() {
mDbHelper.onUpgrade(this.mDb, 1, 1);
}
public DBhelper(Context ctx) {
mCtx = ctx;
mDbHelper = new DatabaseHelper(mCtx);
}
public DBhelper open() throws SQLException {
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
public void insertEmpDetails(Employee employee) {
ContentValues cv = new ContentValues();
cv.put(EMP_PHOTO, Utility.getBytes(employee.getBitmap()));
cv.put(EMP_NAME, employee.getName());
cv.put(EMP_AGE, employee.getAge());
mDb.insert(EMPLOYEES_TABLE, null, cv);
}
public Employee retriveEmpDetails() throws SQLException {
Cursor cur = mDb.query(true, EMPLOYEES_TABLE, new String[] { EMP_PHOTO,
EMP_NAME, EMP_AGE }, null, null, null, null, null, null);
if (cur.moveToFirst()) {
byte[] blob = cur.getBlob(cur.getColumnIndex(EMP_PHOTO));
String name = cur.getString(cur.getColumnIndex(EMP_NAME));
int age = cur.getInt(cur.getColumnIndex(EMP_AGE));
cur.close();
return new Employee(Utility.getPhoto(blob), name, age);
}
cur.close();
return null;
}
}
Utility.java
класс Утилиты главная роль здесь Перед вставкой изображения и retrive изображения из базы данных SQLite мы используем их ниже методы. getBytes()
Преобразования растрового изображения в массиве байт и Retrun байт [] getPhoto()
новообращенных байт [] в растровое изображение и Retrun растрового изображения
package com.androidsurya.sqliteexample;
import java.io.ByteArrayOutputStream;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
public class Utility {
// convert from bitmap to byte array
public static byte[] getBytes(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, stream);
return stream.toByteArray();
}
// convert from byte array to bitmap
public static Bitmap getPhoto(byte[] image) {
return BitmapFactory.decodeByteArray(image, 0, image.length);
}
}
Регистрация Android активности в AndroidManifest файл
<activity
android:name="com.androidsurya.sqliteexample.InsertandRetriveBlobData"
android:label="@string/app_name" >