如何从一个方法返回2个值并在一个类中使用这两个值?

时间:2018-02-07 09:55:22

标签: java android return microsoft-cognitive

我正在尝试使用Microsoft提供的这些代码,但是我想要结合他们制作的两个功能。一个是分析图像,一个是检测名人。但是,我在如何从一个函数返回2个值时遇到困难。 这是处理方法......

private String process() throws VisionServiceException, IOException {
    Gson gson = new Gson();
    String model = "celebrities";

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    bitmapPicture.compress(Bitmap.CompressFormat.JPEG, 100, output);
    ByteArrayInputStream inputStream = new ByteArrayInputStream(output.toByteArray());


    AnalysisResult v = this.client.describe(inputStream, 1);
    AnalysisInDomainResult m = this.client.analyzeImageInDomain(inputStream,model);

    String result = gson.toJson(v);
    String result2 = gson.toJson(m);

    Log.d("result", result);

    return result, result2;
}

将2个结果与此方法结合起来......

    @Override
protected void onPostExecute(String data) {
    super.onPostExecute(data);

    mEditText.setText("");
    if (e != null) {
        mEditText.setText("Error: " + e.getMessage());
        this.e = null;
    } else {
        Gson gson = new Gson();
        AnalysisResult result = gson.fromJson(data, AnalysisResult.class);
        //pang detect ng peymus...
        AnalysisInDomainResult result2 = gson.fromJson(data, AnalysisInDomainResult.class);

        //decode the returned result
        JsonArray detectedCelebs = result2.result.get("celebrities").getAsJsonArray();
        if(result2.result != null){
            mEditText.append("Celebrities detected: "+detectedCelebs.size()+"\n");
            for(JsonElement celebElement: detectedCelebs) {
                JsonObject celeb = celebElement.getAsJsonObject();
                mEditText.append("Name: "+celeb.get("name").getAsString() +", score" +
                        celeb.get("confidence").getAsString() +"\n");
            }
        }else {
            for (Caption caption: result.description.captions) {
                mEditText.append("Your seeing " + caption.text + ", confidence: " + caption.confidence + "\n");
            }
            mEditText.append("\n");
        }


       /* for (String tag: result.description.tags) {
            mEditText.append("Tag: " + tag + "\n");
        }
        mEditText.append("\n");
        mEditText.append("\n--- Raw Data ---\n\n");
        mEditText.append(data);*/
        mEditText.setSelection(0);
    }
}

提前致谢!

3 个答案:

答案 0 :(得分:6)

你可以用。参数是两个对象,所以你可以放一切

  final Pair<String, String> pair = Pair.create("1", "2");
  String a = pair.first;
  String b = pair.second;

答案 1 :(得分:4)

只需使用Bundle

即可
 Bundle bundle = new Bundle();
        bundle.putString("key_one", "your_first_value");
        bundle.putString("key_two", "your_second_value");
        return bundle;

你可以在Bundle中添加不同类型的多个值。在这种情况下,你的方法的返回类型应该是Bundle。

答案 2 :(得分:0)

AbstractMap#SimpleEntry(或Java-9 Map#entry

您始终可以通过Arrays.asList(one, two)

返回两个值