Kev*_*vik 14 multithreading android android-asynctask
我有一个方法,它执行SQLite数据库更新并将其放在AsyncTask中,以使其更快,更可靠.
但是,更新数据库需要两个数据.一个是Integer,另一个是此处显示的PrimaryKeySmallTank类的对象.
在AsyncTask的doInBackground方法的参数中使用params数组,我可以传入一个Integer,但是如果我有两种不同类型的数据呢?
如果整数存储在int ... params [0]中,我不能在params [1]中存储不同的类型对象,那么可以做些什么呢?
对象我想传递给AsyncTask
public class PrimaryKeySmallTank {
int contractNumber;
int customerCode;
int septicCode;
String workDate;
int workNumber;
}
Run Code Online (Sandbox Code Playgroud)
我正在使用的AsyncTask
public class UpdateInfoAsyncTask extends AsyncTask<Integer, Void, Void>{
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
@Override
protected Void doInBackground(Integer... params) {
Integer mIntegerIn = params[0]; // this is what I want to do, example
PrimaryKeySmallTank mPrimaryKeySmallTank = params[1]; // different data type to pass in
Database db = new Database(InspectionInfoSelectionList.this);
db.openToWrite();
db.updateWorkClassificationByRow(mPrimaryKeySmallTank, mIntegerIn);
db.close();
return null;
}
} // end UpdateInfoAsyncTask
Run Code Online (Sandbox Code Playgroud)
Chi*_*hod 43
你应该为它创建一个构造函数.
public class UpdateInfoAsyncTask extends AsyncTask<Void, Void, Void>{
int intValue;
String strValue;
public UpdateInfoAsyncTask(int intValue,String strValue){
this.intValue = intValue;
this.strValue = strValue;
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
@Override
protected Void doInBackground(Void... params) {
//use intValue
//use strValue
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
使用它
new UpdateInfoAsyncTask(10,"hi").execute();
Run Code Online (Sandbox Code Playgroud)
只需在异步任务的构造函数中传递所需的对象,然后在doinBackground()中使用该对象.您可以创建构造函数并以下列方式传递您的对象:
public class MyAsyncTask extends AsyncTask<Void, Void, Void>{
PrimaryKeySmallTank tankObj;
public UpdateInfoAsyncTask(PrimaryKeySmallTank obj ){
tankObj=obj;
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
@Override
protected Void doInBackground(Void... params) {
//code and use tankObj
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
在您的代码中传递所需的对象:
new myAsyncTask(new PrimaryKeySmallTank (1,1,1,"hi",1).execute();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
13916 次 |
最近记录: |