如何使用 AsyncTask 从 URL 返回单个对象

Posted

技术标签:

【中文标题】如何使用 AsyncTask 从 URL 返回单个对象【英文标题】:How to return a single object from URL with AsyncTask 【发布时间】:2020-09-21 07:30:51 【问题描述】:

我想尝试在我的 JSON 响应中返回一个对象。 这是我得到的响应,我希望应用程序只显示电影名称而不是所有内容。我希望它只返回名称,例如 "Casino" 而不是 "film_name": "Casino"

JSON 响应


    "films": [
        
            "film_id": 3139,
            "imdb_id": 112641,
            "film_name": "Casino",
            "release_dates": [
                
                    "release_date": "1995-11-28",
                    "notes": "GBR"
                
            ],
            "age_rating": [
                
                    "rating": "18 ",
                    "age_rating_image": "https://assets.movieglu.com/age_rating_logos/uk/18.png",
                    "age_advisory": "strong violence"
                
            ],
            "film_trailer": null,
            "synopsis_long": "Robert DeNiro, Sharon Stone and Joe Pesci star in director Martin Scorsese's riveting look at how blind ambition, white-hot passion and 24-karat greed toppled an empire. Las Vegas 1973 is the setting for this fact-based story about the Mob's multi-million dollar casino operation - where fortunes and lives were made and lost with a roll of the dice.",
            "images": 
                "poster": 
                    "1": 
                        "image_orientation": "portrait",
                        "region": "global",
                        "medium": 
                            "film_image": "https://image.movieglu.com/3139/003139h1.jpg",
                            "width": 199,
                            "height": 300
                        
                    
                
            
        ,
        
            "film_id": 7257,
            "imdb_id": 80455,
            "film_name": "The Blues Brothers",
            "release_dates": [
                
                    "release_date": "2009-07-24",
                    "notes": "GBR"
                
            ],
            "age_rating": [
                
                    "rating": "15 ",
                    "age_rating_image": "https://assets.movieglu.com/age_rating_logos/uk/15.png",
                    "age_advisory": ""
                
            ],
            "film_trailer": "https://trailer.movieglu.com/7257_high.mp4",
            "synopsis_long": "Jake and Elwood Blues endeavor to raise $5,000 for their childhood parrish by putting their old band back together uand taking their show on the road. While touring, they manage to wreak havoc on the entire city of Chicago and much of the midwest.",
            "images": 
                "poster": 
                    "1": 
                        "image_orientation": "portrait",
                        "region": "UK",
                        "medium": 
                            "film_image": "https://image.movieglu.com/7257/GBR_007257h0.jpg",
                            "width": 200,
                            "height": 300
                        
                    ,
                    "2": 
                        "image_orientation": "portrait",
                        "region": "global",
                        "medium": 
                            "film_image": "https://image.movieglu.com/7257/AUS_007257h0.jpg",
                            "width": 164,
                            "height": 300
                        
                    
                
            
        ,
        
            "film_id": 12486,
            "imdb_id": 94336,
            "film_name": "Withnail & I",
            "release_dates": [
                
                    "release_date": "2007-09-07",
                    "notes": "GBR"
                
            ],
            "age_rating": [
                
                    "rating": "15 ",
                    "age_rating_image": "https://assets.movieglu.com/age_rating_logos/uk/15.png",
                    "age_advisory": ""
                
            ],
            "film_trailer": null,
            "synopsis_long": "",
            "images": 
                "poster": 
                    "1": 
                        "image_orientation": "portrait",
                        "region": "UK",
                        "medium": 
                            "film_image": "https://image.movieglu.com/12486/GBR_012486h0.jpg",
                            "width": 200,
                            "height": 300
                        
                    
                
            
        ,
        
            "film_id": 279925,
            "imdb_id": 7549996,
            "film_name": "Judy",
            "release_dates": [
                
                    "release_date": "2019-10-04",
                    "notes": "GBR"
                
            ],
            "age_rating": [
                
                    "rating": "12A ",
                    "age_rating_image": "https://assets.movieglu.com/age_rating_logos/uk/12a.png",
                    "age_advisory": "scenes of drug misuse, infrequent strong language"
                
            ],
            "film_trailer": "https://trailer.movieglu.com/279925_uk_high_V3.mp4",
            "synopsis_long": "Winter 1968 and showbiz legend Judy Garland arrives in Swinging London to perform a five-week sold-out run at The Talk of the Town. It is 30 years since she shot to global stardom in The Wizard of Oz, but if her voice has weakened, its dramatic intensity has only grown. As she prepares for the show, battles with management, charms musicians and reminisces with friends and adoring fans, her wit and warmth shine through. Even her dreams of love seem undimmed as she embarks on a whirlwind romance with Mickey Deans, her soon-to-be fifth husband. Featuring some of her best-known songs, the film celebrates the voice, the capacity for love, and the sheer pizzazz of \"the world's greatest entertainer.\"",
            "images": 
                "poster": 
                    "1": 
                        "image_orientation": "portrait",
                        "region": "UK",
                        "medium": 
                            "film_image": "https://image.movieglu.com/279925/GBR_279925h0.jpg",
                            "width": 202,
                            "height": 300
                        
                    
                ,
                "still": 
                    "1": 
                        "image_orientation": "landscape",
                        "medium": 
                            "film_image": "https://image.movieglu.com/279925/279925h2.jpg",
                            "width": 300,
                            "height": 200
                        
                    
                
            
        ,
        
            "film_id": 80849,
            "imdb_id": 77631,
            "film_name": "Grease Sing-A-Long",
            "release_dates": [
                
                    "release_date": "2010-07-13",
                    "notes": "GBR"
                
            ],
            "age_rating": [
                
                    "rating": "PG ",
                    "age_rating_image": "https://assets.movieglu.com/age_rating_logos/uk/pg.png",
                    "age_advisory": ""
                
            ],
            "film_trailer": null,
            "synopsis_long": "Rydell High's most famous graduating class is going back to school. A newly restored print brings the highest-grossing musical of all time, \"Grease\" (1978), to the big screen as a sing-along. Join Danny and Sandy with your own crew of T-Birds and Pink Ladies for a carnival ride back to those amazing summer nights!",
            "images": 
                "poster": 
                    "1": 
                        "image_orientation": "portrait",
                        "region": "global",
                        "medium": 
                            "film_image": "https://image.movieglu.com/80849/080849h1.jpg",
                            "width": 200,
                            "height": 300
                        
                    
                ,
                "still": 
                    "1": 
                        "image_orientation": "landscape",
                        "medium": 
                            "film_image": "https://image.movieglu.com/80849/080849h2.jpg",
                            "width": 300,
                            "height": 200
                        
                    
                
            
        ,
        
            "film_id": 281047,
            "imdb_id": 7715070,
            "film_name": "Horrible Histories: The Movie",
            "release_dates": [
                
                    "release_date": "2019-07-26",
                    "notes": "GBR"
                
            ],
            "age_rating": [
                
                    "rating": "PG ",
                    "age_rating_image": "https://assets.movieglu.com/age_rating_logos/uk/pg.png",
                    "age_advisory": "mild comic violence, injury detail, rude humour, language"
                
            ],
            "film_trailer": "https://trailer.movieglu.com/281047_uk_high.mp4",
            "synopsis_long": "Friends, Romans, Celts lend us your ears. The all-conquering Romans rule the civilised world and that includes the stain that is Britain. While the young Emperor Nero must battle his scheming mother Agrippina for ultimate power, Celt queen Boudicca gathers an army in Britain to repel the rotten Romans. Mixed up in this battle for liberation are the teenage Atti, a reluctant Roman soldier, and Orla, a young Celt with dreams of becoming a warrior like Boudicca. Will they fall on opposite sides or forge a friendship in the chaos of Celtic-inspired rebellion?",
            "images": 
                "poster": 
                    "1": 
                        "image_orientation": "portrait",
                        "region": "UK",
                        "medium": 
                            "film_image": "https://image.movieglu.com/281047/GBR_281047h0.jpg",
                            "width": 200,
                            "height": 300
                        
                    
                ,
                "still": 
                    "1": 
                        "image_orientation": "landscape",
                        "medium": 
                            "film_image": "https://image.movieglu.com/281047/281047h2.jpg",
                            "width": 300,
                            "height": 200
                        
                    
                
            
        ,
        
            "film_id": 2129,
            "imdb_id": 45152,
            "film_name": "Singin' in the Rain",
            "release_dates": [
                
                    "release_date": "2019-10-18",
                    "notes": "GBR"
                
            ],
            "age_rating": [
                
                    "rating": "U ",
                    "age_rating_image": "https://assets.movieglu.com/age_rating_logos/uk/u.png",
                    "age_advisory": "very mild comic violence"
                
            ],
            "film_trailer": "https://trailer.movieglu.com/2129_high.mp4",
            "synopsis_long": "Gene Kelly, Debbie Reynolds and Donald O'Connor star in Singin' in the Rain, one of the greatest and most successful musicals ever filmed - filled with memorable songs, lavish routines and Kelly's fabulous song-and-dance number performed in the rain.\n\nSet during the advent of \"talkies,\" Don Lockwood  has risen to stardom during Hollywood's silent-movie era - paired with the beautiful, jealous and dumb Lina Lamont. And when Lockwood becomes attracted to young studio singer Kathy Selden, Lamont has her fired.\n\nBut with the introduction of talking pictures, Lockwood finds his career in jeopardy after audiences laugh when they hear Lamont speak in her shrill voice for the first time... until the studio decides to use Selden to dub her voice.",
            "images": 
                "poster": 
                    "1": 
                        "image_orientation": "portrait",
                        "region": "UK",
                        "medium": 
                            "film_image": "https://image.movieglu.com/2129/GBR_002129h0.jpg",
                            "width": 200,
                            "height": 300
                        
                    ,
                    "2": 
                        "image_orientation": "portrait",
                        "region": "global",
                        "medium": 
                            "film_image": "https://image.movieglu.com/2129/AUS_002129h0.jpg",
                            "width": 220,
                            "height": 300
                        
                    
                ,
                "still": 
                    "1": 
                        "image_orientation": "landscape",
                        "medium": 
                            "film_image": "https://image.movieglu.com/2129/002129h2.jpg",
                            "width": 300,
                            "height": 200
                        
                    
                
            
        ,
        
            "film_id": 6548,
            "imdb_id": 38669,
            "film_name": "The Killers (1946)",
            "release_dates": [
                
                    "release_date": "1946-09-16",
                    "notes": "GBR"
                
            ],
            "age_rating": [
                
                    "rating": "PG ",
                    "age_rating_image": "https://assets.movieglu.com/age_rating_logos/uk/pg.png",
                    "age_advisory": ""
                
            ],
            "film_trailer": null,
            "synopsis_long": "",
            "images": 
                "poster": 
                    "1": 
                        "image_orientation": "portrait",
                        "region": "UK",
                        "medium": 
                            "film_image": "https://image.movieglu.com/6548/GBR_006548h0.jpg",
                            "width": 200,
                            "height": 300
                        
                    
                
            
        ,
        
            "film_id": 4705,
            "imdb_id": 96928,
            "film_name": "Bill & Ted's Excellent Adventure",
            "release_dates": [
                
                    "release_date": "1989-08-25",
                    "notes": "GBR"
                
            ],
            "age_rating": [
                
                    "rating": "PG ",
                    "age_rating_image": "https://assets.movieglu.com/age_rating_logos/uk/pg.png",
                    "age_advisory": "Contains mild language and violence"
                
            ],
            "film_trailer": null,
            "synopsis_long": "Bill Preston and Ted Logan are two totally excellent dudes facing one most heinous history exam. With the help of Rufus an ultra-cool messenger in a time traveling phone booth, the triumphant two-some bag a bevy of historical heavy weights like the \"Bodacious Philosopher Socrates, \"One Very Excellent Barbarian\" Genghis Khan, the \"Short Dead Dude\" Napoleon and Noah's Wife Joan of Arc to stage the most hysterical high school project ever. History's about to be rewritten by two guys who can't even spell.",
            "images": 
                "poster": 
                    "1": 
                        "image_orientation": "portrait",
                        "region": "UK",
                        "medium": 
                            "film_image": "https://image.movieglu.com/4705/GBR_004705h0.jpg",
                            "width": 200,
                            "height": 300
                        
                    
                
            
        ,
        
            "film_id": 3855,
            "imdb_id": 93191,
            "film_name": "Wings of Desire",
            "release_dates": [
                
                    "release_date": "1990-10-01",
                    "notes": "GBR"
                
            ],
            "age_rating": [
                
                    "rating": "12 ",
                    "age_rating_image": "https://assets.movieglu.com/age_rating_logos/uk/12.png",
                    "age_advisory": "Contains one use of strong language"
                
            ],
            "film_trailer": null,
            "synopsis_long": "\"Wings of Desire\" is one of cinema's loveliest city symphonies. Bruno Ganz is Damiel, an angel perched atop buildings high over Berlin who can hear the thoughts fears, hopes, dreams of all the people living below. But when he falls in love with a beautiful trapeze artist, he is willing to give up his immortality and come back to earth to be with her. Made not long before the fall of the Berlin wall, this stunning tapestry of sounds and images, shot in black and white and color by the legendary Henri Alekan, is movie poetry. And it forever made the name Wim Wenders synonymous with film art.",
            "images": 
                "poster": 
                    "1": 
                        "image_orientation": "portrait",
                        "region": "UK",
                        "medium": 
                            "film_image": "https://image.movieglu.com/3855/GBR_003855h0.jpg",
                            "width": 200,
                            "height": 300
                        
                    
                ,
                "still": 
                    "1": 
                        "image_orientation": "landscape",
                        "medium": 
                            "film_image": "https://image.movieglu.com/3855/003855h2.jpg",
                            "width": 300,
                            "height": 200
                        
                    
                
            
        
    ],
    "status": 
        "count": 10,
        "state": "OK",
        "method": "filmsNowShowing",
        "message": null,
        "request_method": "GET",
        "version": "WALS_2v200",
        "territory": "UK",
        "device_datetime_sent": "2020-05-17T08:30:17.360Z",
        "device_datetime_used": "2020-05-17 08:30:17"
    

