Как сохранить путь к изображению в базе данных SQlite и получить его для отображения в imgeView - PullRequest
0 голосов
/ 20 ноября 2018

Я хочу сохранить путь к изображению в базе данных SQlite, а затем получить его для заполнения в listView.

Вот мой код ниже. Проблема в том, что ImageView не заполняется после сохранения пути к изображению в базе данных.

Код для получения изображения Uri из галереи и получения пути к изображению

     @Override
     protected void onActivityResult(int requestCode, int resultCode, Intent 
     data) {

     if (requestCode == 1 && resultCode == Activity.RESULT_OK){
        if (data != null){
            imageUri = data.getData();
            imagePath = getImagePath(imageUri);
            itemImage.setImageURI(imageUri);
            itemImage.invalidate();
        }
    }
    }

    //Method to get the image path from the Uri
    public String getImagePath(Uri currentUri){
    String path = "no-path-found";
    String[] projection = {MediaStore.Images.Media.DATA};
    Cursor cursor = getContentResolver().query(currentUri, projection, null,
            null, null);
    if(cursor.moveToFirst()) {
        int column_Index = 
    cursor.getColumnIndex(MediaStore.Images.Media.DATA);

        path = cursor.getString(column_Index);
    }
    cursor.close();
    return path;
}

А это код для вставки изображения Путь к БД:

    private void insertItem(){

    //Get a writable database
    SQLiteDatabase database = itemDbHelper.getWritableDatabase();

    Uri mUri;

    //Get values from the fields from user
    String name = itemName.getText().toString().trim();
    imagePath = getImagePath(imageUri).trim();

    //Create a content values object to insert items
    ContentValues values = new ContentValues();
    values.put(ItemEntry.COLUMN_NAME, name);
    values.put(ItemEntry.COLUMN_IMAGE, imagePath);

Затем я использую класс Cursor Adapter для заполнения представлений:

    public class ItemCursorAdapter extends CursorAdapter {
    public ItemCursorAdapter(Context context) {
    super(context, null, 0);
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
    return LayoutInflater.from(context).inflate(R.layout.list_item, parent, 
    false);
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {

    ImageView imageView = view.findViewById(R.id.item_image);
    TextView textView = view.findViewById(R.id.item_name);

    //Fetching the values from the cursor
    String name = 
    cursor.getString(cursor.getColumnIndex(ItemEntry.COLUMN_NAME));
    String image = 
    cursor.getString(cursor.getColumnIndex(ItemEntry.COLUMN_IMAGE));

    File file = new File(image);
    Uri uri = Uri.fromFile(file);

    //Populate the views
    imageView.setImageURI(uri);
    textView.setText(name);
}

}

Вот XML-файл list_item:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

   <ImageView
    android:id="@+id/item_image"
    android:layout_width="90dp"
    android:layout_height="90dp"
    tools:src="@tools:sample/avatars" />

   <TextView
    android:id="@+id/item_name"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:textSize="20sp"
    android:textStyle="bold|italic"
    tools:text="Name"/></LinearLayout>

Как получить путь, сохраненный в базе данных, и заполнить изображение в imageView?

1 Ответ

0 голосов
/ 21 ноября 2018

Попробуйте это, я реализовал это.1-е поле таблицы BLOB подобно img_driver BLOB.

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
Bitmap mBitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();
encImage = Base64.encodeToString(byteArray, Base64.DEFAULT);

2-е изображение преобразуется в формат Base64.Этот процесс сохраняет изображение в базе данных Sqlite.

Теперь извлекает изображение из базы данных SqLite.

1-й Когда вы выбираете изображение, которое извлекается по времени в String

byte[] decodedString = Base64.decode(arr_image.get(0).getImg_driver(), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
iv_sign.setImageBitmap(decodedByte);

Base64 строка для преобразования в декодирование в byte array И вы можете установить изображение в ImageView

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...