android – How do I put an image from SQLite GridView in ImageView?-ThrowExceptions

Exception or error:

We need your much-respected help. In view of the lack of sufficient experience.
There is a SQLite database in which I store an image and 2 text fields + id. The list with data is displayed in GridView. Tried to do the following:

gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Intent i = new Intent(FoodList.this, FullView.class);
    Cursor c = MainActivity.sqLiteHelper.getData2("SELECT image FROM FOOD WHERE id = "+id);

    ArrayList<Integer> arrID = new ArrayList<Integer>();
    while (c.moveToNext()){
        //arrID.add(c.getInt(3));
        byte[] image = c.getBlob(3);

        Bitmap bm = BitmapFactory.decodeByteArray(image, 0 ,image.length);
        ImageView im3 = (ImageView)findViewById(R.id.imageView3);

        im3.setImageBitmap(bm);
    }


}
});

Nothing comes out.

Here is the SQLiteHelper class.

public class SQLiteHelper extends SQLiteOpenHelper {

public SQLiteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
    super(context, name, factory, version);
}

public void queryData(String sql){
    SQLiteDatabase database = getWritableDatabase();
    database.execSQL(sql);
}

public void insertData(String name, String price, byte[] image){
    SQLiteDatabase database = getWritableDatabase();
    String sql = "INSERT INTO FOOD VALUES (NULL, ?, ?, ?)";

    SQLiteStatement statement = database.compileStatement(sql);
    statement.clearBindings();

    statement.bindString(1, name);
    statement.bindString(2, price);
    statement.bindBlob(3, image);

    statement.executeInsert();
}

public void updateData(String name, String price, byte[] image, int id) {
    SQLiteDatabase database = getWritableDatabase();

    String sql = "UPDATE FOOD SET name = ?, price = ?, image = ? WHERE id = ?";
    SQLiteStatement statement = database.compileStatement(sql);

    statement.bindString(1, name);
    statement.bindString(2, price);
    statement.bindBlob(3, image);
    statement.bindDouble(4, (double)id);

    statement.execute();
    database.close();
}

public  void deleteData(int id) {
    SQLiteDatabase database = getWritableDatabase();

    String sql = "DELETE FROM FOOD WHERE id = ?";
    SQLiteStatement statement = database.compileStatement(sql);
    statement.clearBindings();
    statement.bindDouble(1, (double)id);

    statement.execute();
    database.close();
}




public Cursor getData(String sql){
    SQLiteDatabase database = getReadableDatabase();
    return database.rawQuery(sql, null);
}



@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {

}

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

}
}

Here is the FoodList class in which all data is output.

public class FoodList extends AppCompatActivity {
ImageView im3;
GridView gridView;
ArrayList<Food> list;
public  Bitmap bm, bitmap;
FoodListAdapter adapter = null;
ViewPager viewPager;
Cursor cursor;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_food_list);
    gridView = (GridView) findViewById(R.id.gridView);
    list = new ArrayList<>();
    adapter = new FoodListAdapter(this, R.layout.food_items, list);
    gridView.setAdapter(adapter);

    // get all data from sqlite
    Cursor cursor = MainActivity.sqLiteHelper.getData("SELECT * FROM FOOD");
    list.clear();
    while (cursor.moveToNext()) {
        int id = cursor.getInt(0);
        String name = cursor.getString(1);
        String price = cursor.getString(2);
        byte[] image = cursor.getBlob(3);

        list.add(new Food(name, price, image, id));
    }
    adapter.notifyDataSetChanged();
      gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
  @Override
   public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Intent i = new Intent(FoodList.this, FullView.class);
    Cursor c = MainActivity.sqLiteHelper.getData("SELECT image FROM FOOD WHERE id = "+id);

    ArrayList<Integer> arrID = new ArrayList<Integer>();
    while (c.moveToNext()){
        //arrID.add(c.getInt(3));
        byte[] image = c.getBlob(3);

        Bitmap bm = BitmapFactory.decodeByteArray(image, 0 ,image.length);
        ImageView im3 = (ImageView)findViewById(R.id.imageView3);

        im3.setImageBitmap(bm);
    }
     }
       });
    gridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, final int position,
      long id) {

            CharSequence[] items = {"Update", "Delete"};
            AlertDialog.Builder dialog = new AlertDialog.Builder(FoodList.this);

            dialog.setTitle("Choose an action");
            dialog.setItems(items, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int item) {
                    if (item == 0) {
                        // update
                        Cursor c = MainActivity.sqLiteHelper.getData("SELECT id FROM FOOD");
                        ArrayList<Integer> arrID = new ArrayList<Integer>();
                        while (c.moveToNext()){
                            arrID.add(c.getInt(0));
                        }
                        // show dialog update at here
                        showDialogUpdate(FoodList.this, arrID.get(position));

                    } else {
                        // delete
                        Cursor c = MainActivity.sqLiteHelper.getData("SELECT id FROM FOOD");
                        ArrayList<Integer> arrID = new ArrayList<Integer>();
                        while (c.moveToNext()){
                            arrID.add(c.getInt(0));
                        }
                        showDialogDelete(arrID.get(position));
                    }
                }
            });
            dialog.show();
            return true;
        }
    });
}

