2016-09-14 97 views
2

我正在創建一個應用程序,但是當我去插入一些數據時,它不起作用。這是我的應用程序的screenshot,包括錯誤消息。這裏是我的database職業:數據沒有被插入到SQLite數據庫中

public class database extends SQLiteOpenHelper { 
    public static final String DATABASE_NAME = "STUDENT"; 
    public static final String TABLE_NAME = "TRIP"; 
    public static final String COL1 = "ID"; 
    public static final String COL2 = "NAME"; 
    public static final String COL3 = "CURRENT"; 
    public static final String COL4 = "DESTINATION"; 
    public static final String COL5 = "BUDGET"; 
    public database(Context context) { 
     super(context, DATABASE_NAME, null, 1); 
    } 

    @Override 
    public void onCreate(SQLiteDatabase db) { 
     db.execSQL("create table if not exists " + TABLE_NAME + "(" + COL1 + " INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,CURRENT TEXT,DESTINATION TEXT,BUDGET INTEGER)"); 
    } 

    @Override 
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
     db.execSQL("drop table if exists " + TABLE_NAME); 
     onCreate(db); 
    } 
    public void insertdata(String name,String current,String destination,String budget) 
    { 
     SQLiteDatabase db=this.getWritableDatabase(); 
     db.execSQL("insert into TRIP(NAME,CURRENT,DESTINATION,BUDGET)values('" + name + "','" + current + "','" + destination + "',"+Integer.parseInt(budget)+")"); 
    } 
} 

有關如何解決這個問題的任何建議?

+1

卸載並重新安裝您的應用程序。 http://stackoverflow.com/questions/21881992/when-is-sqliteopenhelper-oncreate-onupgrade-run – laalto

+1

如果你已經採用了Current Field Later,那麼你需要先從設備上卸載應用程序,然後再運行應用程序,ii將工作 – Vickyexpert

+1

我想你需要在sqlite查詢結尾添加分號,比如'db.execSQL(「create table if not exists」+ TABLE_NAME +「(」+ COL1 +「INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,CURRENT TEXT,DESTINATION TEXT, BUDGET INTEGER);「);' – Pzy64

回答

1

試着讓insertdata函數返回一個long。這一個更換insertdata功能:

public long insertdata(String name, String current, String destination, String budget) { 
    SQLiteDatabase db = this.getWritableDatabase(); 

    ContentValues contentValues = new ContentValues(); 
    contentValues.put(COL2, name); 
    contentValues.put(COL3, current); 
    contentValues.put(COL4, destination); 
    contentValues.put(COL5, budget); 

    return db.insert(TABLE_NAME, null, contentValues); 
} 

在你的活動,你要插入的數據,請確保您調用這個函數像這樣:

database db = new database(this); 

if (db.insertdata("name", "current", "destination", "budget") > 0) 
    // do something else here 

如果您仍然遇到相同問題,請卸載您的應用程序並重試。如果它仍然無效,請隨時在下面發表評論。

+0

,但在我的代碼中,每當我刪除CURRENT列,那麼它的工作原理是插入數據 –

+0

這可能是您創建表格的方式。你是否仍然收到與上面提到的新代碼一樣的錯誤? – Razor