【问题标题】:How does one correctly override AsyncTask onPostExecute() method? [duplicate]如何正确覆盖 AsyncTask onPostExecute() 方法? [复制]
【发布时间】:2015-12-30 18:47:02
【问题描述】:

我正在使用AsyncTask 进行 API 调用。我的AsyncTask 应该向面部识别服务发送两张图像,并返回服务的 JSON 响应中包含的Double

但是,关于onPostExecute(),我不断收到此错误:

Error:(44, 5) error: method does not override or implement a method from >a supertype

我不明白为什么会出现此错误。

这是我的AsyncTask 子类:

public class KairosManager extends AsyncTask<Bitmap, Void, JSONObject> {

    // MainActivity Context
    private Context mContext;

    public KairosManager(Context context){
        mContext = context;
    }


    // Call Kairos API and return JSONObject response to doInBackground()

    public JSONObject compareImages(Bitmap bm1, Bitmap bm2){
        // Kairos Call here!
        return jsonResponse;
    }


    // Take both images in the array and call compareImages which calls the service.

    @Override
    protected JSONObject doInBackground(Bitmap... params){
        Bitmap bm1 = params[0];
        Bitmap bm2 = params[1];
        return compareImages(bm1, bm2);
    }


    // Parse JSONObject response and return 'confidence' value to MainActivity

    @Override
    protected Double onPostExecute(JSONObject result){
        try{
            JSONArray TwoImages = result.getJSONArray(IMAGES);
            JSONObject image = TwoImages.getJSONObject(0);
            JSONObject subimage = image.getJSONObject(TRANSACTION);
            Double confidence = subimage.getDouble(CONFIDENCE);
            Log.d("Percent: ", confidence.toString());
            return confidence;
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

}

这是我的 MainActivity:

    Bitmap bm1 = ((BitmapDrawable) image1.getDrawable()).getBitmap();
    Bitmap bm2 = ((BitmapDrawable) image2.getDrawable()).getBitmap();

    KairosManager myKairosManager = new KairosManager(this);
    myKairosManager.execute(bm1, bm2);

【问题讨论】:

  • 三个点 ... 表示可以将零个或多个对象(或它们的数组)作为该函数的参数传递。
  • 它被称为可变参数。您可以将其用作对象数组。在您的情况下是 ArrayList 的数组

标签: java android android-asynctask


【解决方案1】:

您的doInBackground 方法应返回Double 类型的对象。

【讨论】:

  • 现在 doInBackground 返回 JSON 响应,onPostExecute 解析它并返回感兴趣的值。您是否建议 doInBackground 也应该解析 JSONObject 并返回感兴趣的值?那么我的 onPostExecute 将是多余的。
  • @Jacobo 将&lt;ArrayList&lt;Bitmap&gt;, Void, Double&gt; 替换为&lt;ArrayList&lt;Bitmap&gt;, Void, JSONObject&gt;,错误就会消失。
  • 我已经做了你提到的改变。现在我只需要弄清楚如何将 Double 发送回 MainActivity,但这是另一回事。感谢您的帮助!
  • 使用 Java 接口和回调。
  • 我只需要 TextView.setText(confidence.toString());我可以直接从 AsyncTask 类执行此操作,还是需要使用接口和回调将置信度发送回 MainActivity 和那里的 setText?
猜你喜欢
  • 2015-05-08
  • 2011-11-13
  • 2015-09-16
  • 1970-01-01
  • 2016-03-07
  • 2011-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多