How to add image from SQL Database into RecyclerView

佐手、 提交于 2019-12-25 01:08:27

问题


I want to display a Recipe photo from my SQL Database into my RecyclerView. I declared as String the photo variable in my Recipe class:

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;
}

plus getter/setter methods. After saving the Recipe, I got a method in the DatabaseHelper to get all the recipes inside the database:

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;
}

After I'm going to add these recipes to a RecipeList and displaying them into the MainActivity (and it works for the Recipe TITLE!).

To save the images (until 3), before I ask for permissions and to choose between galley or to take a picture, then I save it with these methods:

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 "";
}

Then, inside my RecyclerViewAdapter, I declared my ImageView into the ViewHolder class and this inside 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()));

}

There aren't errors but it doesn't works. Thanks for helping


回答1:


Try showing image in imageview using Glide library this way

add this in your gradle file

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

Replace this line in onBindViewHolder

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

with

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


来源:https://stackoverflow.com/questions/55219031/how-to-add-image-from-sql-database-into-recyclerview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!