2017-02-19 53 views
-2

我很难将数据插入到我的SQLite数据库。当我打电话给我的addData()方法时,我的应用程序崩溃。我在我的onTouchEvent方法中从我的GameView类中调用我的addData方法(位于MainActivity)。我需要将我的turns整数插入到我的数据库中的COLUMN_SCORES列中。感谢任何帮助!插入和提取数据到SQLite

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

} 
+2

'我的应用程序crashes' - 请张贴堆栈跟踪 –

+1

我不认为你应该创建一个新的MainActivity在'MainActivity主要=新MainActivity ();'。 – MikeT

+0

PS您可能希望在阅读[SQLite Autoincrement](http://sqlite.org/autoinc.html)后使用'AUTOINCREMENT'重新考虑。 – MikeT

回答

0

在您的onTouchEventGameView类中,而不是创建一个MainActivity的新实例(我怀疑它正在追查不合格),您可以直接调用DatabaseHelper类的insertData方法。例如而不是使用: -

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

尝试

 DatabaseHelper mydb = new DatabaseHelper(this); 
     mydb.insertData("test");