数据在Android中的SQLite中插入两次

时间:2015-11-12 07:35:34

标签: android database sqlite

我正在使用Android和SQLite创建一个APP作为我的第一个数据库项目 我可以将数据插入到数据库中,但是当我点击Add Data时,即使我只点击一次,它也会将相同的数据添加到数据库中2次。

我无法找到解决方案

以下是我的Datahelper类代码,我已经完成的所有进口,这里没有提到。

public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, 2);


}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table " + TABLE_NAME +" (SID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,COURSE_NAME TEXT,COURSE_FEES BIGINT,REFERENCE VARCHAR,NUMBER BIGINT,DOJ VARCHAR,NOTES VARCHAR)");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS students");
    onCreate(db);
}
public Boolean insertData(String name,String cn,String cf,String ref,String num,String doj,String Notes)
{
    SQLiteDatabase db=this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL_2,name);
    contentValues.put(COL_3,cn);
    contentValues.put(COL_4,cf);
    contentValues.put(COL_5,num);
    contentValues.put(COL_6,ref);
    contentValues.put(COL_7,doj);
    contentValues.put(COL_8,Notes);
    db.insert(TABLE_NAME, null, contentValues);
    long result=db.insert(TABLE_NAME,null,contentValues);
    if (result==-1)
        return false;
    else
        return true;

}
public Cursor getAllData()
{
    SQLiteDatabase db=this.getWritableDatabase();
    Cursor res = db.rawQuery("select * from students",null);
    return res;
}}

此处的主要活动

public class MainActivity extends AppCompatActivity {
DatabaseHelper myDb;

EditText editname,editcourse,editfees,editref,editnum,editnotes;
Button Add;
TextView editdoj,ViewB;
private DatePicker datePicker;
private Calendar calendar;
private TextView dateView;
private int year, month, day;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    myDb=new DatabaseHelper(this);

    editname= (EditText) findViewById(R.id.NameET);
    editcourse= (EditText) findViewById(R.id.CourseNameET);
    editfees= (EditText) findViewById(R.id.FeesET);
    editref= (EditText) findViewById(R.id.ReferenceET);
    editnum= (EditText) findViewById(R.id.NumberET);
    editdoj= (TextView) findViewById(R.id.dateView);
    editnotes= (EditText) findViewById(R.id.NoteET);
    dateView = (TextView) findViewById(R.id.textView3);
    Add= (Button) findViewById(R.id.AddBT);
    ViewB= (Button) findViewById(R.id.ViewBT);
    calendar = Calendar.getInstance();
    year = calendar.get(Calendar.YEAR);
    month = calendar.get(Calendar.MONTH);
    day = calendar.get(Calendar.DAY_OF_MONTH);
    showDate(year, month + 1, day);
    AddData();
    viewAll();
}
public void AddData()
{
    Add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
             boolean isInserted=myDb.insertData(editname.getText().toString(),editcourse.getText().toString(),
                    editfees.getText().toString(),editref.getText().toString(),editnum.getText().toString(),
                    editdoj.getText().toString(),editnotes.getText().toString());

            if(isInserted=true)
                    Toast.makeText(MainActivity.this,"Inserted",Toast.LENGTH_LONG).show();
                else
                    Toast.makeText(MainActivity.this,"Not Inserted",Toast.LENGTH_LONG).show();
        }
    });
}
public void viewAll()
{
    ViewB.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Cursor res=myDb.getAllData();
                    if(res.getCount()== 0) {
                        showMessage("ERROR","No database");
                        return;
                    }else
                    {
                        StringBuffer buffer=new StringBuffer();
                        while (res.moveToNext())
                        {
                            buffer.append("Student No:"+ res.getString(0)+"\n");
                            buffer.append("Name:"+ res.getString(1)+"\n");
                            buffer.append("Course:"+ res.getString(2)+"\n");
                            buffer.append("Fees Total:"+ res.getString(3)+"\n");
                            buffer.append("Reference:"+ res.getString(5)+"\n");
                            buffer.append("Number:"+ res.getString(4)+"\n");
                            buffer.append("DOJ:"+ res.getString(6)+"\n");
                            buffer.append("Extra:" + res.getString(7) + "\n");
                            buffer.append("_____________________________\n");
                        }
                        showMessage("I.M.A.G.E",buffer.toString());

                    }
                }
            }
    );
}
public void showMessage(String title,String Message)
{
    AlertDialog.Builder builder=new AlertDialog.Builder(this);
    builder.setCancelable(true);
    builder.setTitle(title);
    builder.setMessage(Message);
    builder.show();

}


@SuppressWarnings("deprecation")
public void setDate(View view) {
    showDialog(999);
    Toast.makeText(getApplicationContext(), "Select Joining Date ", Toast.LENGTH_LONG)
            .show();
}

@Override
protected Dialog onCreateDialog(int id) {
    // TODO Auto-generated method stub
    if (id == 999) {
        return new DatePickerDialog(this, myDateListener, year, month, day);
    }
    return null;
}

private DatePickerDialog.OnDateSetListener myDateListener = new DatePickerDialog.OnDateSetListener() {
    @Override
    public void onDateSet(DatePicker arg0, int arg3, int arg2, int arg1) {
        // TODO Auto-generated method stub
        // arg1 = year
        // arg2 = month
        showDate(arg3, arg2 + 1, arg1);
        // arg3 = day
    }
};

private void showDate(int year, int month, int day) {
    dateView.setText(new StringBuilder().append(day).append("/")
            .append(month).append("/").append(year));
}}

2 个答案:

答案 0 :(得分:3)

您遇到此问题是因为您将值插入数据库2次。

不正确:

db.insert(TABLE_NAME, null, contentValues);
long result=db.insert(TABLE_NAME,null,contentValues);
if (result==-1)
    return false;
else
    return true;

正确:

long result=db.insert(TABLE_NAME,null,contentValues);
if (result==-1)
    return false;
else
    return true;

答案 1 :(得分:3)

您曾两次致电insert()

db.insert(TABLE_NAME, null, contentValues); // Unnecessary
long result=db.insert(TABLE_NAME,null,contentValues);

删除第一行,它应该可以正常工作:

long result=db.insert(TABLE_NAME,null,contentValues);