java - 如何保留我设置的值以便可以返回它?安卓

标签 java android

这是我能想到的最好的标题,但是如果不看代码,我的问题有点难以解释。我添加了一些评论来解释发生了什么。这是我的代码:

private Movie APICallTwo(final String ID)
    {
        Movie found;//want to return this

        OkHttpClient client2 = new OkHttpClient();
        String urlforID = "https://movie-database-imdb-alternative.p.rapidapi.com/?i=" + ID + "&r=json";
        final Request request = new Request.Builder()
                .url(urlforID)
                .get()
                .addHeader("x-rapidapi-host", "movie-database-imdb-alternative.p.rapidapi.com")
                .addHeader("x-rapidapi-key", "")//deleted the key for obvious reasons
                .build();
        client2.newCall(request).enqueue(new Callback()
        {
            @Override
            public void onFailure(Call call, IOException e)
            {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException
            {
                if(response.isSuccessful())
                {
                    String title = "";
                    String year = "";
                    String rated = "";
                    String released = "";
                    String runtime = "";
                    String genre = "";
                    String director = "";
                    String writer = "";
                    String actors = "";
                    String plot = "";
                    String imdbID = "";
                    String production = "";

                    String myResponse = response.body().string();
                    try
                    {
                        myObj = new JSONObject(myResponse);
                    }
                    catch (JSONException e)
                    {
                        e.printStackTrace();
                    }

                    try
                    {    
                        title = myObj.getString("Title");
                        year = myObj.getString("Year");
                        rated = myObj.getString("Rated");
                        released = myObj.getString("Released");
                        runtime = myObj.getString("Runtime");
                        genre = myObj.getString("Genre");
                        director = myObj.getString("Director");
                        writer = myObj.getString("Writer");
                        actors = myObj.getString("Actors");
                        plot = myObj.getString("Plot");
                        imdbID = myObj.getString("imdbID");

                        try//not all movies have production companies listen on IMDb
                        {
                            production = myObj.getString("Production");
                        }
                        catch (JSONException e)
                        {
                            production = "N/A";
                        }
                    }
                    catch (JSONException e)
                    {
                        e.printStackTrace();
                    }

                    test = new Movie(title, year, rated, released, runtime, genre, director, writer, actors, plot, imdbID, production);//test is declared as "Movie test" up in the main

//                    Log.d("in ApiCall2", "The Details for: " + ID + " are: \n" + test.printMovie());//this check works, it returns what is in test properly
                }
            }

        });
        found = test;
                            Log.d("in ApiCall2", "The Details for: " + ID + " are: \n" + found.printMovie());//this check doesn't work, says that test is null

        detailLatch.countDown();
        return found;
    }

我怎样才能得到它,以便保留抓取的信息并将其传递回调用它的地方?我知道,当在循环或另一个函数中声明某些内容时,当它离开该函数时,该函数会被遗忘,但这在这里没有意义。我没有其他想法如何解决这个问题。

最佳答案

如您所知,创建网络调用是异步的。因此,无论 View 是什么,从异步函数返回一个值到您的 Activity/fragment ,您需要创建一个适当的回调,一旦获取响应就会触发该回调。

第 1 步:创建界面

interface NetworkCallback{
    void onNetworkResponse(Movie movie); //There could be any type of object you want to return.
}

第 2 步:将 NetworkCallback 引用传递给您异步函数

private void fetchMovie(final String ID,NetworkCallback networkCallback) {
        Movie found;//want to return this

        OkHttpClient client2=new OkHttpClient();
        String urlforID="https://movie-database-imdb-alternative.p.rapidapi.com/?i="+ID+"&r=json";
        final Request request=new Request.Builder()
                .url(urlforID)
                .get()
                .addHeader("x-rapidapi-host","movie-database-imdb-alternative.p.rapidapi.com")
                .addHeader("x-rapidapi-key","")//deleted the key for obvious reasons
                .build();
        client2.newCall(request).enqueue(new Callback()
        {
            @Override
            public void onFailure(Call call,IOException e)
            {

            }

            @Override
            public void onResponse(Call call,Response response)throws IOException
            {
                if(response.isSuccessful())
                {
                    String title="";
                    String year="";
                    String rated="";
                    String released="";
                    String runtime="";
                    String genre="";
                    String director="";
                    String writer="";
                    String actors="";
                    String plot="";
                    String imdbID="";
                    String production="";

                    String myResponse=response.body().string();
                    try
                    {
                        myObj=new JSONObject(myResponse);
                    }
                    catch(JSONException e)
                    {
                        e.printStackTrace();
                    }

                    try
                    {
                        title=myObj.getString("Title");
                        year=myObj.getString("Year");
                        rated=myObj.getString("Rated");
                        released=myObj.getString("Released");
                        runtime=myObj.getString("Runtime");
                        genre=myObj.getString("Genre");
                        director=myObj.getString("Director");
                        writer=myObj.getString("Writer");
                        actors=myObj.getString("Actors");
                        plot=myObj.getString("Plot");
                        imdbID=myObj.getString("imdbID");

                        try//not all movies have production companies listen on IMDb
                        {
                            production=myObj.getString("Production");
                        }
                        catch(JSONException e)
                        {
                            production="N/A";
                        }
                    }
                    catch(JSONException e)
                    {
                        e.printStackTrace();
                    }

                    Movie movie =new Movie(title,year,rated,released,runtime,genre,director,writer,actors,plot,imdbID,production);//test is declared as "Movie test" up in the main

                    networkCallback.onNetworkResponse(movie);
//                    Log.d("in ApiCall2", "The Details for: " + ID + " are: \n" + test.printMovie());//this check works, it returns what is in test properly
                }
            }

        });
        //Log.d("in ApiCall2","The Details for: "+ID+" are: \n"+found.printMovie());//this check doesn't work, says that test is null

       // detailLatch.countDown();
    }

第 3 步:从 Activity/fragment 调用 fetchMovie。并更新 onNetworkResponse 内的 UI

    private void fetchMovie(){
        APICallTwo("YOUR_ID", new NetworkCallback() {
            @Override
            public void onNetworkResponse(Movie movie) {
                //NOW YOU RECEIVED YOUR FAVORITE MOVIE INFO
                //UPDATE YOUR UI HERE
            }
        });
    }

关于java - 如何保留我设置的值以便可以返回它?安卓,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60837946/

相关文章:

java - 从微调器中为项目设置值

java - 动态类型转换

java - 如何在底部导航 fragment (或抽屉导航)之间传递数据?

java - 从 XSD 生成代码

java - 适应递归堆栈溢出错误

android - 黑屏而不是多纹理

java - 所有聚类列的总和太长 (65927 > 65535)

android - ionic 运行android不在设备上运行应用程序

android - 下载图片并在ImageView中查看时为"decoder->decode returned false"

java - 如何处理相互交互的多个 Activity ?