15

我有一种方法可以更新 SQLite 数据库并将其放入 AsyncTask 中,以使其更快、更可靠。

但是,更新数据库需要两条数据。一个是整数,另一个是此处显示的 PrimaryKeySmallTank 类的对象。

在 AsyncTask 的 doInBackground 方法的参数中使用 params 数组,我可以传入一个 Integer,但是如果我有两种不同类型的数据呢?

如果整数存储在 int...params[0] 中,我无法在 params[1] 中存储不同类型的对象,那么对此可以做些什么呢?

我想传递给 AsyncTask 的对象

public class PrimaryKeySmallTank {

int contractNumber;
int customerCode;
int septicCode;
String workDate;
int workNumber;

}

我正在使用的 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
4

3 回答 3

44

您应该为此创建一个构造函数。

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;
  }
}

使用它

new UpdateInfoAsyncTask(10,"hi").execute();
于 2013-08-01T09:20:59.677 回答
6

只需在异步任务的构造函数中传递所需的对象,然后在 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;
    }
}

在您的代码中传递所需的对象:

new myAsyncTask(new PrimaryKeySmallTank (1,1,1,"hi",1).execute();
于 2013-08-01T09:26:58.473 回答
4

你也可以尝试这样的事情:

private class xyz extends AsyncTask<Object, Void, String> {

@Override
protected String doInBackground(Object... objects) {

Long abc = (Long)objects[0];
String pqr = (String)objects[1];
.
.
.

只是一个简单的评论。这样,需要指出的是,不能传递原始数据(因为原始数据不能存储为对象)。对于原始数据,唯一的方法是让包装器(如整数、布尔值等)像往常一样转换。例如,

int i = (Integer) objects[0];
于 2014-03-30T08:18:47.713 回答