Reputation: 163
can you guys help me to check where is the problem? I put a loop for the LastTxnNo, But it won't increase automatically. This is initialize database.
dbHelper = new dbOpenHelper(this);
mSQLiteHelper = new dbOpenHelper(this);
mModels = new ArrayList<>();
mAdapter = new settingAdapter(this, R.layout.row_setting, mModels);
listView1.setAdapter(mAdapter);
I have two tables, This is the 'Donation_Details' table, the TxnNo should be 'A0010001' or '0001'
and this is the 'Information' table
'Donation_Details' TxnNo should be 'Information' unitcode+lastTxnNo, means TxnNo should 'A0010001'. and when i click the button, the lastTxnNo will increase, and it will change to 'A0010002'. But I think I missed some logic.
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();
}
}
});
Upvotes: 0
Views: 59
Reputation: 37404
You have declared the variable inside method which is getting the value from preference
so every time the new local variable(redeclare with button press) get value 0
from preference so either
i
outside method int i = app_preferences.getInt("key", 0);
i++; // no need of i = ++i;
editor.putInt("key",i);
editor.commit(); // save value into preference
or use
// declare i outside method
private int i = 0;
... someMethod(){
Db_Save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// ... code
i++;
// ... code
}
});
}
Upvotes: 2