你们可以帮我检查问题出在哪里吗?我为 LastTxnNo 设置了一个循环,但不会自动增加。这是初始化数据库。
dbHelper = new dbOpenHelper(this);
mSQLiteHelper = new dbOpenHelper(this);
mModels = new ArrayList<>();
mAdapter = new settingAdapter(this, R.layout.row_setting, mModels);
listView1.setAdapter(mAdapter);
我有两个表,这是“ Donation_Details”表,TxnNo应该为“ A0010001”或“ 0001”
这是“信息”表
'Donation_Details'TxnNo应该是'Information'单位代码+ lastTxnNo,表示 TxnNo应该为“ A0010001”。当我单击按钮时,lastTxnNo将增加,并且将更改为“ A0010002”。但是我想我错过了一些逻辑。
Db_Save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Model txn = new Model();// initialize your model class first
SettingModel txnSec = new SettingModel();
BigDecimal paidAmt = new BigDecimal(D_Amount.getText().toString()).setScale(2, RoundingMode.HALF_UP);
txn.setName(D_Name.getText().toString());
txnSec.setLastTxnNo(D_Txn.getText().toString());
txn.setTxnDate(Select_Date.getText().toString());
txn.setAmount(paidAmt);
txn.setDescription1(D_Description.getSelectedItem().toString());
txn.setDescription2(Ds_Description.getText().toString());
try {
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("name", txn.getName());
cv.put("TxnNo", String.format("%04d", i));
cv.put("TxnDate", txn.getTxnDate());
cv.put("Amount", txn.getAmount().toPlainString());
cv.put("Description1", txn.getDescription1());
cv.put("Description2", txn.getDescription2());
db.insert("Donation_Details", null, cv);
db.close();
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(Donation_Page.this);
SharedPreferences.Editor editor = app_preferences.edit();
int i = app_preferences.getInt("key", 0);
i = ++i;
txnSec.setLastTxnNo(i + "");
SQLiteDatabase dbSec = dbHelper.getWritableDatabase();
ContentValues cvSec = new ContentValues();
cvSec.put("TxnNo", String.format("%04d", i));
editor.putInt("key", i).commit();
dbSec.insert("Information", null, cvSec);
dbSec.close();
Toast.makeText(Donation_Page.this, "Add successfully", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
答案 0 :(得分:2)
您已经声明了方法内部的变量,该方法正在从preference
获取值,因此每次新的局部变量(通过按下按钮进行声明)都从首选项获取值0
,所以要么
i
int i = app_preferences.getInt("key", 0);
i++; // no need of i = ++i;
editor.putInt("key",i);
editor.commit(); // save value into preference
或使用
// declare i outside method
private int i = 0;
... someMethod(){
Db_Save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// ... code
i++;
// ... code
}
});
}