2014-02-16 90 views
0

我想將單個整數值添加到我的SQLite數據庫中。問題在於int值在另一個類中,那麼如何將這個值添加到我的數據庫中,並說明總贏?我只想在裏面添加一段數據?如何在SQLite中添加數據Android

public class Database extends SQLiteOpenHelper{ 

public Database(Context applicationContext) { 
    super(applicationContext, "HighScores.db",null, 1); 
} 

@Override //creating database 
public void onCreate(SQLiteDatabase database) { 

    String query = "CREATE TABLE HighScores (totalWins INTEGER)"; 
    database.execSQL(query); 
} 

@Override //if the table exists then drop it 
public void onUpgrade(SQLiteDatabase database, int arg1, int arg2) { 
    String query = "DROP TABLE IF EXISTS HighScores"; 
    database.execSQL(query); 
    onCreate(database); 

} 

//for inserting values 
public void insertHighScores(HashMap<String, String> queryValues) { 
    SQLiteDatabase database = this.getWritableDatabase(); 

    ContentValues values = new ContentValues(); 
    values.put("totalWins",queryValues.get("totalWins")); 

    database.insert("HighScores", null, values); 
    database.close(); 
} 

//for updating values 
public int updateHighScores(HashMap<String, String> queryValues){ 
    SQLiteDatabase database = this.getWritableDatabase(); 

    ContentValues values = new ContentValues(); 
    values.put("totalWins",queryValues.get("totalWins")); 

    return database.update("HighScores", values, "totalWins" + " =?", new String[] 
      {queryValues.get("totalWins")}); 
} 
//return all highscores 
public ArrayList<HashMap<String,String>>getAllHighScores() { 
    ArrayList<HashMap<String, String>> highScoreArrayList = new ArrayList<HashMap<String, String>>(); 

    String selectQuery = "SELECT * FROM HighScores"; 

    SQLiteDatabase database = this.getWritableDatabase(); 

    Cursor MyCursor = database.rawQuery(selectQuery, null); 

    if (MyCursor.moveToFirst()) { 
     do{ 
      HashMap<String, String>highScoresMap = new HashMap<String, String>(); 
      highScoresMap.put("totalWins",MyCursor.getString(0)); 

      highScoreArrayList.add(highScoresMap); 

     }while(MyCursor.moveToNext()); 
    } 
    return highScoreArrayList; 
} 

    } 
+0

當您嘗試插入時是否收到錯誤消息? – janos

+0

我不知道如何插入我還沒有嘗試插入,因爲我不知道如何,爲什麼數據庫有問題? – user3267882

+0

你讀過這個嗎? http://developer.android.com/training/basics/data-storage/databases.html – janos

回答

0

這個怎麼樣?

public class SomeOtherClass{ 


Database myDatabase = new Database (this); 

public void editHighScores(int myvalue){ 

    HashMap<String, String> queryValues = new HashMap<String, String>(); 
    queryValues.put("totalWins", myvalue); 

    myDatabase.insertHighScores(queryValues); 
} 
} 
+0

但這是存儲一個編輯文本?我有一個int值在另一個它不在一個活動中,我試圖將該int值存儲到數據庫中。 – user3267882

+0

見上面我編輯過,這是你的意思嗎? –

相關問題