Java 如何在android studio中从SQLite检索图像

Java 如何在android studio中从SQLite检索图像,java,android,sqlite,Java,Android,Sqlite,我可以保存4个值​​但我只检索字符串 public class CafeteriaDB extends SQLiteOpenHelper { private static final String NOMBRE_DB = "cafeteria.db"; private static final int VERSION_DB = 1; private static final String TABLA_BEBIDAS = "CREATE TABLE BEBIDAS(NOM

我可以保存4个值​​但我只检索字符串

public class CafeteriaDB extends SQLiteOpenHelper {

    private static final String NOMBRE_DB = "cafeteria.db";
    private static final int VERSION_DB = 1;
    private static final String TABLA_BEBIDAS = "CREATE TABLE BEBIDAS(NOMBRE TEXT, PRECIO TEXT, INFO TEXT, FOTO BLOB)";

    public CafeteriaDB(@Nullable Context context) {
        super(context, NOMBRE_DB, null, VERSION_DB);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(TABLA_BEBIDAS);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS "+ TABLA_BEBIDAS);
        db.execSQL(TABLA_BEBIDAS);
    }

    public void agregarProducto(String nombre, String precio, String info, byte[] foto){
        SQLiteDatabase db=getWritableDatabase();
        if(db!=null){
            if(info.equals("Bebidas")){
                db.execSQL("INSERT INTO BEBIDAS VALUES('"+nombre+"','"+precio+"','"+info+"','"+foto+"')");
                db.close();
            }
        }
    }

    public ArrayList<CarritoVo> mostrarBebidas(){
        SQLiteDatabase db=getReadableDatabase();
        Cursor cursor= db.rawQuery("SELECT * FROM BEBIDAS",null);
        ArrayList<CarritoVo> bebidas=new ArrayList<>();
        if(cursor.moveToFirst()){
            do{
                bebidas.add(new CarritoVo(cursor.getString(0),cursor.getString(1),cursor.getString(2),cursor.getBlob(3)));
            }while(cursor.moveToNext());
        }
        return bebidas;
    }

    public void eliminarProducto(String nombre, String info){
        SQLiteDatabase db=getWritableDatabase();
        if(db != null){
            if(info.equals("Bebidas")){
                db.execSQL("DELETE FROM BEBIDAS WHERE NOMBRE='"+nombre+"'");
                db.close();
            }
        }
    }
}


      Button btnCarrito = (Button)myDialog.findViewById(R.id.btnCarrito);
               btnCarrito.setOnClickListener(new View.OnClickListener() {
                   @Override
                   public void onClick(View v) {
                       try {
                           cafeteriaDB.agregarProducto(
                                   dialogName.getText().toString().trim(),
                                   dialogCantidad.getText().toString().trim(),
                                   dialogInfo.getText().toString().trim(),
                                   imageViewToByte(dialog_foto));
                           Toast.makeText(parent.getContext(),"Producto Añadido Correctamente",Toast.LENGTH_SHORT).show();
                       }
                       catch (Exception e){
                           e.printStackTrace();
                       }
                   }
               });

               myDialog.show();
            }
        });

        return myHolder;

    }

    private static byte[] imageViewToByte(ImageView dialog_foto) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        Bitmap bitmap = ((BitmapDrawable)dialog_foto.getDrawable()).getBitmap();
        bitmap.compress(Bitmap.CompressFormat.PNG,100, stream);
        byte[] byteArray = stream.toByteArray();
        return byteArray;
    }


