101 votes

Comment stocker une image dans une base de données SQLite

Dans mon application, je charge une image depuis la galerie et je veux stocker cette image dans la base de données SQLite. Comment stocker un bitmap dans la base de données? Je convertis le bitmap en une chaîne et je la sauvegarde dans la base de données. Lorsque je la récupère depuis la base de données, je ne parviens pas à assigner cette chaîne à ImageView car c'est une chaîne.

Imageupload12.java:

 public class Imageupload12 extends Activity {
      Button buttonLoadImage;
      ImageView targetImage;
      int i = 0;
      Database database = new Database(this);
      String i1;
      String img;
      @Override
      public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main5);
       buttonLoadImage = (Button) findViewById(R.id.loadimage);
       targetImage = (ImageView) findViewById(R.id.targetimage);

       Bundle b = getIntent().getExtras();
       if (b != null) {
        img = b.getString("image");
        targetImage2.setImageURI("image");
        // j'obtiens une erreur car je ne peux pas assigner une chaîne à ImageView.

       }

       buttonLoadImage.setOnClickListener(new Button.OnClickListener() {

        public void onClick(View arg0) {
         // TODO - implémenter la méthode
         Intent intent = new Intent(Intent.ACTION_PICK,
          android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
         Log.i("photo", "" + intent);
         startActivityForResult(intent, i);
         i = i + 1;
        }
      });

      }

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

       // TODO - implémenter la méthode
       super.onActivityResult(requestCode, resultCode, data);
       switch (requestCode) {

        case 0:
         if (resultCode == RESULT_OK) {
          Uri targetUri = data.getData();
          //             textTargetUri.setText(targetUri.toString());
          Bitmap bitmap;
          try {
           bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(targetUri));
           targetImage.setImageBitmap(bitmap);

           i1 = bitmap.toString();
           Log.i("première image........", "" + i1);
           targetImage.setVisibility(0);

           SQLiteDatabase db = database.getWritableDatabase();
           db.execSQL("INSERT INTO UPLOAD VALUES('" + i1 + "');");

          } catch (FileNotFoundException e) {
           // TODO - implémenter la méthode
           e.printStackTrace();
          }
         }
         break;

       }

      }
     }

Image.class:

 public class Image extends Activity {
     Database database = new Database(this);
     static EfficientAdapter adapter, adapter1;
     static ListView lv1;

     static SQLiteDatabase db;
     static EfficientAdapter adp;
     static Cursor c1;

     static Vector < String > IMAGE = new Vector < String > ();

     @Override
     public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);

      db = database.getReadableDatabase();
      c1 = db.rawQuery("select * from UPLOAD;", null);

      if (c1.moveToFirst()) {

       do {
        IMAGE.add(c1.getString(0).toString());

       } while (c1.moveToNext());

       c1.close();
      }

      lv1 = (ListView) findViewById(R.id.List);

      adapter = new EfficientAdapter(this);

      lv1.setAdapter(adapter);

      ImageView add = (ImageView) findViewById(R.id.imv1a);

      add.setOnClickListener(new OnClickListener() {

       @Override
       public void onClick(View v) {
        // TODO - implémenter la méthode
        IMAGE.clear();

        Intent i = new Intent(Image.this, Imageupload12.class);
        startActivity(i);

       }
      });

     }

     private static class EfficientAdapter extends BaseAdapter {

      //        protected  final Context Context = null;
      protected LayoutInflater mLayoutInflater;
      AlertDialog.Builder aBuilder;
      public EfficientAdapter(Context context) {
       // TODO - implémenter le constructeur
       mLayoutInflater = LayoutInflater.from(context);
      }

      @Override
      public int getCount() {
       // TODO - implémenter la méthode

       return IMAGE.size();
      }

      @Override
      public Object getItem(int position) {
       // TODO - implémenter la méthode
       return position;
      }

      @Override
      public long getItemId(int position) {
       // TODO - implémenter la méthode
       return position;
      }

      @Override
      public View getView(final int position, View convertView, ViewGroup parent) {
       // TODO - implémenter la méthode

       final ViewHolder mVHolder;
       if (convertView == null) {
        convertView = mLayoutInflater.inflate(R.layout.pjtlistdetails, parent, false);

        mVHolder = new ViewHolder();

        mVHolder.t1 = (TextView) convertView.findViewById(R.id.pjtdetails);
        mVHolder.time = (TextView) convertView.findViewById(R.id.name);

        mVHolder.imv = (ImageButton) convertView.findViewById(R.id.editic);
        mVHolder.imvd = (ImageView) convertView.findViewById(R.id.delete);
        mVHolder.imvf = (ImageView) convertView.findViewById(R.id.fwd);

        mVHolder.imv.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {

          String img = IMAGE.elementAt(position);
          Log.i("image...", "" + img);

          Context ctx = v.getContext();
          Intent myIntent = new Intent();
          ctx = v.getContext();
          myIntent.setClass(ctx, Imageupload12.class);
          myIntent.putExtra("image", img);

          ctx.startActivity(myIntent);

          IMAGE.clear();

         }
        });
        static class ViewHolder {

         ImageButton imv;
         ImageView imvd, imvf;
        }
       }
      }
     }
    }