AsyncTaskClass

public class GetFilmsTask extends AsyncTask 
    //String films = "UNDEFINED";
    private TextView textView;
    StringBuilder builder = new StringBuilder();

    public GetFilmsTask(TextView textView) 
        this.textView = textView;
    

    @Override
    protected String doInBackground(Object[] objects) 
        URL url = null;
        HttpsURLConnection urlConnection = null;
        try
            url = new URL("https://api-gate2.movieglu.com/filmsNowShowing/?n=10");
            urlConnection = (HttpsURLConnection) url.openConnection();
            urlConnection.setRequestProperty("api-version", "v200");
            urlConnection.setRequestProperty("Authorization", "*****************************");
            urlConnection.setRequestProperty("client", "*******");
            urlConnection.setRequestProperty("x-api-key", "v***********************************");
            urlConnection.setRequestProperty("device-datetime", "2018-09-14T08:30:17.360Z");
            urlConnection.setRequestProperty("territory", "UK");
        catch(Exception ex)

        

        try 
            InputStream stream = new BufferedInputStream(urlConnection.getInputStream());
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
            //here is a temporary string to hold each line that is read from the reader

            String inputLine;
            while ((inputLine = bufferedReader.readLine()) != null) 
                builder.append(inputLine);
                //builder.append("film_name");
            


            /*JSONObject topLevel = new JSONObject(builder.toString());
            JSONObject filmName = topLevel.getJSONObject("film_name");
            films = filmName.getString("film_name");*/

        catch(Exception ex)
            System.out.println(ex.toString());
        
        finally 
            //closes the connection.
            urlConnection.disconnect();
        

        return null;
    

    @Override
    protected void onPostExecute(Object o) 
        textView.setText("Current Film: " + builder);
        Log.d("good", String.valueOf(builder));
    