emphasized text
      @Override
    public void onBindViewHolder(@NonNull ViewHolderCarrito holder, int position) {
       byte[] foto =listaCarrito.get(position).getFoto();
       ByteArrayInputStream fotoStream = new ByteArrayInputStream(foto);
       Bitmap thefoto = BitmapFactory.decodeByteArray(foto,0,foto.length);
       holder.etiFoto.setImageBitmap(thefoto);
        holder.etiNombre.setText(listaCarrito.get(position).getNombre());
        holder.etiPrecio.setText(listaCarrito.get(position).getPrecio());
        holder.etiInfo.setText(listaCarrito.get(position).getInfo());
    }
}
public类自助餐厅扩展SQLiteOpenHelper{
私有静态最终字符串NOMBRE_DB=“cafeteria.DB”;
私有静态最终int版本_DB=1;
私有静态最终字符串TABLA_BEBIDAS=“创建表BEBIDAS(NOMBRE TEXT、PRECIO TEXT、INFO TEXT、FOTO BLOB)”;
公共自助餐厅(@Nullable Context){
super(上下文,NOMBRE_DB,null,VERSION_DB);
}
@凌驾
public void onCreate(SQLiteDatabase db){
db.execSQL(TABLA_BEBIDAS);
}
@凌驾
public void onUpgrade(SQLiteDatabase db,int-oldVersion,int-newVersion){
db.execSQL(“如果存在删除表”+TABLA_BEBIDAS);
db.execSQL(TABLA_BEBIDAS);
}
public void agregarProducto(字符串nombre、字符串precio、字符串info、字节[]foto){
SQLiteDatabase db=getWritableDatabase();
如果(db!=null){
如果(信息等于(“Bebidas”)){
db.execSQL(“插入BEBIDAS值(“+nombre+”、“+precio+”、“+info+”、“+foto+”)”);
db.close();
}
}
}
公共阵列列表mostrarBebidas(){
SQLiteDatabase db=getReadableDatabase();
Cursor Cursor=db.rawQuery(“从BEBIDAS中选择*”,null);
ArrayList bebidas=新的ArrayList();
if(cursor.moveToFirst()){
做{
添加(新的CarritoVo(cursor.getString(0)、cursor.getString(1)、cursor.getString(2)、cursor.getBlob(3));
}while(cursor.moveToNext());
}
返回bebidas;
}
公共无效eliminarProducto(字符串名称、字符串信息){
SQLiteDatabase db=getWritableDatabase();
如果(db!=null){
如果(信息等于(“Bebidas”)){
db.execSQL(“从BEBIDAS中删除,其中NOMBRE='“+NOMBRE+””);
db.close();
}
}
}
}
按钮btnCarrito=(按钮)myDialog.findViewById(R.id.btnCarrito);
btnCarrito.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
试一试{
agregarProducto自助餐厅(
dialogName.getText().toString().trim(),
dialogCantidad.getText().toString().trim(),
dialogInfo.getText().toString().trim(),
imageViewToByte(对话框);
Toast.makeText(parent.getContext(),“Producto Añado Correctamente”,Toast.LENGTH_SHORT.show();
}
捕获(例外e){
e、 printStackTrace();
}
}
});
myDialog.show();
}
});
归还我的持有人;
}
专用静态字节[]imageViewToByte(ImageView对话框){
ByteArrayOutputStream=新建ByteArrayOutputStream();
位图位图=((BitmapDrawable)对话框_foto.getDrawable()).getBitmap();
compress(bitmap.CompressFormat.PNG,100,流);
byte[]byteArray=stream.toByteArray();
乘火车返回;
}
强调文本
@凌驾
public void onBindViewHolder(@NonNull ViewHolderCarrito holder,int位置){
字节[]foto=listaCarrito.get(位置).getFoto();
ByteArrayInputStream fotoStream=新的ByteArrayInputStream(foto);
位图thefoto=BitmapFactory.decodeByteArray(foto,0,foto.length);
holder.etiFoto.setImageBitmap(thefoto);
holder.etiNombre.setText(listaCarrito.get(position.getNombre());
holder.etiPrecio.setText(listaCarrito.get(position.getPrecio());
holder.etiInfo.setText(listaCarrito.get(position.getInfo());
}
}
插入方法:-

public void agregarProducto(String nombre, String precio, String info, byte[] foto){
    SQLiteDatabase db=getWritableDatabase();
    if(db!=null){
        if(info.equals("Bebidas")){
            db.execSQL("INSERT INTO BEBIDAS VALUES('"+nombre+"','"+precio+"','"+info+"','"+foto+"')");
            db.close();
        }
    }
}
不会插入BLOB,它可能会插入字节[]指针的值

必须将BLOB指定为
x'??
,其中问号是数组中字节的十六进制表示形式。e、 g.x'00F1F2F3'

将字节数组转换为合适格式的简单方法是让SQLiteDatabase便利方法代表您进行转换

因此,将上述方法更改为:-

public long agregarProducto(String nombre, String precio, String info, byte[] foto){
    SQLiteDatabase db=getWritableDatabase();
    ContentValues cv = new ContentValues();

    if(db!=null){
        if(info.equals("Bebidas")){
            cv.put("NOMBRE",nombre);
            cv.put("PRECIO",precio);
            cv.put("INFO",info);
            cv.put("FOTO",foto);
            db.insert("BEBIDAS",null,cv);
            db.close();
        }
    }
}
  • 请注意,该方法将返回一个long,如果插入有效,它将大于0,否则它将为-1,表示未插入任何内容
    • 插入方法:-

      public void agregarProducto(String nombre, String precio, String info, byte[] foto){
          SQLiteDatabase db=getWritableDatabase();
          if(db!=null){
              if(info.equals("Bebidas")){
                  db.execSQL("INSERT INTO BEBIDAS VALUES('"+nombre+"','"+precio+"','"+info+"','"+foto+"')");
                  db.close();
              }
          }
      }
      
      不会插入BLOB,它可能会插入字节[]指针的值

      必须将BLOB指定为
      x'??
      ,其中问号是数组中字节的十六进制表示形式。e、 g.x'00F1F2F3'

      将字节数组转换为合适格式的简单方法是让SQLiteDatabase便利方法代表您进行转换

      因此,将上述方法更改为:-

      public long agregarProducto(String nombre, String precio, String info, byte[] foto){
          SQLiteDatabase db=getWritableDatabase();
          ContentValues cv = new ContentValues();
      
          if(db!=null){
              if(info.equals("Bebidas")){
                  cv.put("NOMBRE",nombre);
                  cv.put("PRECIO",precio);
                  cv.put("INFO",info);
                  cv.put("FOTO",foto);
                  db.insert("BEBIDAS",null,cv);
                  db.close();
              }
          }
      }
      
      • 请注意,该方法将返回一个long,如果插入有效,它将大于0,否则它将为-1,表示未插入任何内容