2011-10-31 99 views
1

我一直在使用Callable,但現在我需要函數在call方法中使用參數。我知道這不是call的能力,所以我該如何做到這一點?傳遞android函數使用參數

我目前有(錯誤):

AsyncTask async = new MyAsyncTask(); 
async.finished(new Callable(param) { 
    // the function called during async.onPostExecute; 
    doSomething(param); 
}); 
async.execute(url); 

MyAsyncTask:

... 
@Override 
protected void onPostExecute(JSONObject result) { 
    //super.onPostExecute(result); 
    if(result != null) { 
     try { 
      this._finished.call(result); // not valid because call accepts no params 
     } catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 
} 

public void finished(Callable<Void> func) { 
    this._finished = func; 
} 
... 

回答

5

如果您param最終的變數,你可以參考它從Callable內:

final String param = ...; 
async.finished(new Callable() { 
    // the function called during async.onPostExecute; 
    doSomething(param); 
}); 

你必須這樣做,當你創建Callable雖然 - 你不能在稍後給它的價值。如果你出於某種原因需要這些,你將不得不基本上使用共享狀態 - 一些「持有者」,Callable可以訪問它,並且可以在執行Callable之前將值設置爲它。這很可能只是爲MyAsyncTask本身:

final MyAsyncTask async = new MyAsyncTask(); 
async.finished(new Callable() { 
    // the function called during async.onPostExecute; 
    doSomething(async.getResult()); 
}); 
async.execute(url); 

然後:

private JSONObject result; 
public JSONObject getResult() { 
    return result; 
} 

@Override 
protected void onPostExecute(JSONObject result) { 
    this.result = result; 
    if(result != null) { 
     try { 
      this._finished.call(); 
     } catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 
} 
+0

OMG它是***喬恩Skeet ***又名* SOB的勒布朗詹姆斯*。我花了我一秒的時間才知道你在用代碼做什麼,但現在我明白了 - 它像一個冠軍。 – Jacksonkr

0

我做了一個新的類像這樣

import java.util.concurrent.Callable; 

public abstract class ParamCallable<T> implements Callable<T> { 
    public String Member; // you can add what you want here, ints, bools, etc. 
} 

然後,所有你需要做的就是

ParamCallable<YourType> func = new ParamCallable<YourType>() { 
    public YourType call() { 
     // Do stuff. 
     // Reference Member or whatever other members that you added here. 
     return YourType; 
    } 
} 

然後當你打電話給它時,你可以設置你的數據,並致電()

func.Member = value; 
func.call();