【问题讨论】:

你绝对不想那样做;您想使用AyncTask<String, Integer, Film>,您应该将URL 传递给doInBackground(String[] urls)(而不是将其硬编码到任务中)。那么你应该使用onPostExecute(Film film) 并使用film.getTitle() 设置文本。 对不起,我不知道这应该去哪里我还在学习。我是否只需将protected String doInBackground(Object[] objects) 更改为protected Film doInBackground(String[] urls) 并创建一个名为film 的类? getTitle 是如何工作的?谢谢 【参考方案1】:

您肯定想花一些时间查看AsyncTask https://developer.android.com/reference/android/os/AsyncTaskdocumentation 以了解它的工作原理。老实说,在您余下的开发生涯中,您的大部分时间都将花在阅读 API 文档上——还要注意 AsyncTask 已被弃用。

最令人困惑的事情之一是,您正在查找电影列表,但仅将一个标题设置为文本视图,因此您想查看一些设计明智的东西。

但既然你有 JSON 并且你需要获取电影,你可能想要这样设置:

// com.example.film.Film
// Create your film class which does the work
public class Film 
    private long id;        // film_id
    private long imdbId;    // imdb_id
    private String title;   // name also where film.getTitle() comes from
    ...

您需要查看 JSON 解析,但您的代码看起来已经开始涉足(已注释掉),因此请继续进行。

