Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...