在SQLite中插入和提取数据

时间:2017-02-19 19:08:46

标签: java android sqlite android-sqlite

我在将数据插入SQLite数据库时遇到困难。当我调用addData()方法时,我的应用程序崩溃了。我在addData方法中的MainActivity类中调用GameView方法(位于onTouchEvent)。我需要将turns整数插入到数据库的COLUMN_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;
    }

}

MainActivity.java:

公共类MainActivity扩展了AppCompatActivity {

    private GestureDetector mGestureDetector;
    private ImageView imageView;

    private RadioGroup radioGroup;

    private int mcolumns;
    private int mrows;

    DatabaseHelper myDb;

    String test = "test data";
    int turns;

    static Context appcon;

    String highScore;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        appcon = this;
        myDb = new DatabaseHelper(this);

    }

    public void runGame(View view){

        Intent intent = new Intent(this, GameViewActivity.class);

        startActivity(intent);
    }

    public void runInstructions(View view) {

        Intent intent = new Intent(this, InstructionsActivity.class);

        startActivity(intent);
    }


    public void setTurns() {
        //GameView mGameView = new GameView(getApplicationContext());
        this.turns = GameView.turns;
        System.out.println("Turns: " + Integer.toString(turns));
    }

    public void addData() {

        boolean isInserted = myDb.insertData(test);
        if(isInserted == true) {
            System.out.println("Data inserted");
        }
        else {
            System.out.println("Data NOT inserted");
        }
    }

    public void getData() {
       Cursor res = myDb.getAllData();
        StringBuffer buffer = new StringBuffer();
        while(res.moveToNext()) {
            buffer.append(res.getString(1));
        }
        System.out.println(buffer.toString());
    }

}

1 个答案:

答案 0 :(得分:0)

onTouchEvent类的GameView中,而不是创建一个新的MainActivity实例,我怀疑它是否正在运行failiure,您可以调用{{1}的insertData方法直接类。例如而不是使用: -

DatabaseHelper

尝试

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