现在你想创建一个 AsyncTask 来获取你的电影列表

/**
 * The generics you use here can be read about on the AsyncTask documentation page.
 * String - is going to be your String[] args for the request
 * Integer - is going to be what you use to update progress (although you can skip for now)
 * List<Film> - is going to be the response that you get from doInBackground and passed into onPostExecute.
 */
public class GetFilmsAsyncTask extends AsyncTask<String,Integer,List<Film>> 
    @Override
    protected List<Film> doInBackground(String[] objects)  
        // Use your String[] to build your URL, maybe page size, maybe filter, etc.
        return filmList;  // Parsed from Json
    

    @Override
    protected void onPostExecute(List<Film> films) 
        // Now do stuff with the film list you got
    

我猜这更接近您想要的,但仍然缺少一些东西: - 您可能希望将此数据提供给某种列表视图,而不是 TextView - 你需要查看你的 JSON 处理

【讨论】:

以上是关于如何使用 AsyncTask 从 URL 返回单个对象的主要内容,如果未能解决你的问题,请参考以下文章

如何在单个AsyncTask中访问多个URL

如何将变量从 AsyncTask 返回到 Android 中的 Google Map 活动

从 AsyncTask 返回数据到 MainActivity 的最佳方法

如果使用 Asynctask 将 URL 存储在 ArrayList 中,如何从服务器下载图像?

如何从服务器下载图像如果使用Asynctask存储在ArrayList中的URL?

如何在android的Asynctask中显示json响应[重复]