1

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

2 に答える 2

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.データベースにデータを削除するための次のメソッドを作成します。

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;
        }
于 2012-10-12T07:33:11.097 に答える
0

メインアクティビティでは、insertを呼び出す前にdbUser.open()を実行し、挿入が完了した後に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); 
        }
于 2012-09-08T04:11:49.293 に答える