ImageView imageViewFood;
private void showDialogUpdate(Activity activity, final int position){

    final Dialog dialog = new Dialog(activity);
    dialog.setContentView(R.layout.update_food_activity);
    dialog.setTitle("Update");

    imageViewFood = (ImageView) dialog.findViewById(R.id.imageViewFood);

    final EditText edtName = (EditText) dialog.findViewById(R.id.edtName);
    final EditText edtPrice = (EditText) dialog.findViewById(R.id.edtPrice);
    Button btnUpdate = (Button) dialog.findViewById(R.id.btnUpdate);

    // set width for dialog
    int width = (int) (activity.getResources().getDisplayMetrics().widthPixels * 0.95);
    // set height for dialog
    int height = (int) (activity.getResources().getDisplayMetrics().heightPixels * 0.7);
    dialog.getWindow().setLayout(width, height);
    dialog.show();

    imageViewFood.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // request photo library
            ActivityCompat.requestPermissions(
                    FoodList.this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    888
            );
        }
    });

    btnUpdate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                MainActivity.sqLiteHelper.updateData(
                       edtName.getText().toString().trim(),
                      edtPrice.getText().toString().trim(),
                        MainActivity.imageViewToByte(imageViewFood),
                        position
                );
                dialog.dismiss();
                Toast.makeText(getApplicationContext(), "Update 
           successfully!!!",Toast.LENGTH_SHORT).show();
            }
            catch (Exception error) {
                Log.e("Update error", error.getMessage());
            }
            updateFoodList();
        }
    });
}

private void showDialogDelete(final int idFood){
    final AlertDialog.Builder dialogDelete = new AlertDialog.Builder(FoodList.this);

    dialogDelete.setTitle("Warning!!");
    dialogDelete.setMessage("Are you sure you want to this delete?");
    dialogDelete.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            try {
                MainActivity.sqLiteHelper.deleteData(idFood);
                Toast.makeText(getApplicationContext(), "Delete  
        successfully!!!",Toast.LENGTH_SHORT).show();
            } catch (Exception e){
                Log.e("error", e.getMessage());
            }
            updateFoodList();
        }
    });

    dialogDelete.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
    dialogDelete.show();
}

private void updateFoodList(){
    // get all data from sqlite
    Cursor cursor = MainActivity.sqLiteHelper.getData("SELECT * FROM FOOD");
    list.clear();
    while (cursor.moveToNext()) {
        int id = cursor.getInt(0);
        String name = cursor.getString(1);
        String price = cursor.getString(2);
        byte[] image = cursor.getBlob(3);

        list.add(new Food(name, price, image, id));
    }
    adapter.notifyDataSetChanged();
}

@Override
    public void onRequestPermissionsResult(int requestCode, 
    @NonNull String[] permissions,  @NonNull    int[] grantResults) {

    if(requestCode == 888){
        if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setType("image/*");
            startActivityForResult(intent, 888);
        }
        else {
            Toast.makeText(getApplicationContext(), "You don't have permission to access file location!", Toast.LENGTH_SHORT).show();
        }
        return;
    }
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
public byte[] imageViewToByte(ImageView image) {
    Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
    byte[] byteArray = stream.toByteArray();
    return byteArray;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if(requestCode == 888 && resultCode == RESULT_OK && data != null){
        Uri uri = data.getData();
        try {
            InputStream inputStream = getContentResolver().openInputStream(uri);
           bitmap = BitmapFactory.decodeStream(inputStream);

            imageViewFood.setImageBitmap(bitmap);



        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    super.onActivityResult(requestCode, resultCode, data);
}

FoodListAdapter HERE:

public class FoodListAdapter extends BaseAdapter {

private Context context;
private  int layout;
private ArrayList<Food> foodsList;

public FoodListAdapter(Context context, int layout, ArrayList<Food> foodsList) {
    this.context = context;
    this.layout = layout;
    this.foodsList = foodsList;
}

@Override
public int getCount() {
    return foodsList.size();
}

@Override
public Object getItem(int position) {
    return foodsList.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

private class ViewHolder{
    ImageView imageView;
    TextView txtName, txtPrice;
}

@Override
public View getView(int position, View view, ViewGroup viewGroup) {

    View row = view;
    ViewHolder holder = new ViewHolder();

    if(row == null){
        LayoutInflater inflater = (LayoutInflater)   
     context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        row = inflater.inflate(layout, null);

        holder.txtName = (TextView) row.findViewById(R.id.txtName);
        holder.txtPrice = (TextView) row.findViewById(R.id.txtPrice);
        holder.imageView = (ImageView) row.findViewById(R.id.imgFood);
        row.setTag(holder);
    }
    else {
        holder = (ViewHolder) row.getTag();
    }

    Food food = foodsList.get(position);

    holder.txtName.setText(food.getName());
    holder.txtPrice.setText(food.getPrice());

    byte[] foodImage = food.getImage();
    Bitmap bitmap = BitmapFactory.decodeByteArray(foodImage, 0, foodImage.length);
    holder.imageView.setImageBitmap(bitmap);

    return row;
 }
 }

standart Food.class

public class Food {
private int id;
private String name;
private String price;
private byte[] image;

public Food(String name, String price, byte[] image, int id) {
    this.name = name;
    this.price = price;
    this.image = image;
    this.id = id;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getPrice() {
    return price;
}

public void setPrice(String price) {
    this.price = price;
}

public byte[] getImage() {
    return image;
}

public void setImage(byte[] image) {
    this.image = image;
}
}

I want the image from Gridview to appear in ImageView when I click on the GridView element.

How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *