1

を使用してきましたがCallable、メソッドでパラメーターを使用する関数が必要になりましたcall。これはの機能ではないことがcallわかりました。どうすればこれを行うことができますか?

私が現在持っているもの(間違っている):

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

2 に答える 2

5

final 変数を作成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();
        }
    }
}
于 2011-10-31T20:51:13.250 に答える
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;
    }
}

そして、それを呼び出すときに、データを設定して call() を呼び出します

func.Member = value;
func.call();
于 2013-08-28T17:20:19.330 に答える