mardi 27 octobre 2015

How to access SQLite Database from another class

I'm need to access the SQLite database that is created in one class from my other activity. I want to access from public void getImage(View view) {but the app crashes when I use it. Here is my activity:

public class CameraToDatabase extends Activity {
    private static final int CAMERA_REQUEST = 1888;
    public ImageView imageView1;
    Imagehelper help = new Imagehelper(this);

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


        Button B = (Button) this.findViewById(R.id.camera);
        B.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                Intent cameraIntent = new Intent(
                        android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(cameraIntent, CAMERA_REQUEST);
            }
        });
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CAMERA_REQUEST) {
            Bitmap photo = (Bitmap) data.getExtras().get("data");
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            photo.compress(Bitmap.CompressFormat.JPEG, 100, stream);
            byte[] byteArray = stream.toByteArray();
            help.insert(byteArray);
        }
    }

    public void getImage(View view) {

        Cursor c = help.getAll();
        if (c.moveToNext())
        {
            byte[] byteArray = c.getBlob(0);
            Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
            imageView1.setImageBitmap(bmp);

        }
        c.close();

    }

And here is where I create the database:

public class Imagehelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "clothes.db";
    private static final int SCHEMA_VERSION = 3;

    public Imagehelper(Context context) {
        super(context, DATABASE_NAME, null, SCHEMA_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL("CREATE TABLE Image(_id INTEGER PRIMARY KEY AUTOINCREMENT,imageblob BLOB);");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    public void insert(byte[] bytes) {
        ContentValues cv = new ContentValues();

        cv.put("imageblob", bytes);
        Log.e("inserted", "inserted");
        getWritableDatabase().insert("Image", "imageblob", cv);

    }

    public Cursor getAll() {
        return (getReadableDatabase().rawQuery("SELECT column1 FROM Image", null));
    }



}

}

Aucun commentaire:

Enregistrer un commentaire