2015-06-10 35 views
-1

我試圖用數據庫做一個簡單的應用程序。 問題是,由於某種原因,應用程序在啓動時崩潰。 不幸的是,崩潰日誌並沒有告訴我很多,除了創建數據庫似乎有問題,但也許有人可以理解它。 在此先感謝!數據庫導致應用程序崩潰

MainActivity

package se.welovecode.wdmmg; 

import android.support.v7.app.ActionBarActivity; 
import android.os.Bundle; 
import android.text.format.Time; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.widget.EditText; 


public class MainActivity extends ActionBarActivity { 

DBAdapter myDB; 
EditText etTransaction; 

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

    openDB(); 
} 

protected void onDestroy(){ 
    super.onDestroy(); 
    closeDb(); 
} 

private void openDB(){ 
    myDB = new DBAdapter(this); 
    myDB.open(); 
} 
private void closeDb(){ 

    myDB.close(); 
} 

public void onClick_AddRecord(View v){ 
    myDB.insertRow("transaction","item","sum"); 
} 
} 

將對DBAdapter

package se.welovecode.wdmmg; 

import android.content.ContentValues; 
import android.content.Context; 
import android.database.Cursor; 
import android.database.sqlite.SQLiteDatabase; 
import android.database.sqlite.SQLiteOpenHelper; 
import android.util.Log; 

public class DBAdapter { 

private static final String TAG = "DBAdapter"; //used for logging database version changes 

// Field Names: 
public static final String KEY_ROWID = "_id"; 
public static final String KEY_TRANSACTION = "transaction"; 
public static final String KEY_ITEM = "item"; 
public static final String KEY_SUM = "sum"; 

public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_TRANSACTION, KEY_ITEM, KEY_SUM,}; 

// Column Numbers for each Field Name: 
public static final int COL_ROWID = 0; 
public static final int COL_TRANSACTION = 1; 
public static final int COL_ITEM = 2; 
public static final int COL_SUM = 3; 

// DataBase info: 
public static final String DATABASE_NAME = "db"; 
public static final String DATABASE_TABLE = "mainTransactions"; 
public static final int DATABASE_VERSION = 1; // The version number must be incremented each time a change to DB structure occurs. 

//SQL statement to create database 
private static final String DATABASE_CREATE_SQL = 
     "CREATE TABLE " + DATABASE_TABLE 
     + " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " 
     + KEY_TRANSACTION + " TEXT NOT NULL, " 
     + KEY_ITEM + " TEXT NOT NULL, " 
     + KEY_SUM + " TEXT," 
     + ");"; 

private final Context context; 
private DatabaseHelper myDBHelper; 
private SQLiteDatabase db; 


public DBAdapter(Context ctx) { 
    this.context = ctx; 
    myDBHelper = new DatabaseHelper(context); 
} 

// Open the database connection. 
public DBAdapter open() { 
    db = myDBHelper.getWritableDatabase(); 
    return this; 
} 

// Close the database connection. 
public void close() { 
    myDBHelper.close(); 
} 

// Add a new set of values to be inserted into the database. 
public long insertRow(String transaction, String item, String sum) { 
    ContentValues initialValues = new ContentValues(); 
    initialValues.put(KEY_TRANSACTION, transaction); 
    initialValues.put(KEY_ITEM, item); 
    initialValues.put(KEY_SUM, sum); 

    // Insert the data into the database. 
    return db.insert(DATABASE_TABLE, null, initialValues); 
} 

// Delete a row from the database, by rowId (primary key) 
public boolean deleteRow(long rowId) { 
    String where = KEY_ROWID + "=" + rowId; 
    return db.delete(DATABASE_TABLE, where, null) != 0; 
} 

public void deleteAll() { 
    Cursor c = getAllRows(); 
    long rowId = c.getColumnIndexOrThrow(KEY_ROWID); 
    if (c.moveToFirst()) { 
     do { 
      deleteRow(c.getLong((int) rowId));    
     } while (c.moveToNext()); 
    } 
    c.close(); 
} 

// Return all data in the database. 
public Cursor getAllRows() { 
    String where = null; 
    Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null, null, null, null); 
    if (c != null) { 
     c.moveToFirst(); 
    } 
    return c; 
} 

// Get a specific row (by rowId) 
public Cursor getRow(long rowId) { 
    String where = KEY_ROWID + "=" + rowId; 
    Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, 
        where, null, null, null, null, null); 
    if (c != null) { 
     c.moveToFirst(); 
    } 
    return c; 
} 

