简体   繁体   中英

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));
    }



}

}

Your table 'Image' has no column 'column1'. It has '_id' and 'imageblob', as you can see in the onCreate method. So the 'getAll' method can never work, as it executes 'SELECT column1 FROM Image'!

It would be helpful to see the error mesage / stack trace of the crash you are talking about.

Place

new Imagehelper(this)

after oncreate.

Your on create should like this:

private static final int CAMERA_REQUEST = 1888;
    public ImageView imageView1;
    Imagehelper help ;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera_to_database);
        help = new Imagehelper(this);

        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);
            }
        });
    }

Now your Mainactivity ShouldLike That:

package com.solution.sa.stack_camerasql;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import java.io.ByteArrayOutputStream;

public class MainActivity extends AppCompatActivity {

    private static final int CAMERA_REQUEST = 1888;
    public ImageView imageView1;
    Imagehelper help ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        help = new Imagehelper(this);
        imageView1= (ImageView) this.findViewById(R.id.myimg);
        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);
            getImage();
        }
    }

    public void getImage() {

        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 your Imgaehelper Class like that :

package com.solution.sa.stack_camerasql;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * Created by asim on 10/27/2015.
 */
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  imageblob FROM Image", null));
    }



}

Now you have only manage to show only last captured image instead of loop on all images

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM