如何在SQLite数据库中保存相机中的图片并在另一个活动中检索它们?

时间:2015-05-13 14:51:54

标签: android database sqlite camera

我正在构建我的应用程序,现在我想创建一个SQLite数据库,用于存储从相机拍摄的图片以及用户在EditText中插入的相关文本;然后在ListView中检索它们应该是有点画廊,用户可以轻松访问他们的照片。 这是我的数据库助手类:

public class MySQLiteHelper3 extends SQLiteOpenHelper {
public static final String TABLE_IMAGE = "images";

public static final String COLUMN_ID4 = " id4";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_IMAGE = "image";
public static final String DATABASE_TABLE = "Gallery";
public static final int DATABASE_VERSION = 2;
public static final String DATABASE_NAME = "Gallery";
public static final String DATABASE_CREATE4="CREATE TABLE " + TABLE_IMAGE + "("
        + COLUMN_ID4 + " INTEGER PRIMARY KEY," + COLUMN_NAME + " TEXT,"
        + COLUMN_IMAGE + " BLOB" + ")";
public MySQLiteHelper3(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

public void onCreate(SQLiteDatabase database) {
    database.execSQL(DATABASE_CREATE4);
}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    Log.w(MySQLiteHelper3.class.getName(),
            "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
    db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
    onCreate(db);
}

}

以下代码是我的数据库构造函数:

public class ImageDataSource {
private SQLiteDatabase data;
private MySQLiteHelper3 dbhelp;
private String[] allColumnsi = {MySQLiteHelper3.COLUMN_ID4, MySQLiteHelper3.COLUMN_NAME, MySQLiteHelper3.COLUMN_IMAGE};

public ImageDataSource(Context context) {
    dbhelp = new MySQLiteHelper3(context);
}

public void opendata() throws SQLException {
    data = dbhelp.getWritableDatabase();
}

public void closedata() {
    dbhelp.close();
}

public Image createImage(String nome, byte [] ima) {
    ContentValues valo = new ContentValues();
    valo.put(MySQLiteHelper3.COLUMN_NAME, nome);
    long InsertID = data.insert(MySQLiteHelper3.TABLE_IMAGE, null, valo);
    Cursor cursor = data.query(MySQLiteHelper3.TABLE_IMAGE, allColumnsi, MySQLiteHelper3.COLUMN_ID4 + " = " + InsertID, null,
            null, null, null);
    cursor.moveToFirst();
    Image image = cursorToImage(cursor);
    cursor.close();
    return image;
}

public void deleteImage(Image image) {
    long id = image.getID();
    System.out.println("Comment deleted with id: " + id);
    data.delete(MySQLiteHelper3.TABLE_IMAGE, MySQLiteHelper3.COLUMN_ID4
            + " = " + id, null);
}

public void updateImage(Image image) {
    long id = image.getID();
    ContentValues values = new ContentValues();
    values.put(MySQLiteHelper3.COLUMN_NAME, "0");
    data.update(MySQLiteHelper3.TABLE_IMAGE, values, MySQLiteHelper3.COLUMN_ID4 + " = " + id, null);
}

public ArrayList<Map<String, Object>> getAllImages() {
    ArrayList<Map<String, Object>> image = new ArrayList<Map<String, Object>>();
    Cursor cursor = data.query(MySQLiteHelper3.TABLE_IMAGE, allColumnsi, null, null, null, null, null, null);
    if (cursor.getCount() > 0) {
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            Image image1 = cursorToImage(cursor);
            image.add(putData("Item Name :" + image1.getName().toString() + " Image : " + image1.getImage(),image1.getImage()));
            cursor.moveToNext();
        }
    }
    // make sure to close the cursor
    cursor.close();
    return image;
}

private HashMap<String, Object> putData(String nome, byte[] image) {
    HashMap<String, Object> item = new HashMap<String, Object>();
    item.put("NOME", nome);
    item.put("IMMAGINE'", image);
    return item;
}

private Image cursorToImage(Cursor cursor) {
    Image image = new Image();
    image.setID(cursor.getLong(0));
    image.setImage(cursor.getBlob(1));
    return image;
}
}