// Change an existing row to be equal to new data. 
public boolean updateRow(long rowId, String transaction, String item, String sum) { 
    String where = KEY_ROWID + "=" + rowId; 
    ContentValues newValues = new ContentValues(); 
    newValues.put(KEY_TRANSACTION, transaction); 
    newValues.put(KEY_ITEM, item); 
    newValues.put(KEY_SUM, sum); 
    // Insert it into the database. 
    return db.update(DATABASE_TABLE, newValues, where, null) != 0; 
} 


private static class DatabaseHelper extends SQLiteOpenHelper 
{ 
    DatabaseHelper(Context context) { 
     super(context, DATABASE_NAME, null, DATABASE_VERSION); 
    } 

    @Override 
    public void onCreate(SQLiteDatabase _db) { 
     _db.execSQL(DATABASE_CREATE_SQL);   
    } 

    @Override 
    public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) { 
     Log.w(TAG, "Upgrading application's database from version " + oldVersion 
       + " to " + newVersion + ", which will destroy all old data!"); 

     // Destroy old database: 
     _db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE); 

     // Recreate new database: 
     onCreate(_db); 
    } 
} 
} 

崩潰日誌

java.lang.RuntimeException: Unable to start activity ComponentInfo{se.welovecode.wdmmg/se.welovecode.wdmmg.MainActivity}: android.database.sqlite.SQLiteException: near "transaction": syntax error (code 1): , while compiling: CREATE TABLE mainTransactions (_id INTEGER PRIMARY KEY AUTOINCREMENT, transaction TEXT NOT NULL, item TEXT NOT NULL, sum TEXT,); 
     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2814) 
     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2879) 
     at android.app.ActivityThread.access$900(ActivityThread.java:182) 
     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1475) 
     at android.os.Handler.dispatchMessage(Handler.java:102) 
     at android.os.Looper.loop(Looper.java:145) 
     at android.app.ActivityThread.main(ActivityThread.java:6141) 
     at java.lang.reflect.Method.invoke(Native Method) 
     at java.lang.reflect.Method.invoke(Method.java:372) 
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399) 
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194) 
Caused by: android.database.sqlite.SQLiteException: near "transaction": syntax error (code 1): , while compiling: CREATE TABLE mainTransactions (_id INTEGER PRIMARY KEY AUTOINCREMENT, transaction TEXT NOT NULL, item TEXT NOT NULL, sum TEXT,); 
     at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method) 
     at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1093) 
     at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:670) 
     at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588) 
     at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:59) 
     at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31) 
     at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1798) 
     at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1729) 
     at se.welovecode.wdmmg.DBAdapter$DatabaseHelper.onCreate(DBAdapter.java:132) 
     at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251) 
     at  android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163) 
     at se.welovecode.wdmmg.DBAdapter.open(DBAdapter.java:54) 
     at se.welovecode.wdmmg.MainActivity.openDB(MainActivity.java:32) 
     at se.welovecode.wdmmg.MainActivity.onCreate(MainActivity.java:22) 
at android.app.Activity.performCreate(Activity.java:6374) 
at   android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119) 
at  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2767) 
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2879) 
            at android.app.ActivityThread.access$900(ActivityThread.java:182) 
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1475) 
            at android.os.Handler.dispatchMessage(Handler.java:102) 
            at android.os.Looper.loop(Looper.java:145) 
            at android.app.ActivityThread.main(ActivityThread.java:6141) 
            at java.lang.reflect.Method.invoke(Native Method) 
            at java.lang.reflect.Method.invoke(Method.java:372) 
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399) 
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194) 
+0

我看到'sum TEXT,'。看起來像逗號是多餘的 – olyv

回答

5

你去錯在這裏

+ KEY_SUM + " TEXT," // remove ,(comma) from last 

正確的:

String DATABASE_CREATE_SQL = 
    "CREATE TABLE " + DATABASE_TABLE 
    + " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " 
    + KEY_TRANSACTION + " TEXT NOT NULL, " 
    + KEY_ITEM + " TEXT NOT NULL, " 
    + KEY_SUM + " TEXT" 
    + ");"; 

而且改變交易列名becoz它的保留,並且不能在查詢中使用。

+2

一個非常小的優化(0.001 ns?),只是爲了最小化字符串連接:'+ KEY_SUM +「TEXT)」;(**; **沒有被使用)。如果我們都開始對這種類型的東西使用'StringBuilder',那會更好,但是!嗯,是的,也許在未來...;) –

+1

@DerGolem你說得對... –

1
public static final String KEY_TRANSACTION = "transaction"; 

交易是SQL保留字,不能用作列名。將其更改爲transaction_text或類似的東西。