how to pass in two different data types to AsyncTask, Android

前端 未结 3 1876
醉酒成梦
醉酒成梦 2021-01-04 04:34

i have a method that does an SQLite database update and put this inside of an AsyncTask to make it faster and more reliable.

however there are two pieces of data tha

相关标签:
3条回答
  • 2021-01-04 05:01

    You should create a constructor for that.

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

    To use it

    new UpdateInfoAsyncTask(10,"hi").execute();
    
    0 讨论(0)
  • 2021-01-04 05:01

    you can also try something like this :

    private class xyz extends AsyncTask<Object, Void, String> {
    
    @Override
    protected String doInBackground(Object... objects) {
    
    Long abc = (Long)objects[0];
    String pqr = (String)objects[1];
    .
    .
    .
    

    Just a simple remark. In this way, it should be pointed out that you can not pass the primitive data (because the primitives can not be stored as an Object). For a primitive data the only way is to have the wrappers (like to Integer, Boolean etc.) converted then as usual. For example,

    int i = (Integer) objects[0];
    
    0 讨论(0)
  • 2021-01-04 05:24

    Just pass the required object in the constructor of your async task and later use this object in doinBackground().You can create constructor and pass the your object in the following way:

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

    In your code pass the required object:

    new myAsyncTask(new PrimaryKeySmallTank (1,1,1,"hi",1).execute();
    
    0 讨论(0)
提交回复
热议问题