2014-12-02 36 views
-2

我正在创建一个应用程序,其中人们将分数给予其他人。为此,我想在安装应用程序时将某人的名字(比如5)插入到数据库中。现在,当我第一次运行应用程序时,一切都很顺利。但是当我第二次运行它时,再次插入数据使其成为10,即重复数据。问题是每当我运行这个活动时,它都会添加数据。这个问题的解决方案是什么? 这里是我的代码:重复的数据问题android sqlite

@TargetApi(Build.VERSION_CODES.HONEYCOMB) 
    public class GamePlay extends ActionBarActivity { 
    //Some code----------- 

@Override 
protected void onCreate(Bundle savedInstanceState) { 

    super.onCreate(savedInstanceState); 
    setContentView(R.layout.gameplay); 
    //Some code---- 

    db=openOrCreateDatabase("MyGameData", MODE_PRIVATE, null); 

    try{ 
     db.execSQL("create table teachers(_id integer primary key autoincrement , name varchar(30) , gender varchar(2) , score integer)"); 
     Toast.makeText(this, "Table created", Toast.LENGTH_SHORT).show(); 
    } 

    catch(Exception e){ 
     Toast.makeText(this, "Exception 1", Toast.LENGTH_SHORT).show(); 
     Log.i("Create table", e.getMessage()); 
    } 

    // Insert values in table------- 


    String str_name[]={"arun", "dhanraj", "decoder", "sanjana"}; 
    String str_gender[]={"m", "m", "m", "f"}; 

    ContentValues cv = new ContentValues(); 

    for(int i=0; i<str_name.length; i++){ 

     cv.put("name", str_name[i]); 
     cv.put("gender", str_gender[i]); 
     db.insert("teachers", null, cv); 

    } 

    //Some code------ 
+0

当然。你应该**更新**现有数据,如果已经存在。你只**插入**新记录,复制你的数据库中的信息。 – 2014-12-02 21:52:28

+0

@DerGolem:我想在安装过程中插入新数据。首先没有数据存在。这就是为什么我使用INSERT。更新是另一个过程。那么我应该如何插入名字和性别? – Decoder 2014-12-02 21:57:50

+1

我会做另一个查询,看看用户是否存在,然后做Der Golem说的,并更新数据。 – 2014-12-02 22:02:30

回答

1

你应该有一个SQLiteOpenHelper类,它包含了数据库管理和生命周期一样

onCreate(SQLiteDatabase db) // Called when the database is created for the first time. 
onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) //Called when the database needs to be downgraded. 
onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) // Called when the database needs to be upgraded. 

而其他的一些方法,你可以看看这里:http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html

按照本教程应该让你关于使用此帮手的好路径: http://developer.android.com/training/basics/data-storage/databases.html

我的建议是创建一些Querys,类似于将在t之后填充并执行它们的Querys他创造的表格也应该在那里。这样,您的应用程序将只会首次插入这些插入内容,即使您更新数据库(如果您在onUpgrade()方法中没有声明其他内容),也会保留它们。

这应该解决您的问题。

+0

是的,这解决了这个问题。谢谢。 – Decoder 2014-12-03 04:48:01

2

如果我得到你的问题吧,你可以使用一个辅助类和扩展SQLiteOpenHelper。

在onCreate方法中,您可以插入所需的数据。这种方法只被调用一次。

希望这会有所帮助。