如何将图像从SQL数据库添加到RecyclerView

时间:2019-03-18 10:16:18

标签: android sql image android-recyclerview recycler-adapter

我想将我的SQL数据库中的食谱照片显示到RecyclerView中。我在我的Recipe类中将照片变量声明为String:

public class Recipe {

private String title;
private String photo;
private String instructions;
private int targetPeople;
private int time;



public Recipe(String title, String photo, String instructions, int targetPeople, int time) {

    this.title = title;
    this.photo = photo;
    this.instructions = instructions;
    this.targetPeople = targetPeople;
    this.time = time;
}

加上getter / setter方法。保存食谱后,我在DatabaseHelper中获得了一种方法来获取数据库内部的所有食谱:

public List<Recipe> getAllRecipes() {

    // sorting orders
    String sortOrder =
            RECIPE_TITLE + " ASC";
    List<Recipe> recipeList = new ArrayList<Recipe>();

    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.rawQuery("SELECT * FROM " + TBL_RECIPE, null);

    DatabaseUtils.dumpCursor(cursor);

    // Traversing through all rows and adding to list
    if (cursor.moveToFirst()) {
        recipeList.clear();
        do {

            Recipe recipe = new Recipe(title, photo, instructions, target, timep);
            recipe.setTitle(cursor.getString(cursor.getColumnIndex(RECIPE_TITLE)));
            recipe.setPhoto(cursor.getString(cursor.getColumnIndex(RECIPE_PHOTO)));
            recipe.setInstructions(cursor.getString(cursor.getColumnIndex(RECIPE_INSTRUCTIONS)));
            recipe.setTargetPeople(Integer.parseInt(cursor.getString(cursor.getColumnIndex(RECIPE_TARGET))));
            recipe.setTime(Integer.parseInt(cursor.getString(cursor.getColumnIndex(RECIPE_TIME))));

            // Adding user record to list
            recipeList.add(recipe);

        } while (cursor.moveToNext());
    }

    cursor.close();
    db.close();

    // return user list
    return recipeList;
}

在我将这些食谱添加到RecipeList并将它们显示在MainActivity中之后(它适用于Recipe TITLE!)。

要保存图像(直到3个),在我请求许可并在厨房或拍照之间进行选择之前,请使用以下方法保存图像:

public void onActivityResult(int requestCode, int resultCode, Intent data)
{

    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == this.RESULT_CANCELED)
    {
        return;
    }

    // GALLERY
    if (requestCode == GALLERY)
    {
        if (data != null)
        {
            Uri contentURI = data.getData();
            try
            {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), contentURI);
                String path = saveImage(bitmap);

                photoPath = path;

                Toast.makeText(AddRecipeActivity.this, "Image Saved", Toast.LENGTH_SHORT).show();

                if(pickingFor1Photo)
                {
                    add1ImageButton.setImageBitmap(bitmap);
                } else if (pickingFor2Photo)
                {
                    add2ImageButton.setImageBitmap(bitmap);
                } else if (pickingFor3Photo)
                {
                    add3ImageButton.setImageBitmap(bitmap);
                }

            }
            catch (IOException e)
            {
                e.printStackTrace();
                Toast.makeText(AddRecipeActivity.this, "Failed", Toast.LENGTH_SHORT).show();
            }
        }


    }

    // CAMERA
    else if (requestCode == CAMERA)
    {
        Bitmap thumbnail = (Bitmap) data.getExtras().get("data");

        if(pickingFor1Photo)
        {
            add1ImageButton.setImageBitmap(thumbnail);
        } else if (pickingFor2Photo)
        {
            add2ImageButton.setImageBitmap(thumbnail);
        } else if (pickingFor3Photo)
        {
            add3ImageButton.setImageBitmap(thumbnail);
        }

        String path = saveImage(thumbnail);

        photoPath = path;

        Toast.makeText(AddRecipeActivity.this, "Image Saved", Toast.LENGTH_SHORT).show();
    }
}

public String saveImage(Bitmap myBitmap)
{
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);

    // Creating images directory
    File wallpaperDirectory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString());

    if (!wallpaperDirectory.exists())
    {
        wallpaperDirectory.mkdirs();
    }

    try
    {
        File f = new File(wallpaperDirectory, Calendar.getInstance()
                .getTimeInMillis() + ".jpg");
        f.createNewFile();
        FileOutputStream fo = new FileOutputStream(f);
        fo.write(bytes.toByteArray());
        MediaScannerConnection.scanFile(this,
                new String[]{f.getPath()},
                new String[]{"image/jpeg"}, null);

        fo.flush();
        fo.close();

        return f.getAbsolutePath();
    }
    catch (IOException e1)
    {
        e1.printStackTrace();
    }

    return "";
}

然后,在我的RecyclerViewAdapter内部,将ImageView声明为ViewHolder类,并将其声明为onBindViewHolder:

    @Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, int position) {

    // retrieve UI elements inside viewHolder object
    Recipe recipe = recipeList.get(position);

    viewHolder.textViewTitle.setText(recipeList.get(position).getTitle());
    viewHolder.imageView.setImageResource(Integer.parseInt(recipeList.get(position).getPhoto()));

}

没有错误,但不起作用。感谢您的帮助

1 个答案:

答案 0 :(得分:0)

尝试使用Glide库在imageview中显示图像

将此添加到您的gradle文件中

implementation 'com.github.bumptech.glide:glide:4.8.0'

将此行替换为onBindViewHolder

viewHolder.imageView.setImageResource(Integer.parseInt(recipeList.get(position).getPhoto()));

使用

 Glide.with(mContext)
                    .load(recipeList.get(position).getPhoto())
                    .apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.ALL))
                    .apply(RequestOptions.noAnimation())
//                    .centerCrop()
                    .thumbnail(0.3f)
                    .into(viewHolder.imageView);