Search code examples
androidsqliteduplicate-data

Duplicate data issue android sqlite


I am creating an app in which people give scores to other persons. For that, I want to insert names of some person (say 5) to a database during installation of the app. Now the when I run the app first time everything goes fine. But when I run it second time, the data are inserted again making it 10, i.e. duplicate data. The problem is whenever I run this activity, it adds the data. What is the solution to this problem? Here's my code:

@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------

Solution

  • You should have a SQLiteOpenHelper class which contains some methods for database management and lifecycle like

    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.
    

    And other ones, you can have a look here: http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html

    Following this tutorial should keep you on the good path about using this helper: http://developer.android.com/training/basics/data-storage/databases.html

    My advice is to create some Querys like the ones that will populate and execute them after the creation of the Tables which should be there too. This way, your app will only make those inserts the first time, and keep them even if you update your database (if you don't state something else on the onUpgrade() method).

    This should fix your problem.