Android Volley并同时发出两个请求,以将数据传递到下一个活动

时间:2018-06-20 13:02:36

标签: android asynchronous async-await android-volley

我是Android开发的新手,因此以下问题是: 我需要发出两个REST请求才能从两个不同的来源获取数据,然后传递给我的下一个Activity。我该怎么办?

ArrayList<T> data1 = GetDataFromSource1();
 ArrayList<T> data2 = GetDataFromSource2();

有没有像C#中那样的异步等待概念?

2 个答案:

答案 0 :(得分:0)

您可以使用排球库用法示例:

String url = "http://www.google.com/humans.txt";

RequestFuture<String> future = RequestFuture.newFuture();
StringRequest request = new StringRequest(Request.Method.GET, url, future, future)
mRequestQueue.add(request);

String result = future.get(); // this line will block

要设置参数,您可以执行以下操作

StringRequest sr = new StringRequest(Request.Method.GET,url,
  new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
      Log.e("HttpClient", "success! response: " + response.toString());
    }
  },
  new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
      Log.e("HttpClient", "error: " + error.toString());
    }
  })
  {
    @Override
    protected Map<String,String> getParams(){
      Map<String,String> params = new HashMap<String, String>();
      params.put("user","YOUR USERNAME");
      params.put("pass","YOUR PASSWORD");
      return params;
    }
  };
可以找到{p> documentaion here

答案 1 :(得分:0)

这是在活动之间传递ArrayList的答案。
您可以在您的对象类中实现Parcelable。

public class Currency implements Parcelable {

public static final Parcelable.Creator<Currency> CREATOR = new Parcelable.Creator<Currency>() {
    public Currency createFromParcel(Parcel in) {
        return new Currency(in);
    }

    public Currency[] newArray(int size) {
        return new Currency[size];
    }
};

...
@Override
public int describeContents() {
    return 0;
}

//Order must be the same as read
@Override
public void writeToParcel(Parcel out, int flags) {
    out.writeLong(code);
    out.writeString(name);
    out.writeString(swiftSymbol);
    out.writeString(symbol);
}

//Order must be the same as write
private void readFromParcel(Parcel in) {
    code = in.readLong();
    name = in.readString();
    swiftSymbol = in.readString();
    symbol = in.readString();
}

然后您可以像这样传递它;

Intent intent = new Intent(YourActivity.this,TargetActivity.class);
intent.putParcelableArrayListExtra(tagOne,data1);
intent.putParcelableArrayListExtra(tagTwo,data2);
startActivity(intent);