这是我的类来定义我的对象:

public class Image {
// private variables
private long id3;
private String name;
private byte[] image;

public Image(long id3, String name, byte[] image) {
    this.id3 = id3;
    this.name = name;
    this.image = image;

}

public long getID() {
    return id3;
}

public void setID(long id3) {
    this.id3 = id3;
}

public String getName() {
    return this.name;
}

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

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


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

}

这是我的主要课程,我有一个按钮来访问摄像头和EditText以及另一个数据库,只需照顾相机操作!

public class AddProductNoEan extends ActionBarActivity {

EditText quantita;
private TextView today;
private String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
FloatingActionButton actionButton;
private EditText prodo;
private EditText amou;
private ImageView imageView;
private Prodotto_noEanDataSource db;
FloatingActionButton B;
private static final int CAMERA_REQUEST = 1888;
private ImageDataSource ihellp;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_product_no_ean);
    today=(TextView)findViewById(R.id.currentt);
    today.setText(currentDateTimeString);
    prodo=(EditText)findViewById(R.id.addpro);
    amou=(EditText)findViewById(R.id.amount);
    db = new Prodotto_noEanDataSource(this);
    db.openDb();
    ihellp=new ImageDataSource(this);
    ihellp.opendata();
    final Context context = getApplicationContext();
    ImageView icon = new ImageView(this); // Create an icon
    icon.setImageResource(R.drawable.ic_action_save);
    actionButton = new FloatingActionButton.Builder(this)
            .setContentView(icon)
            .setPosition(4)
            .build();
    actionButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            String prod = prodo.getText().toString();
            String much = amou.getText().toString();
            String data_finale = today.getText().toString();
            @SuppressWarnings("unchecked")
            String[] prodotto_noEanx = new String[]{prod, much, data_finale};
            db.createProdotto_noEan(prodotto_noEanx[0], prodotto_noEanx[1], prodotto_noEanx[2]);
            CharSequence text = getString(R.string.save_message);
            int duration = Toast.LENGTH_SHORT;
            Toast toast = Toast.makeText(context, text, duration);
            toast.show();
            finish();
            startActivity(getIntent());
        }
    });
    this.imageView = (ImageView)this.findViewById(R.id.imageView1);
    ImageView icon1 = new ImageView(this); // Create an icon
    icon1.setImageResource(R.drawable.ic_action_camera);
    B = new FloatingActionButton.Builder(this)
            .setContentView(icon1)
            .setPosition(6)
            .build();
    B.setOnClickListener(new View.OnClickListener()
   {
        public void onClick(View v) {
            Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(cameraIntent, CAMERA_REQUEST);
        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_add_product_no_ean, menu);
    return true;
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == CAMERA_REQUEST) {
        Bitmap photo = (Bitmap) data.getExtras().get("data");
        imageView.setImageBitmap(photo);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
        byte[] byteArray = stream.toByteArray();
        ihellp.createImage("",byteArray);
    }
}

        @Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        Intent note=new Intent(AddProductNoEan.this,Notes.class);
        startActivity(note);
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

最后我的画廊课程:

public class Gallery extends ActionBarActivity  {
private ListView images;
private ImageDataSource imagehelper;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_gallery);
    images=(ListView)findViewById(R.id.gale);
    imagehelper=new ImageDataSource(this);
    imagehelper.opendata();
    ArrayList<Map<String,Object>> values=imagehelper.getAllImages();
    String [] from ={"IMMAGINE","DESCRIZIONE"};
    int[] to = {android.R.id.text1,android.R.id.text2};
    SimpleAdapter adapter = new SimpleAdapter(this,values,android.R.layout.simple_expandable_list_item_2,from,to);
    images.setAdapter(adapter);



}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_gallery, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}


}

我已经使用过SQLite数据库,但这是我第一次使用Objects而不是Strings.Thanks提前获取任何提示或建议!

0 个答案:

没有答案