簡體   English   中英

將圖像保存在SQLite數據庫中

[英]Saving image in SQLite database

我正在嘗試創建日記,以便用戶保存一些文本和圖像。 我已經設法保存了文本(標題和正文),但是我是一個初學者,所以我不確定如何保存圖像,有人可以幫忙嗎? 這是我的代碼,我創建了注釋,試圖在代碼中獲取圖像,但是我不知道如何使它起作用

ActivityDiaryEdit.java:

      public class ActivityDiaryEdit extends Activity { 


     private static final int RESULT_LOAD_IMAGE =1;

      private EditText mTitleText;
      private EditText mBodyText;
      private ImageView mImage;    //image
      private Long mRowId;
      private DiaryDbAdapter mDbHelper;

      @Override
      protected void onCreate(Bundle savedInstanceState) {                             
        super.onCreate(savedInstanceState);
        mDbHelper = new DiaryDbAdapter(this);
        mDbHelper.open();
        setContentView(R.layout.diary_edit);

        mTitleText = (EditText) findViewById(R.id.title);                               
        mBodyText = (EditText) findViewById(R.id.body);
        mImage = (ImageView) findViewById(R.id.imageView1);  //image



        Button confirmButton = (Button) findViewById(R.id.confirm);                       

        mRowId = null;
        Bundle extras = getIntent().getExtras();                                             
        if (extras != null) {
          String title = extras.getString(DiaryDbAdapter.KEY_TITLE);                           
          String body = extras.getString(DiaryDbAdapter.KEY_BODY);

          mRowId = extras.getLong(DiaryDbAdapter.KEY_ROWID);

          if (title != null) {                                                                  
            mTitleText.setText(title);
          }
          if (body != null) {
            mBodyText.setText(body);
          }
        }

        confirmButton.setOnClickListener(new View.OnClickListener() {                         
          public void onClick(View view) {
            String title = mTitleText.getText().toString();
            String body = mBodyText.getText().toString();

            Bitmap image =((BitmapDrawable)mImage.getDrawable()).getBitmap();    //image
            if (mRowId != null) {
              mDbHelper.updateDiary(mRowId, title, body , image); //add image?
            } else
              mDbHelper.createDiary(title, body , image);
            Intent mIntent = new Intent();
            setResult(RESULT_OK, mIntent);
            finish();
          }

        });
      } 


        public void onClick(View v){           

        switch(v.getId()) {

        case R.id.imageView1:                     //when the imageup is clicked the following will happen

            Intent galleryIntent = new Intent (Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(galleryIntent,RESULT_LOAD_IMAGE);

            break;

        case R.id.confirm:

            Bitmap image =((BitmapDrawable)mImage.getDrawable()).getBitmap();  //holds the image

            break;

        }


        }

        @Override
        protected void onActivityResult(int  requestCode , int resultCode, Intent data){
            super.onActivityResult(requestCode, resultCode, data);
            if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && data !=null){


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

                mImage.setImageBitmap(bmp);
                mImage.requestFocus();

                ByteArrayOutputStream boas = new ByteArrayOutputStream();
                bmp.compress(Bitmap.CompressFormat.JPEG, 100, boas);
                byte [] b =boas.toByteArray();
                String encodedImageString = Base64.encodeToString(b, Base64.DEFAULT);

                byte[] bytarray= Base64.decode(encodedImageString, Base64.DEFAULT);
                Bitmap bmimage = BitmapFactory.decodeByteArray(bytarray, 0,
                        bytarray.length);

                Uri selectedImage =data.getData();
                mImage.setImageURI(selectedImage);

            }
        }

        private class UploadImage extends AsyncTask<Void,Void ,Void >{     

            Bitmap image;
            String name;


            public UploadImage(Bitmap image,String name){                   

                this.image = image;
                this.name = name;

            }

        @Override
            protected Void doInBackground(Void... params) {               
                // TODO Auto-generated method stub

                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                image.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
                String encodedImage = Base64.encodeToString(byteArrayOutputStream.toByteArray(),Base64.DEFAULT);   //encoding the image-String representation of the image



                ArrayList<NameValuePair>dataToSend = new ArrayList<>();
                dataToSend.add(new BasicNameValuePair("image", encodedImage));
                dataToSend.add(new BasicNameValuePair("name",name));

                return null;
            }


      }

DiaryDbAdapter.java:

  class DiaryDbAdapter {

   public static final String KEY_TITLE = "title";
   public static final String KEY_BODY = "body";
    public static final String KEY_ROWID = "_id";
    public static final String KEY_CREATED = "created";
    public static final String KEY_IMAGE = "image";  //image
     private static final String TABLE_CONTACTS = "contacts";  

         private static final String TAG = "DiaryDbAdapter";
     private DatabaseHelper mDbHelper;                                             
     private SQLiteDatabase mDb;                                                      

  private static final String DATABASE_CREATE = "create table diary (_id   integer primary key autoincrement, "
  + "title text not null, body text not null, created text not null);";                                         

   private static final String DATABASE_NAME = "database";
    private static final String DATABASE_TABLE = "diary";
    private static final int DATABASE_VERSION = 1;

  private final Context mCtx;

   private static class DatabaseHelper extends SQLiteOpenHelper {

    DatabaseHelper(Context context) {
     super(context, DATABASE_NAME, null, DATABASE_VERSION);                           
    }

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

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

 public DiaryDbAdapter(Context ctx) {
  this.mCtx = ctx;                                                                         
  }

 public DiaryDbAdapter open() throws SQLException {                                         
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}

 public void closeclose() {
 mDbHelper.close();
 }



  public void onCreate(SQLiteDatabase db) {
    String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
            + KEY_IMAGE + " BLOB" + ")";
    db.execSQL(CREATE_CONTACTS_TABLE);
   }   //for image



 public long createDiary(String title, String body , Bitmap image) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_TITLE, title);
initialValues.put(KEY_BODY, body);
//  initialValues.put(KEY_IMAGE, image);   //how to put image?
Calendar calendar = Calendar.getInstance();                                              
String created = calendar.get(Calendar.YEAR) + ""
    + calendar.get(Calendar.MONTH) + ""
    + calendar.get(Calendar.DAY_OF_MONTH) + ""                                         
    + calendar.get(Calendar.HOUR_OF_DAY) + ""
    + calendar.get(Calendar.MINUTE) + "";
initialValues.put(KEY_CREATED, created);
return mDb.insert(DATABASE_TABLE, null, initialValues);
}

  public boolean deleteDiary(long rowId) {                                                  

return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
 }

  public Cursor getAllNotes() {

  return mDb.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_TITLE,                
    KEY_BODY, KEY_CREATED ,KEY_IMAGE}, null, null, null, null, null);
  }

     public Cursor getDiary(long rowId) throws SQLException {                              

  Cursor mCursor =

    mDb.query(true, DATABASE_TABLE, new String[] { KEY_ROWID, KEY_TITLE,
    KEY_BODY, KEY_CREATED , KEY_IMAGE }, KEY_ROWID + "=" + rowId, null,    null,
    null, null, null);
   if (mCursor != null) {
   mCursor.moveToFirst();
 }
   return mCursor;

 }

   public boolean updateDiary(long rowId, String title, String body , Bitmap image) {                         
  ContentValues args = new ContentValues();
  args.put(KEY_TITLE, title);
  args.put(KEY_BODY, body);
   //args.put(KEY_IMAGE, image);   //how to put image?
Calendar calendar = Calendar.getInstance();
String created = calendar.get(Calendar.YEAR) + ""
    + calendar.get(Calendar.MONTH) + ""
    + calendar.get(Calendar.DAY_OF_MONTH) + ""
    + calendar.get(Calendar.HOUR_OF_DAY) + ""
    + calendar.get(Calendar.MINUTE) + "";
args.put(KEY_CREATED, created);

return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
}
}

