我编写了将数据插入SQLite
数据库的代码,当时我在返回行nullpointer
db.insert("userdetails", null, initialValues);
异常
public class DBUserAdapter {
private static final String DATABASE_NAME = "users";
private static final int DATABASE_VERSION = 1;
private static final String USERDETAILS=
"create table userdetails(usersno integer primary key autoincrement,photo BLOB,date text not null);";
private Context context = null;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
// public DBUserAdapter(Context ctx) {
// this.context = ctx;
// DBHelper = new DatabaseHelper(context);
// }
public DBUserAdapter(SampleViewBase sampleViewBase) {
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(USERDETAILS);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS users");
onCreate(db);
}
}
public void open() throws SQLException
{
db = DBHelper.getWritableDatabase();
}
public void close()
{
DBHelper.close();
}
public long insert(byte[] photo, String date)
{
ContentValues initialValues = new ContentValues();
initialValues.put("photo", photo);
initialValues.put("date", date);
// initialValues.put(KEY_TIME, time);
Log.d("inotvaluessssssssss",initialValues.toString());
return db.insert("userdetails", null, initialValues);
}
我的主要活动
public abstract class SampleViewBase extends SurfaceView implements SurfaceHolder.Callback, Runnable {
private static final String TAG = "Sample-ImageManipulations::SurfaceView";
DBUserAdapter dbUser= null ;
private SurfaceHolder mHolder;
private VideoCapture mCamera;
byte[] photo;
// Mat mRgba;
Mat mRgba = new Mat();
Mat mRgba1= new Mat();
// private FpsMeter mFps;
int[] intArray = new int[50];
// int[] y;
// int check=0;
int cod=0;
public SampleViewBase(Context context) {
super(context);
mHolder = getHolder();
mHolder.addCallback(this);
// mFps = new FpsMeter();
Log.i(TAG, "Instantiated new " + this.getClass());
}
public boolean openCamera() {
Log.i(TAG, "openCamera");
synchronized (this) {
releaseCamera();
mCamera = new VideoCapture(Highgui.CV_CAP_ANDROID);
if (!mCamera.isOpened()) {
mCamera.release();
mCamera = null;
Log.e(TAG, "Failed to open native camera");
return false;
}
}
return true;
}
public void releaseCamera() {
Log.i(TAG, "releaseCamera");
synchronized (this) {
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
}
}
public void setupCamera(int width, int height) {
Log.i(TAG, "setupCamera("+width+", "+height+")");
synchronized (this) {
if (mCamera != null && mCamera.isOpened()) {
List<Size> sizes = mCamera.getSupportedPreviewSizes();
int mFrameWidth = width;
int mFrameHeight = height;
// selecting optimal camera preview size
{
double minDiff = Double.MAX_VALUE;
for (Size size : sizes) {
if (Math.abs(size.height - height) < minDiff) {
mFrameWidth = (int) size.width;
mFrameHeight = (int) size.height;
minDiff = Math.abs(size.height - height);
}
}
}
mCamera.set(Highgui.CV_CAP_PROP_FRAME_WIDTH, mFrameWidth);
mCamera.set(Highgui.CV_CAP_PROP_FRAME_HEIGHT, mFrameHeight);
}
}
}
public void surfaceChanged(SurfaceHolder _holder, int format, int width, int height) {
Log.i(TAG, "surfaceChanged");
setupCamera(width, height);
}
public void surfaceCreated(SurfaceHolder holder) {
Log.i(TAG, "surfaceCreated");
(new Thread(this)).start();
}
public void surfaceDestroyed(SurfaceHolder holder) {
Log.i(TAG, "surfaceDestroyed");
releaseCamera();
}
protected abstract Bitmap processFrame(VideoCapture capture);
public void run() {
Log.i(TAG, "Starting processing thread");
//mFps.init();
while (true) {
Bitmap bmp = null;
synchronized (this) {
if (mCamera == null) {
Log.i(TAG, "mCamera == null");
break;
}
if (!mCamera.grab()) {
Log.e(TAG, "mCamera.grab() failed");
break;
}
bmp = processFrame(mCamera);
String i1=bmp.toString();
dbUser = new DBUserAdapter(SampleViewBase.this);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateTime = sdf.format(Calendar.getInstance().getTime()); // reading local time in the system
// mRgba= (Mat)processFrame(mCamera);
ByteArrayOutputStream blob = new ByteArrayOutputStream();
bmp.compress(CompressFormat.PNG, 100 /*ignored for PNG*/, blob);
photo = blob.toByteArray();
dbUser.insert(photo, dateTime);
Log.d("bitmapdataaaaaaaaaaaaaaaaaaaaaaa",""+photo);
Bitmap bmp32 = bmp.copy(Bitmap.Config.ARGB_8888, true);
Utils.bitmapToMat(bmp32,mRgba);
Utils.bitmapToMat(bmp32,mRgba1);
// Log.d("lengthhhhhhhhhhhh",""+bitmapdata.length);
// for(int k=0;k<bitmapdata.length;k++)
// {
//
// }
bmp = processFrame(mCamera);
int i= bmp.getWidth();
int j=bmp.getHeight();
Log.d("Coming outoutttttttttttt ","Coming outputtttttttt");
intArray=FindFeatures(mRgba1.getNativeObjAddr(),mRgba.getNativeObjAddr());
Log.d("valueeeeeeeeee",""+intArray[0]);
Log.d("valueeeeeeeeee",""+intArray[1]);
Log.d("valueeeeeeeeee",""+intArray[2]);
Log.d("valueeeeeeeeee",""+intArray[3]);
Log.d("valueeeeeeeeee",""+intArray[3]);
// Log.d("Coming outo-----------------------==========","hjhjhj");
// mRgba=(Mat)bitmapdata;
// mFps.measure();
// Utils.matToBitmap(mRgba, bmp);
}
if (bmp != null)
{
Canvas canvas = mHolder.lockCanvas();
if (canvas != null)
{
//Log.d("Coming outo---454545--------------------==========","hjhjhj");
canvas.drawBitmap(bmp, (canvas.getWidth() - bmp.getWidth()) / 2, (canvas.getHeight() - bmp.getHeight()), null);
// mFps.draw(canvas, (canvas.getWidth() - bmp.getWidth()) / 2, 0);
mHolder.unlockCanvasAndPost(canvas);
}
bmp.recycle();
}
//FindFeatures(bitmapdata,j,i);
}
Log.i(TAG, "Finishing processing thread");
}
// public native void FindFeatures(final byte[] bitmapdata,long m,int height,int width);
public native int[] FindFeatures(long n,long m);
static {
// Log.d("Coming hereeeeeee","Coming hereeeeeeeeeeeeee");
System.loadLibrary("mixed_sample");
}
public class Demo
{
int[] x;
int[] y;
int check=0;
int cod=0;
}
}
答案 0 :(得分:0)
在mainactivity中,在调用insert之前执行此修改,并在插入完成后执行dbUser.close()。
这是修改:
dbUser = new DBUserAdapter(SampleViewBase.this);
dbUser.open(); // <<<<<<<<<<<<<<<<<< look at this modification too
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateTime = sdf.format(Calendar.getInstance().getTime()); // reading local time in the system
// mRgba= (Mat)processFrame(mCamera);
ByteArrayOutputStream blob = new ByteArrayOutputStream();
bmp.compress(CompressFormat.PNG, 100 /*ignored for PNG*/, blob);
photo = blob.toByteArray();
dbUser.insert(photo, dateTime);
dbUser.close(); // <<<<<<<<<<<<<<<<<< look at this modification too
Log.d("bitmapdataaaaaaaaaaaaaaaaaaaaaaa",""+photo);
Bitmap bmp32 = bmp.copy(Bitmap.Config.ARGB_8888, true);
这是带有修改的MainActivity代码:
public abstract class SampleViewBase extends SurfaceView implements SurfaceHolder.Callback, Runnable {
private static final String TAG = "Sample-ImageManipulations::SurfaceView";
DBUserAdapter dbUser= null ;
private SurfaceHolder mHolder;
private VideoCapture mCamera;
private Context mContext;
byte[] photo;
// Mat mRgba;
Mat mRgba = new Mat();
Mat mRgba1= new Mat();
// private FpsMeter mFps;
int[] intArray = new int[50];
// int[] y;
// int check=0;
int cod=0;
public SampleViewBase(Context context) {
super(context);
this.mContext = context;
mHolder = getHolder();
mHolder.addCallback(this);
// mFps = new FpsMeter();
Log.i(TAG, "Instantiated new " + this.getClass());
}
public boolean openCamera() {
Log.i(TAG, "openCamera");
synchronized (this) {
releaseCamera();
mCamera = new VideoCapture(Highgui.CV_CAP_ANDROID);
if (!mCamera.isOpened()) {
mCamera.release();
mCamera = null;
Log.e(TAG, "Failed to open native camera");
return false;
}
}
return true;
}
public void releaseCamera() {
Log.i(TAG, "releaseCamera");
synchronized (this) {
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
}
}
public void setupCamera(int width, int height) {
Log.i(TAG, "setupCamera("+width+", "+height+")");
synchronized (this) {
if (mCamera != null && mCamera.isOpened()) {
List<Size> sizes = mCamera.getSupportedPreviewSizes();
int mFrameWidth = width;
int mFrameHeight = height;
// selecting optimal camera preview size
{
double minDiff = Double.MAX_VALUE;
for (Size size : sizes) {
if (Math.abs(size.height - height) < minDiff) {
mFrameWidth = (int) size.width;
mFrameHeight = (int) size.height;
minDiff = Math.abs(size.height - height);
}
}
}
mCamera.set(Highgui.CV_CAP_PROP_FRAME_WIDTH, mFrameWidth);
mCamera.set(Highgui.CV_CAP_PROP_FRAME_HEIGHT, mFrameHeight);
}
}
}
public void surfaceChanged(SurfaceHolder _holder, int format, int width, int height) {
Log.i(TAG, "surfaceChanged");
setupCamera(width, height);
}
public void surfaceCreated(SurfaceHolder holder) {
Log.i(TAG, "surfaceCreated");
(new Thread(this)).start();
}
public void surfaceDestroyed(SurfaceHolder holder) {
Log.i(TAG, "surfaceDestroyed");
releaseCamera();
}
protected abstract Bitmap processFrame(VideoCapture capture);
public void run() {
Log.i(TAG, "Starting processing thread");
//mFps.init();
while (true) {
Bitmap bmp = null;
synchronized (this) {
if (mCamera == null) {
Log.i(TAG, "mCamera == null");
break;
}
if (!mCamera.grab()) {
Log.e(TAG, "mCamera.grab() failed");
break;
}
bmp = processFrame(mCamera);
String i1=bmp.toString();
dbUser = new DBUserAdapter(mContext);
dbUser.open(); // <<<<<<<<<<<<<<<<<< look at this modification too
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateTime = sdf.format(Calendar.getInstance().getTime()); // reading local time in the system
// mRgba= (Mat)processFrame(mCamera);
ByteArrayOutputStream blob = new ByteArrayOutputStream();
bmp.compress(CompressFormat.PNG, 100 /*ignored for PNG*/, blob);
photo = blob.toByteArray();
dbUser.insert(photo, dateTime);
dbUser.close(); // <<<<<<<<<<<<<<<<<< look at this modification too
Log.d("bitmapdataaaaaaaaaaaaaaaaaaaaaaa",""+photo);
Bitmap bmp32 = bmp.copy(Bitmap.Config.ARGB_8888, true);
Utils.bitmapToMat(bmp32,mRgba);
Utils.bitmapToMat(bmp32,mRgba1);
// Log.d("lengthhhhhhhhhhhh",""+bitmapdata.length);
// for(int k=0;k<bitmapdata.length;k++)
// {
//
// }
bmp = processFrame(mCamera);
int i= bmp.getWidth();
int j=bmp.getHeight();
Log.d("Coming outoutttttttttttt ","Coming outputtttttttt");
intArray=FindFeatures(mRgba1.getNativeObjAddr(),mRgba.getNativeObjAddr());
Log.d("valueeeeeeeeee",""+intArray[0]);
Log.d("valueeeeeeeeee",""+intArray[1]);
Log.d("valueeeeeeeeee",""+intArray[2]);
Log.d("valueeeeeeeeee",""+intArray[3]);
Log.d("valueeeeeeeeee",""+intArray[3]);
// Log.d("Coming outo-----------------------==========","hjhjhj");
// mRgba=(Mat)bitmapdata;
// mFps.measure();
// Utils.matToBitmap(mRgba, bmp);
}
if (bmp != null)
{
Canvas canvas = mHolder.lockCanvas();
if (canvas != null)
{
//Log.d("Coming outo---454545--------------------==========","hjhjhj");
canvas.drawBitmap(bmp, (canvas.getWidth() - bmp.getWidth()) / 2, (canvas.getHeight() - bmp.getHeight()), null);
// mFps.draw(canvas, (canvas.getWidth() - bmp.getWidth()) / 2, 0);
mHolder.unlockCanvasAndPost(canvas);
}
bmp.recycle();
}
//FindFeatures(bitmapdata,j,i);
}
Log.i(TAG, "Finishing processing thread");
}
// public native void FindFeatures(final byte[] bitmapdata,long m,int height,int width);
public native int[] FindFeatures(long n,long m);
static {
// Log.d("Coming hereeeeeee","Coming hereeeeeeeeeeeeee");
System.loadLibrary("mixed_sample");
}
public class Demo
{
int[] x;
int[] y;
int check=0;
int cod=0;
}
}
修改DBUserAdapter构造函数:
public DBUserAdapter(Context context) {
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
答案 1 :(得分:0)
DBHelper类用于在数据库上执行操作(创建表,插入数据,更新数据,删除数据,读取数据)。
使用以下代码创建DBHelper类。
1.使用以下类,如果数据库可用,则必须创建数据库和表,然后不要覆盖数据库,如果数据库可用且表没有,则在数据库中创建新表。
首先你必须定义.....
private SQLiteDatabase db;
private final String DB_NAME = "Database_name";
private final int DB_VERSION = 1;
private final String TABLE_NAME = "Table_name";
private final String TABLE_ROW_ID = "id";
private final String TABLE_ROW_ONE = "name";
private final String TABLE_ROW_TWO = "basic_price";
private final String TABLE_ROW_THREE = "tax";
private final String TABLE_ROW_FOUR = "shipping";
private final String TABLE_ROW_FIVE = "price";
private final String TABLE_ROW_SIX = "image";
定义变量后,必须在DBHelper类中定义以下类。
private class CustomSQLiteOpenHelper extends SQLiteOpenHelper
{
public CustomSQLiteOpenHelper(Context context)
{
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db)
{
String newTableQueryString = "create table " +
TABLE_NAME +
" (" +
TABLE_ROW_ID + " integer primary key autoincrement not null," +
TABLE_ROW_ONE + " text," +
TABLE_ROW_TWO + " real," +
TABLE_ROW_THREE + " real," +
TABLE_ROW_FOUR + " real," +
TABLE_ROW_FIVE + " real," +
TABLE_ROW_SIX + " blob" +
");";
db.execSQL(newTableQueryString);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
}
}
}
2.为DBHelper类创建构造函数。
public DBHelper(Context context)
{
this.context = context;
CustomSQLiteOpenHelper helper = new CustomSQLiteOpenHelper(context);
this.db = helper.getWritableDatabase();
}
3.创建以下方法将数据插入数据库。
public void insert_Row(String name, float basic_price, float tax, float shipping,float price,Bitmap image)
{
byte[] data = getBitmapAsByteArray(image);
ContentValues values = new ContentValues();
values.put(TABLE_ROW_ONE, name);
values.put(TABLE_ROW_TWO, basic_price);
values.put(TABLE_ROW_THREE, tax);
values.put(TABLE_ROW_FOUR, shipping);
values.put(TABLE_ROW_FIVE, price);
values.put(TABLE_ROW_SIX, data);
try
{
db.insert(TABLE_NAME, null, values);
Log.w("message","Insert successfully");
}
catch(Exception e)
{
Log.e("DB ERROR", e.toString());
//e.printStackTrace();
}
}
4.创建以下方法将数据更新到数据库中。
public void updateRow(long rowID,String name,float basic_price, float tax, float shipping,float price,Bitmap image)
{
byte[] data = getBitmapAsByteArray(image);
ContentValues values = new ContentValues();
values.put(TABLE_ROW_ONE, name);
values.put(TABLE_ROW_TWO, basic_price);
values.put(TABLE_ROW_THREE, tax);
values.put(TABLE_ROW_FOUR, shipping);
values.put(TABLE_ROW_FIVE, price);
values.put(TABLE_ROW_SIX, data);
try
{
db.update(TABLE_NAME, values, TABLE_ROW_ID + "=" + rowID, null);
Log.w("message","Update successfully";
}
catch (Exception e)
{
Log.e("DB Error", e.toString());
e.printStackTrace();
}
}
5.Create以下方法将数据删除到数据库中。
public void deleteRow(long rowID)
{
try
{
db.delete(TABLE_NAME, TABLE_ROW_ID + "=" + rowID, null);
Log.w("message","delete successfully");
}
catch (Exception e)
{
Log.e("DB ERROR", e.toString());
e.printStackTrace();
}
}
6.创建以下方法以获取特定行到数据库。
public void getRow(long rowID)
{
Cursor cursor;
try
{
cursor = db.query
(
TABLE_NAME,
new String[] { TABLE_ROW_ID, TABLE_ROW_ONE, TABLE_ROW_TWO, TABLE_ROW_THREE, TABLE_ROW_FOUR, TABLE_ROW_FIVE, TABLE_ROW_SIX },
TABLE_ROW_ID + "=" + rowID,
null, null, null, null, null
);
cursor.moveToFirst();
if (!cursor.isAfterLast())
{
do
{
String row_item_id=cursor.getLong(0);
String row_item_name=cursor.getString(1);
String row_item_basic_price=cursor.getFloat(2);
String row_item_tax=cursor.getFloat(3);
String row_item_shipping=cursor.getFloat(4);
String row_item_price=cursor.getFloat(5);
byte[] imgByte = cursor.getBlob(6);
Bitmap row_item_bitmap=BitmapFactory.decodeByteArray(imgByte, 0, imgByte.length);
}
while (cursor.moveToNext());
}
cursor.close();
}
catch (SQLException e)
{
Log.e("DB ERROR", e.toString());
e.printStackTrace();
}
}
7.创建一个ArrayList,它将保存从数据库中收集的所有数据。
ArrayList<ArrayList<Object>> dataArrays = new ArrayList<ArrayList<Object>>();
这是一个创建“游标”对象的数据库调用。 游标对象存储从数据库收集的信息,用于迭代数据。
public ArrayList<ArrayList<Object>> getAllRowsAsArrays()
{
ArrayList<ArrayList<Object>> dataArrays = new ArrayList<ArrayList<Object>>();
Cursor cursor;
try
{
// ask the database object to create the cursor.
cursor = db.query(
TABLE_NAME,
new String[]{TABLE_ROW_ID, TABLE_ROW_ONE, TABLE_ROW_TWO},
null, null, null, null, null
);
// move the cursors pointer to position zero.
cursor.moveToFirst();
// if there is data after the current cursor position, add it
// to the ArrayList.
if (!cursor.isAfterLast())
{
do
{
ArrayList<Object> dataList = new ArrayList<Object>();
dataList.add(cursor.getLong(0));
dataList.add(cursor.getString(1));
dataList.add(cursor.getString(2));
dataArrays.add(dataList);
}
// move the cursor's pointer up one position.
while (cursor.moveToNext());
}
}
catch (SQLException e)
{
Log.e("DB Error", e.toString());
e.printStackTrace();
}
// return the ArrayList that holds the data collected from
// the database.
return dataArrays;
}