Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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------
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
262 views
Welcome To Ask or Share your Answers For Others

1 Answer

If I get your problem right, you could use a helper class and extend SQLiteOpenHelper.

In the onCreate method you can insert the needed data. This method is called only once.

Hope this helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...