Java 在SQLite中插入和获取数据

Java 在SQLite中插入和获取数据,java,android,sqlite,android-sqlite,Java,Android,Sqlite,Android Sqlite,我在将数据插入SQLite数据库时遇到困难。当我调用我的addData()方法时,我的应用程序崩溃。我从GameView类调用onTouchEvent方法中的addData方法(在MainActivity中)。我需要将我的整数插入数据库中的列\u SCORES列。谢谢你的帮助 DatabaseHelper.java: public class DatabaseHelper extends SQLiteOpenHelper { public static final String DAT

我在将数据插入SQLite数据库时遇到困难。当我调用我的
addData()
方法时,我的应用程序崩溃。我从
GameView
类调用
onTouchEvent
方法中的
addData
方法(在
MainActivity
中)。我需要将我的
整数插入数据库中的
列\u SCORES
列。谢谢你的帮助

DatabaseHelper.java:

public class DatabaseHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "scores.db";
    public static final String TABLE_NAME = "scores_table";
    public static final String COLUMN_ID = "ID";
    public static final String COLUMN_SCORE = "SCORE";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table " + TABLE_NAME +" (ID INTEGER PRIMARY KEY AUTOINCREMENT, SCORE INTEGER)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }

    public boolean insertData(String score) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COLUMN_SCORE, score);
        long result = db.insert(TABLE_NAME, null, contentValues);

        if(result == -1) {
            return false;
        }
        else {
            return true;
        }
    }

    public Cursor getAllData() {
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor res = db.rawQuery("select * from " + TABLE_NAME, null);
        return res;
    }

    public boolean updateData(String id, String score) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COLUMN_ID, id);
        contentValues.put(COLUMN_SCORE, score);
        db.update(TABLE_NAME, contentValues, "ID = ?", new String[] { id });
        return true;
    }

    public Integer deleteData(String id) {
        SQLiteDatabase db = this.getWritableDatabase();
        return db.delete(TABLE_NAME, "ID = ?", new String[] { id });
    }
}
GameView.java:

public class GameView extends View {

    int mcolumns = 5;
    int mrows = 5;
    private NetwalkGrid mGame = new NetwalkGrid(mcolumns, mrows);
    private GestureDetector mGestureDetector;
    Random rand = new Random();
    int sizeSqX;
    int sizeSqY;
    int sizeSq;

    public static int turns;        
    Paint bgPaint;

    public GameView(Context context) {
        super(context);
        init();
    }

    private void init() {

    bgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        bgPaint.setStyle(Paint.Style.FILL);
        bgPaint.setColor(0xff0000ff);
    mGame.gridCopy();

        for (int col = 0; col < mGame.getColumns(); col++) {
            for (int row = 0; row < mGame.getRows(); row++) {

                int num = rand.nextInt(3) + 1;

                for (int turns = 1; turns < num; turns++) {
                    mGame.rotateRight(col, row);
                }
            }
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {

        canvas.drawColor(Color.BLACK);

        sizeSqX = getWidth() / mcolumns;
        sizeSqY = getHeight() / mrows;

        if (sizeSqX < sizeSqY) {
            sizeSq = sizeSqX;
        }
        else {
            sizeSq = sizeSqY;
        }

        Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.placeholder);
        //Bitmap s = BitmapFactory.decodeResource(getResources(), R.drawable.straight);
        //Bitmap dl = BitmapFactory.decodeResource(getResources(), R.drawable.downleft);
        int cellContent;

        //square = get width / col
        int square = 140;
        for (int col = 0; col < mGame.getColumns(); col++) {
            for (int row = 0; row < mGame.getRows(); row++) {

                cellContent = mGame.getGridElem(col,row);
                if (cellContent == 1) {
                    b = BitmapFactory.decodeResource(getResources(), R.drawable.up_down); // Image for down position
                    if (cellContent == 65 && mGame.checkWin()) {
                        b = BitmapFactory.decodeResource(getResources(), R.drawable.up_down_connected);
                    }
                }
                else if (cellContent == 2) {
                    b = BitmapFactory.decodeResource(getResources(), R.drawable.left_right); // Right position
                    if (mGame.checkWin()) {
                        b = BitmapFactory.decodeResource(getResources(), R.drawable.left_right_connected);
                    }
                }
                else if (cellContent == 3) {
                    b = BitmapFactory.decodeResource(getResources(), R.drawable.right_down); // Down right position WORKS
                    if (mGame.checkWin()) {
                        b = BitmapFactory.decodeResource(getResources(), R.drawable.right_down_connected);
                    }

                else {
                    b = BitmapFactory.decodeResource(getResources(), R.drawable.placeholder2); //
                }

                canvas.drawBitmap(b, null,new Rect(col * sizeSq, row * sizeSq,col*sizeSq+sizeSq, row*sizeSq+sizeSq), null);

                //Paint paint = new Paint();
                //paint.setColor(Color.WHITE);
               // paint.setStyle(Paint.Style.FILL);

                TextPaint tp = new TextPaint();
                tp.setColor(Color.GREEN);
                tp.setTextSize(70);
                tp.setTypeface(Typeface.create("Courier", Typeface.BOLD));
                canvas.drawText("Moves: " + String.valueOf(turns), 10, 1180, tp);
                canvas.drawText("High score: ", 10, 1280, tp);

            }
        }
    }

    //SoundPoolPlayer sound = new SoundPoolPlayer(getContext());

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        //boolean eventConsumed = mGestureDetector.onTouchEvent(event);
        //GameView mGameView = new GameView(getApplicationContext());

        //if (eventConsumed) {
            int x = (int) event.getX();
            int y = (int) event.getY();

            int column = getColTouched(event.getX());
            int row = getRowTouched(event.getY());

        try {
            mGame.rotateRight(column, row);
            System.out.println(mcolumns);

            turns++;
            MainActivity main = new MainActivity();
            //main.setTurns();
            main.addData();
            //main.getData();

            mGame.checkWin();

            if (mGame.checkWin()) {
                System.out.println("check win works");
                invalidate();

                //main.setTurns();
                //main.AddData();

            }
            invalidate();

        }
        catch (ArrayIndexOutOfBoundsException err) {
            System.out.println("User has pressed outside game grid - exception caught");
        }

        //sound.playShortResource(R.raw.click);
       // sound.release();

        return super.onTouchEvent(event);

    }

    public int getColTouched(float x) {
        return (int) (x / sizeSq);
    }

    public int getRowTouched(float y) {
        return (int) (y / sizeSq);
    }

    public int getCols() {
        return mcolumns;
    }

    public void setColRow(int columns, int rows) {
        this.mcolumns = columns;
        this.mrows = rows;
    }

    public int getTurns() {
        return turns;
    }

}

GameView
类中的
onTouchEvent
中,您可以直接调用
DatabaseHelper
类的
insertData
方法,而不是创建MainActivity的新实例,我怀疑这是导致失败的原因。e、 g.代替使用:-

        MainActivity main = new MainActivity();
        //main.setTurns();
        main.addData();
        //main.getData();
试一试


my app崩溃
-请发布StackTrace我认为您不应该像
MainActivity main=new MainActivity()中那样创建新的MainActivity
.PS阅读此内容后,您可能希望重新考虑使用
AUTOINCREMENT
        MainActivity main = new MainActivity();
        //main.setTurns();
        main.addData();
        //main.getData();
        DatabaseHelper mydb = new DatabaseHelper(this);
        mydb.insertData("test");