我是否需要将此方法转换为一个类并扩展 AsyncTask 才能使用它?我在某处读到我不应该从 UI 线程运行 DB 操作?
如果是这样,我该怎么做呢?
这是代码ATM:
public void addNewContact() {
HashMap<String, String> queryValuesMap = new HashMap<String, String>();
queryValuesMap.put("userName", userName);
queryValuesMap.put("userEmail", userEmail);
queryValuesMap.put("userPassword", userPassword);
queryValuesMap.put("userAvatar", userAvatar);
queryValuesMap.put("userSex", userSex);
dbTools.insertUser(queryValuesMap);
dbTools.close();
}
它从我的提交按钮 onClick() 中调用。
我想我应该做的是:
private class AddNewContact extends AsyncTask <Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
try {
HashMap<String, String> queryValuesMap = new HashMap<String, String>();
queryValuesMap.put("userName", userName);
queryValuesMap.put("userEmail", userEmail);
queryValuesMap.put("userPassword", userPassword);
queryValuesMap.put("userAvatar", userAvatar);
queryValuesMap.put("userSex", userSex);
dbTools.insertUser(queryValuesMap);
dbTools.close();
} catch (Exception e) {}
return null;
}
}
然后在提交按钮 onClick() 中的 AddNewContact.execute()。
这是正确的吗?
编辑:这是在接受答案下方的讨论中实施后的工作代码:
在 onClick 中:
AddNewUserParams addNewUserParams = new AddNewUserParams();
addNewUserParams.userName = this.userName;
addNewUserParams.userEmail = this.userEmail;
addNewUserParams.userPassword = this.userPassword;
addNewUserParams.userAvatar = this.userAvatar;
addNewUserParams.userSex = this.userSex;
new AddNewContact().execute(addNewUserParams);
这是嵌套类:
private class AddNewUserParams {
String userName;
String userEmail;
String userPassword;
String userAvatar;
String userSex;
}
private class AddNewContact extends AsyncTask <AddNewUserParams, Void, Void> {
@Override
protected Void doInBackground(AddNewUserParams... params) {
try {
HashMap<String, String> queryValuesMap = new HashMap<String, String>();
queryValuesMap.put("userName", params[0].userName);
queryValuesMap.put("userEmail", params[0].userEmail);
queryValuesMap.put("userPassword", params[0].userPassword);
queryValuesMap.put("userAvatar", params[0].userAvatar);
queryValuesMap.put("userSex", params[0].userSex);
dbTools.insertUser(queryValuesMap);
dbTools.close();
} catch (Exception e) {
toastMaker.toast(net.asdqwe.activities.Signup.this, configurationz.ERROR_MESSAGES_SIGNUP_USER_NOT_CREATED, configurationz, Toast.LENGTH_LONG);
}
return null;
}
@Override
protected void onPostExecute(Void result) {
Intent signupSuccessHome = new Intent(getApplicationContext(), Home.class);
signupSuccessHome.putExtra(EXTRA_MESSAGE, userEmail);
startActivity(signupSuccessHome);
super.onPostExecute(result);
}
}