1voto

SHAZAM Points 11

N'oubliez pas d'écrire le code d'autorisation d'utilisateur dans le fichier Manifeste

    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            CameraActivity = this;

            imageView = (ImageView) findViewById(R.id.image_view);
            database = new ImageDatabase(this);

            // Définir un écouteur de clic sur le bouton de capture
            captureImage = (Button) findViewById(R.id.capture_image);
            captureImage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(cameraIntent, CAMERA_REQUEST);
                }
            });

        }

        @Override
        public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
            if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {

                theImage = (Bitmap) data.getExtras().get("data");

                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                theImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
                byte[] byteArray = stream.toByteArray();

                SQLiteDatabase db = database.getWritableDatabase();
                ContentValues values = new ContentValues();
                values.put(ImageDatabase.KEY_IMG_URL, byteArray);
                db.insert(ImageDatabase.TABLE_NAME, null, values);
                db.close();
                Bitmap b = getTheImage();
                imageView.setImageBitmap(b);

            }
        }

       public Bitmap getTheImage(){

            SQLiteDatabase db = database.getReadableDatabase();
            Cursor cursor = (Cursor) db.rawQuery(" SELECT * FROM "+ImageDatabase.TABLE_NAME,null,null);
            if (cursor.moveToFirst()){
                byte[] imgByte =  cursor.getBlob(cursor.getColumnIndex(ImageDatabase.KEY_IMG_URL));
                cursor.close();
                return BitmapFactory.decodeByteArray(imgByte,0,imgByte.length);
            }
           if (cursor != null && !cursor.isClosed()) {
               cursor.close();
           }

           return null;
        }
    }

CLASSE DE LA BASE DE DONNÉES

class ImageDatabase extends SQLiteOpenHelper {
    public Context context;
    public static final String DATABASE_NAME = "dataManager";

    public static final int DATABASE_VERSION = 1;
    public static final String TABLE_NAME = "data";
    public static final String KEY_ID = "id";
    public static final String KEY_IMG_URL = "ImgFavourite";

    public ImageDatabase(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context = context;
        //Toast.makeText(context, "Constructor called", Toast.LENGTH_LONG).show();
    }

    public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "(" + KEY_ID +
            " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_IMG_URL + " BLOB " + ")";
    public static final String DROP_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME + "";

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

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL(DROP_TABLE);
        onCreate(db);
    }

    public void deleteEntry(long row) {
        SQLiteDatabase sqLiteDatabase = getWritableDatabase();
        sqLiteDatabase.delete(TABLE_NAME, KEY_ID + "=" + row, null);
    }

}

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X