Android + SQLite:代码不运行?

时间:2014-07-02 13:48:31

标签: android sqlite genymotion

我正在尝试在Android应用程序中使用SQLite实现数据库。

当我尝试运行当前的代码时,我收到错误"应用程序已停止工作"在我的genymotion模拟器中。我的代码有什么错误?

数据库创建类:

public class DatabaseHelper extends SQLiteOpenHelper {

    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "MultapplyDatabase";

    // Contacts table name
    private static final String TABLE_SCORE = "";

    // Contacts Table Columns names
    private static final String COl_NAME = "name";
    private static final String COL_SCORE = "score";
    //private static final String COL_DATE = "date";


    /**
     * Constructor
     * @param context
     */
    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }


    /**
     * Method that creates the database
     */
    @Override
    public void onCreate(SQLiteDatabase db) {

        String CREATE_TABLE_SCORE = "CREATE TABLE " + TABLE_SCORE + "("
                + COl_NAME + " STRING PRIMARY KEY," + COL_SCORE + " INTEGER" + ")";
        db.execSQL(CREATE_TABLE_SCORE);


    }

    /**
     * Method that upgrades the database
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        // Drop older table if existed 
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_SCORE); 

        // Create tables again
        onCreate(db);


    }

    /**
     * All CRUD operations
     */
    // Adding new score details (Name, score, date)
    void addScore(Score score) {
        SQLiteDatabase db = this.getWritableDatabase();

        //ContentValues- holds the values.
        ContentValues values = new ContentValues();
        values.put(COl_NAME, score.getName()); // Contact Name
        values.put(COL_SCORE, score.getScore()); // Contact Phone

        // Inserting Row (i.e. the values that were entered from above
        db.insert(TABLE_SCORE, null, values);
        db.close(); // Closing database connection

}
    /**
     * Method will return a single Name and score
     * @param id
     * @return
     */
    // Getting single contact
    Score getScore(String name) {
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_SCORE, new String[] { COl_NAME,
                COL_SCORE}, COl_NAME + "=?",
                new String[] { String.valueOf(name) }, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();

        Score score = new Score(cursor.getString(0),Integer.parseInt(cursor.getString(1)));
        // return contact
        return score;
    }

    /**
     * Method will return a list of all the scores
     * @return
     */
    // Getting All Contacts
    public List<Score> getAllScores() {
        List<Score> scoreList = new ArrayList<Score>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_SCORE;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Score score = new Score();
                score.setName(cursor.getString(0));
                score.setScore(Integer.parseInt(cursor.getString(1)));
                // Adding contact to list
                scoreList.add(score);
            } while (cursor.moveToNext());
        }

        // return contact list
        return scoreList;
    }

}

我希望对其中的数据进行评分的类(包含getter和setter等)     公共课成绩{

    // inst vars
    String name;
    int score;

    /**
     * Default const
     */
    public Score(){

    }


    /**
     * Arg based const
     * @param name
     * @param score
     */
    public Score(String name, int score) {

        this.name = name;
        this.score = score;

    }

    public String getName() {
        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

    public int getScore() {
        return score;

    }

    public void setScore(int score) {

        this.score = score;

    }

}

尝试添加到数据库等时使用的类:

public class About extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.about);

        DatabaseHelper db = new DatabaseHelper(this);

        /**
         * CRUD Operations
         * */
        // Inserting Contacts
        Log.d("Insert: ", "Inserting ..");
        db.addScore(new Score("Ross", 8));
        db.addScore(new Score("Steve", 15));

        // Reading all contacts
        Log.d("Reading: ", "Reading all contacts..");
        List<Score> scores = db.getAllScores();

        for (Score s : scores) {
            String log = "Name: " + s.getName() + " ,Score: " + s.getScore();
            // Writing Contacts to log
            Log.d("Name: ", log);
        }
    }
}

LogCat错误报告:

07-02 13:41:04.663: E/AndroidRuntime(1363): FATAL EXCEPTION: main
07-02 13:41:04.663: E/AndroidRuntime(1363): Process: com.example.multapply, PID: 1363
07-02 13:41:04.663: E/AndroidRuntime(1363): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.multapply/com.example.multapply.About}: android.database.sqlite.SQLiteException: near "(": syntax error (code 1): , while compiling: CREATE TABLE (name STRING PRIMARY KEY,score INTEGER)

编辑:

在命名表并再次运行代码后,我现在收到以下错误:

07-02 14:48:20.767: E/SQLiteDatabase(1427): Error inserting score=8 name=Ross
07-02 14:48:20.767: E/SQLiteDatabase(1427): android.database.sqlite.SQLiteConstraintException: column name is not unique (code 19)
07-02 14:48:20.767: E/SQLiteDatabase(1427):     at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)

1 个答案:

答案 0 :(得分:4)

你应该给出一个表名

您的代码在这里:

 CREATE TABLE (name STRING PRIMARY KEY,score INTEGER)

它应该是

 CREATE TABLE XXXX (name STRING PRIMARY KEY,score INTEGER)

您的TABLE_SCORE为空,按照:

// Contacts table name
private static final String TABLE_SCORE = "";