Android-避免在Onresume与OnActivityResult中设置文本字段值的冲突
题
我正在编写一个Android应用程序,该应用程序允许用户维护产品列表。在EntroductData活动中,用户可以将有关产品的信息输入表单字段,然后将信息保存到SQLite DB中。 EnterProductData活动还允许用户通过条形码扫描仪应用程序启动条形码扫描,以捕获UPC代码。
我面临的问题是试图在条形码扫描活动完成并返回值后,在OnActivityResult()中设置UPC文本字段的值。最终发生的是我的onResume()方法是调用一个函数(populateFields()),该函数将文本字段的值设置为当前保存在DB中的内容。这似乎正在发生 后 称为OnActivityResult()。这意味着将扫描的UPC设置为文本字段值,仅在之后立即设置为空值。责备的代码线在其旁边的星号上发表了评论。
我想,如果我立即将扫描的UPC保存到OnActivityResult()方法中的DB,我可以避免此问题,但我认为这似乎不是最好的做法。有人可以就我应该做什么建议吗?
EnterProductData.java
public class EnterProductData extends Activity {
private Button mScanButton;
private EditText mUPC;
private Button mSaveButton;
private Long mRowId;
private DbAdapter mDbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDbHelper = new DbAdapter(this);
mDbHelper.open();
setContentView(R.layout.enter_product_data);
mUPC = (EditText) findViewById(R.id.UPC);
mScanButton = (Button) findViewById(R.id.scanButton);
mSaveButton = (Button) findViewById(R.id.saveButton);
mRowId = (savedInstanceState == null) ? null :
(Long) savedInstanceState.getSerializable(DbAdapter.KEY_PRODUCT_ROWID);
if (mRowId == null) {
Bundle extras = getIntent().getExtras();
mRowId = extras != null ? extras.getLong(DbAdapter.KEY_PRODUCT_ROWID): null;
}
populateFields();
mScanButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
IntentIntegrator.initiateScan(EnterProductData.this);
}
});
mSaveButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
setResult(RESULT_OK);
finish();
}
});
}
private void populateFields() {
if (mRowId != null) {
Cursor product = mDbHelper.fetchProduct(mRowId);
startManagingCursor(product);
mUPC.setText(product.getString(
product.getColumnIndexOrThrow(DbAdapter.KEY_UPC))); //******
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
saveState();
outState.putSerializable(DbAdapter.KEY_PRODUCT_ROWID, mRowId);
}
@Override
protected void onPause() {
super.onPause();
saveState();
}
@Override
protected void onResume() {
super.onResume();
populateFields();
}
private void saveState() {
String upc= mUPC.getText().toString();
if (mRowId == null) {
long id = mDbHelper.createProduct(mRowId, UPC);
if (id > 0) {
mRowId = id;
}
} else {
mDbHelper.updateProduct(mRowId, UPC);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode) {
case IntentIntegrator.REQUEST_CODE: {
if (resultCode != RESULT_CANCELED) {
IntentResult scanResult =
IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (scanResult != null) {
String upc = scanResult.getContents();
mUPC.setText(upc);
}
}
break;
}
}
}
}
解决方案
您可以在启动IE,onCreate中读取数据库中的值,并存储在成员变量中。在需要时更新这些值。退出应用程序时,将值存储回数据库。这不仅可以解决您的问题,还可以防止许多数据库交互。
不隶属于 StackOverflow