MainActivity.java:

   public class MainActivity extends ListActivity {
  private static final int ACTIVITY_CREATE = 0;
  private static final int ACTIVITY_EDIT = 1;

  private static final int INSERT_ID = Menu.FIRST;
  private static final int DELETE_ID = Menu.FIRST + 1;

  private DiaryDbAdapter mDbHelper;                               
  private Cursor mDiaryCursor;                                   

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.diary_list);                        
    mDbHelper = new DiaryDbAdapter(this);                           
    mDbHelper.open();
    renderListView();                                                

  }

  private void renderListView() {                                      
    mDiaryCursor = mDbHelper.getAllNotes();
    startManagingCursor(mDiaryCursor);
    String[] from = new String[] { DiaryDbAdapter.KEY_TITLE,               
        DiaryDbAdapter.KEY_CREATED ,  };                                    //DiaryAdapter KEY_IMAGE ?? 
    int[] to = new int[] { R.id.text1, R.id.created , R.id.imageView1  };
    SimpleCursorAdapter notes = new SimpleCursorAdapter(this,
        R.layout.diary_now, mDiaryCursor, from, to);
    setListAdapter(notes);
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {                         
    super.onCreateOptionsMenu(menu);
    menu.add(0, INSERT_ID, 0, R.string.menu_insert);                      
    menu.add(0, DELETE_ID, 0, R.string.menu_delete);
   return true;
 }

  @Override
  public boolean onMenuItemSelected(int featureId, MenuItem item) {     
    switch (item.getItemId()) {
    case INSERT_ID:
      createDiary();
      return true;
    case DELETE_ID:
      mDbHelper.deleteDiary(getListView().getSelectedItemId());
      renderListView();
      return true;
    }
    return super.onMenuItemSelected(featureId, item);
  }

  private void createDiary() {                                            
    Intent i = new Intent(this, ActivityDiaryEdit.class);
    startActivityForResult(i, ACTIVITY_CREATE);
  }

  @Override

  protected void onListItemClick(ListView l, View v, int position, long id) {      // from activity edit and diaryDb
    super.onListItemClick(l, v, position, id);
    Cursor c = mDiaryCursor;
    c.moveToPosition(position);
    Intent i = new Intent(this, ActivityDiaryEdit.class);
    i.putExtra(DiaryDbAdapter.KEY_ROWID, id);
    i.putExtra(DiaryDbAdapter.KEY_TITLE, c.getString(c
        .getColumnIndexOrThrow(DiaryDbAdapter.KEY_TITLE)));
    i.putExtra(DiaryDbAdapter.KEY_BODY, c.getString(c
        .getColumnIndexOrThrow(DiaryDbAdapter.KEY_BODY)));
    startActivityForResult(i, ACTIVITY_EDIT);
 // i.putExtra(DiaryAdapter.KEY_IMAGE, c.getString(c
       //     .getColumnIndexOrThrow(DiaryAdapter.KEY_IMAGE))); image??
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode,                     
      Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
    renderListView();
  }
}

要將圖像存儲在Sqlite中,請使用Blob(二進制大對象)

從壓縮為PNG的位圖中檢索字節數組:

public static byte[] getBytes(Bitmap bitmap) {
    ByteArrayOutputStream stream=new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG,100, stream);
    return stream.toByteArray();
}

在SqlStatement上,使用bindBlob插入圖像。 有關此的更多信息

為了進行檢索,請使用cursor.getBlob(index)並將blob解碼為Bitmap

public static Bitmap getImage(byte[] image)
{
    return BitmapFactory.decodeByteArray(image, 0, image.length);
}

如果會建議將圖像保存為文件而不是使用Sqlite。 Android開發人員對此有很好的文章

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM