android - 如何进行验证以检查它是否有数据?带有 sqlite 的 android 工作室
问题描述
我想知道如何进行验证以检查是否有“数据库column1”然后我输入和保存的任何内容。它将转向“更新”而不是创建新的“Column2”。
这是代码
sB_Save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SettingModel txn = new SettingModel(); // initialize your model class first
txn.setH1(h1.getText().toString());
txn.setH2(h2.getText().toString());
txn.setH3(h3.getText().toString());
txn.setH4(h4.getText().toString());
txn.setPerson_Charge(Person_Charge.getText().toString());
txn.setUnit_Code(unit_Code.getText().toString());
try {
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("header1", txn.getH1()); // get the entered name here.
cv.put("header2", txn.getH2());
cv.put("header3", txn.getH3());
cv.put("header4", txn.getH4());
cv.put("unitcode", txn.getUnit_Code());
cv.put("personInCharge", txn.getPerson_Charge());
db.insert("Information", null, cv);
db.close();
Toast.makeText(Setting_Page.this, "Add successfully", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
它需要'if语句',但我不知道如何进行验证检查......请帮助。提前致谢
解决方案
您可以使用以下内容。
public void onClick(View v) {
SettingModel txn = new SettingModel(); // initialize your model class first
txn.setH1(h1.getText().toString());
txn.setH2(h2.getText().toString());
txn.setH3(h3.getText().toString());
txn.setH4(h4.getText().toString());
txn.setPerson_Charge(Person_Charge.getText().toString());
txn.setUnit_Code(unit_Code.getText().toString());
SQLiteDatabase db = dbHelper.getWritableDatabase();
Cursor csr = db.query("Information",null,null,null,null,null,null);
int rowcount = csr.getCount();
csr.close();
ContentValues cv = new ContentValues();
cv.put("header1", txn.getH1()); // get the entered name here.
cv.put("header2", txn.getH2());
cv.put("header3", txn.getH3());
cv.put("header4", txn.getH4());
cv.put("unitcode", txn.getUnit_Code());
cv.put("personInCharge", txn.getPerson_Charge());
if (rowcount == 0) {
db.insert("Information", null, cv);
Toast.makeText(Setting_Page.this, "Add successfully", Toast.LENGTH_SHORT).show();
} else {
db.update("Information",cv,null,null);
Toast.makeText(Setting_Page.this, "Updated successfully", Toast.LENGTH_SHORT).show();
}
db.close();
}
- 请注意,以上是原则代码,尚未经过测试,因此可能包含错误。
另一种方法(也许有人会说正确的方法)是在一个或多个列上创建一个 UNIQUE(索引)约束,然后使用insertWithonConflict
with CONFLICT_REPLACE(这相当于SQL INSERT OR REPLACE .......
)。
推荐阅读
- c++ - 如何删除最新添加的书?
- javascript - MongoDB Node.js 脚本实现
- google-sheets - Google 表格:当单元格 B2 不为空时,将数据向下移动一行或在数据上方添加一行
- c# - ASP.NET Core 2.x 默认为不存在路由
- akka - 为什么停止演员会增加 CPU 使用率?
- compiler-errors - 从方法内的模式匹配返回时,在当前范围内找不到关联类型
- css - 如何让 ng-grid 像 domReady 一样适合宽度
- javascript - 当更改类的代码遥不可及时如何触发类更改事件
- php - Symfony 4 包含来自不同目录的另一个项目
- node.js - node-rdkafka 使用 REST API 发布消息