gpt4 book ai didi

java - 让第二个 okHTTP 请求等待第一个完成 Android

转载 作者:行者123 更新时间:2023-12-02 08:50:47 24 4
gpt4 key购买 nike

我尝试调用 IMDb API 2 次,第一次调用并获取该电影/节目的 ID,第二次使用该 ID 获取有关该电影/节目的所有信息,我还需要应用程序另一部分的 ID,这就是我这样做的原因。问题是第二个调用没有等待第一个调用完成。我认为这就是为什么当我尝试使用变量时变量没有更新的原因。这是我的 onCreate 方法,所有这些都发生在其中,出于显而易见的原因,我取出了一些 API key :

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.imdb_activity);

mTextViewResult = findViewById(R.id.text_view_result);

OkHttpClient client1 = new OkHttpClient();
//change the url to be generic and usable for user input
String urlforID = "https://movie-database-imdb-alternative.p.rapidapi.com/?page=1&r=json&s=Avengers";
final Request request = new Request.Builder()
.url(urlforID)
.get()
.addHeader("x-rapidapi-host", "movie-database-imdb-alternative.p.rapidapi.com")
.addHeader("x-rapidapi-key", "KEYGOESHERE")
.build();
client1.newCall(request).enqueue(new Callback()
{
@Override
public void onFailure(Call call, IOException e)
{
e.printStackTrace();
}

@Override
public void onResponse(Call call, Response response) throws IOException
{
if(response.isSuccessful())
{
String myResponse = response.body().string();
try
{
myObj = new JSONObject(myResponse);
}
catch (JSONException e)
{
e.printStackTrace();
}

try
{
myArray = myObj.getJSONArray("Search");

// responseID = new String[myArray.length()];//might have to subtract 1

for(int i = 0; i < myArray.length(); i++)
{
JSONObject obj1 = myArray.getJSONObject(i);
responseID[i] = obj1.getString("imdbID");
// Log.d("id","the id that was just put in was: " + responseID[i]);
}
}
catch(JSONException e)
{
e.printStackTrace();
}

imdb_activity.this.runOnUiThread(new Runnable()
{
@Override
public void run()
{
//new ReadJsonForID().execute();
Log.d("id", "The id is: " + responseID[0]);
mTextViewResult.setText(responseID[0]);
}
});
}
}
});
//this is where call 2 would happen but it is not saving the variable how it should
Log.d("id", "The id is after finish: " + mTextViewResult.getText());

最佳答案

您可以使用java.util.concurrent包中的CountDownLatch类。在第一次调用中,countDownLatch 被实例化,在第二次调用中,您等待 CountDownLatch。这可能需要将第二个任务放入 AsyncTask 中。

关于java - 让第二个 okHTTP 请求等待第一个完成 Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60792549/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com