Android Studio +数据库-多个检查数据以插入数据(如果不存在)

时间:2018-10-27 17:31:35

标签: java android sqlite android-sqlite

我的代码有问题。我不知道如何检查数据库中的多列以在每个不存在的数据上插入不同的数据。

例如

第一个输入

名称:Raymond Jay Berin

事件:INTRAMURALS

主持人:CSG

第二个输入

名称:Raymond Jay Berin

事件:爱的座谈会

FACILITATOR:DSSC

这是那件事。雷蒙德·杰伊·贝林已经存在于数据库中,但我希望雷蒙德·杰伊·贝林将被插入到另一个事件中...

此外,我已经尝试创建多个表,但是当我单击“出勤”按钮添加数据时,我的项目崩溃了。

DatabaseHelper.class 的代码:

public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "attendance.sqlite";

public static final String TABLE_NAME = "attendance";
public static final String COL_1 = "ID";
public static final String COL_2 = "FULLNAME";
public static final String COL_EVENT_2 = "EVENT_NAME";
public static final String COL_EVENT_3 = "FACILITATOR_NAME";

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

}

@Override
public void onCreate(SQLiteDatabase db) {
    //ATTENDANCE
db.execSQL(" create table " + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
        "FULLNAME TEXT NOT NULL, EVENT_NAME TEXT NOT NULL, FACILITATOR_NAME TEXT NOT NULL)");

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    //ATTENDANCE
    db.execSQL(" DROP TABLE IF EXISTS "+TABLE_NAME );

    //recreate
    onCreate(db);
}

//ATTENDANCE
public boolean insertData (String fullname, String event, String facilitator){
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL_2,fullname);
    contentValues.put(COL_EVENT_2,event);
    contentValues.put(COL_EVENT_3,facilitator);
    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 "+TABLE_NAME,null);
    return res;
}

public boolean checkIfRecordExist(String nameOfTable,String columnName,String columnValue) {
    SQLiteDatabase db = null;
    try {
        db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT "+columnName+" FROM "+nameOfTable+" WHERE "+columnName+"='"+columnValue+"'",null);
        if (cursor.moveToFirst()) {
            db.close();
            Log.d("Record Already Exists", "Table is:" + nameOfTable + " ColumnName:" + columnName);
            return true;//record Exists

        }
        Log.d("New Record  ", "Table is:" + nameOfTable + " ColumnName:" + columnName + " Column Value:" + columnValue);
        db.close();
    } catch (Exception errorException) {
        Log.d("Exception occured", "Exception occured " + errorException);
        db.close();
    }
    return false;



} }

Attendance.java类的代码

public class Attendance extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
DatabaseHelper myDb;
EditText fname , eventname, faciname;
Button attendance;
Button view;
Switch lock;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_attendance);
    myDb = new DatabaseHelper(this);
    fname = findViewById(R.id.txtFullname);
    eventname = findViewById(R.id.eventname);
    faciname = findViewById(R.id.faciname);
    attendance = findViewById(R.id.btnatt);
    view = findViewById(R.id.btnview);
    lock = findViewById(R.id.switchLock);
    viewAll();
    AddData();
    lock.setOnCheckedChangeListener(this);

}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    if (lock.isChecked()){
        eventname.setEnabled(false);
        faciname.setEnabled(false);
    }else{
        eventname.setEnabled(true);
        faciname.setEnabled(true);
    }

}


public void viewAll() {
    view.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Cursor res = myDb.getAllData();
                    if (res.getCount() == 0) {
                        // show message
                        showMessage("Error", "Nothing found");
                        return;
                    }

                    StringBuffer buffer = new StringBuffer();
                    while (res.moveToNext()) {
                        buffer.append("ID :" + res.getString(0) + "\n");
                        buffer.append("NAME :" + res.getString(1) + "\n");
                        buffer.append("EVENT :" + res.getString(2) + "\n");
                        buffer.append("FACILITATOR :" + res.getString(3) + "\n"+"\n");
                    }

                    // Show all data
                    showMessage("ATTENDANCE LIST", 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();
}

public void AddData() {
    attendance.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final String valInput = fname.getText().toString();
            final String valInput1 = eventname.getText().toString();
            final String valInput2 = faciname.getText().toString();
            boolean valid = true;

            if (TextUtils.isEmpty(valInput)) {
                fname.setError("This Item must not be empty!");
                valid = false;
                }
            if (TextUtils.isEmpty(valInput1)) {
                eventname.setError("This Item must not be empty!");
                valid = false;
            }
            if (TextUtils.isEmpty(valInput2)) {
                faciname.setError("This Item must not be empty!");
                valid = false;
            }
                if (valid) {
                    boolean isExist = myDb.checkIfRecordExist(DatabaseHelper.TABLE_NAME, DatabaseHelper.COL_1, fname.getText().toString());
                    if (!isExist) {
                        boolean isInserted = myDb.insertData(fname.getText().toString(), eventname.getText().toString(), faciname.getText().toString());
                            if (isInserted) {
                                Toast.makeText(Attendance.this, "Attendance Success", Toast.LENGTH_LONG).show();
                                fname.setText(null);
                            } else if (isInserted == false) {
                                Toast.makeText(Attendance.this, "Failed to Attendance", Toast.LENGTH_LONG).show();
                            }
                    }else if (isExist == true){
                        Toast.makeText(Attendance.this, "Failed to Attendance "+fname+" Already Existed", Toast.LENGTH_LONG).show();
                    }
                }
                    }
                    }); }


public boolean onKeyDown(int keyCode, KeyEvent event) {
    //Handle the back button
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        //Ask the user if they want to quit
        new AlertDialog.Builder(this)
                .setIcon(android.R.drawable.ic_dialog_alert)
                .setTitle(R.string.Logout)
                .setMessage(R.string.really_logout)
                .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        //Stop the activity
                        Intent intent = new Intent(Attendance.this, MainActivity.class);
                        startActivity(intent);
                        Attendance.this.finish();
                    }

                })
                .setNegativeButton(R.string.no, null)
                .show();

        return true;
    } else {
        return super.onKeyDown(keyCode, event);
    }

}}

1 个答案:

答案 0 :(得分:0)

更改checkIfRecordExist这样的方法

public boolean checkIfRecordExist(String nameOfTable,String columnName1,String columnValue1,String columnName2,String columnValue2) {
    SQLiteDatabase db = null;
    try {
        db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT * FROM "+nameOfTable+" WHERE "+columnName1+"='"+columnValue1+"' and "+ columnName2 +"='"+columnValue2+"'",null);
.......................

像这样在行下更改

boolean isExist = myDb.checkIfRecordExist(DatabaseHelper.TABLE_NAME, DatabaseHelper.COL_1, fname.getText().toString(),DatabaseHelper.COL_2, eventname.getText().toString())