通过 android 应用程序搜索 Youtube 视频

Search Youtube video through android app

我正在制作通过该应用程序搜索 Yoututbe 视频的应用程序。但它在 SearchListResponse searchResponse = search.execute(); 上抛出异常 如何解决这个问题。请帮助

下面是我在搜索执行期间引发的异常

    05-07 12:26:33.163 26111-26111/com.dp.videostoreadmin W/System.err: android.os.NetworkOnMainThreadException
05-07 12:26:33.164 26111-26111/com.dp.videostoreadmin W/System.err:     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
05-07 12:26:33.164 26111-26111/com.dp.videostoreadmin W/System.err:     at java.net.InetAddress.lookupHostByName(InetAddress.java:431)
05-07 12:26:33.164 26111-26111/com.dp.videostoreadmin W/System.err:     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
05-07 12:26:33.164 26111-26111/com.dp.videostoreadmin W/System.err:     at java.net.InetAddress.getAllByName(InetAddress.java:215)
05-07 12:26:33.164 26111-26111/com.dp.videostoreadmin W/System.err:     at com.android.okhttp.internal.Network.resolveInetAddresses(Network.java:29)
05-07 12:26:33.164 26111-26111/com.dp.videostoreadmin W/System.err:     at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:188)
05-07 12:26:33.164 26111-26111/com.dp.videostoreadmin W/System.err:     at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:157)
05-07 12:26:33.164 26111-26111/com.dp.videostoreadmin W/System.err:     at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:100)
05-07 12:26:33.164 26111-26111/com.dp.videostoreadmin W/System.err:     at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:357)
05-07 12:26:33.164 26111-26111/com.dp.videostoreadmin W/System.err:     at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:340)
05-07 12:26:33.164 26111-26111/com.dp.videostoreadmin W/System.err:     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:330)
05-07 12:26:33.164 26111-26111/com.dp.videostoreadmin W/System.err:     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
05-07 12:26:33.164 26111-26111/com.dp.videostoreadmin W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:437)
05-07 12:26:33.164 26111-26111/com.dp.videostoreadmin W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:114)
05-07 12:26:33.164 26111-26111/com.dp.videostoreadmin W/System.err:     at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.connect(DelegatingHttpsURLConnection.java:89)
05-07 12:26:33.164 26111-26111/com.dp.videostoreadmin W/System.err:     at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java)
05-07 12:26:33.164 26111-26111/com.dp.videostoreadmin W/System.err:     at com.google.api.client.http.javanet.NetHttpRequest.execute(NetHttpRequest.java:93)
05-07 12:26:33.164 26111-26111/com.dp.videostoreadmin W/System.err:     at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:981)
05-07 12:26:33.164 26111-26111/com.dp.videostoreadmin W/System.err:     at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
05-07 12:26:33.165 26111-26111/com.dp.videostoreadmin W/System.err:     at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
05-07 12:26:33.165 26111-26111/com.dp.videostoreadmin W/System.err:     at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
05-07 12:26:33.165 26111-26111/com.dp.videostoreadmin W/System.err:     at com.dp.videostoreadmin.MainActivity.displaySearchResult(MainActivity.java:62)
05-07 12:26:33.165 26111-26111/com.dp.videostoreadmin W/System.err:     at com.dp.videostoreadmin.MainActivity.access[=11=]0(MainActivity.java:22)
05-07 12:26:33.165 26111-26111/com.dp.videostoreadmin W/System.err:     at com.dp.videostoreadmin.MainActivity.onClick(MainActivity.java:40)
05-07 12:26:33.165 26111-26111/com.dp.videostoreadmin W/System.err:     at android.view.View.performClick(View.java:5204)
05-07 12:26:33.165 26111-26111/com.dp.videostoreadmin W/System.err:     at android.view.View$PerformClick.run(View.java:21153)
05-07 12:26:33.165 26111-26111/com.dp.videostoreadmin W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
05-07 12:26:33.165 26111-26111/com.dp.videostoreadmin W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
05-07 12:26:33.165 26111-26111/com.dp.videostoreadmin W/System.err:     at android.os.Looper.loop(Looper.java:148)
05-07 12:26:33.165 26111-26111/com.dp.videostoreadmin W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5417)
05-07 12:26:33.165 26111-26111/com.dp.videostoreadmin W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
05-07 12:26:33.165 26111-26111/com.dp.videostoreadmin W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
05-07 12:26:33.165 26111-26111/com.dp.videostoreadmin W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

下面是我的代码

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import java.io.IOException;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.SearchListResponse;
import com.google.api.services.youtube.model.SearchResult;
import java.util.List;


public class MainActivity extends AppCompatActivity {
    private static final String YOUTUBE_API_KEY = "AIzaSyCxmfKGyNqlQIEtY0XWxGzC4QHX08BWmks";
    EditText searchText;
    Button submit;
    private static YouTube youtube;
    private static final long NUMBER_OF_VIDEOS_RETURNED = 25;

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

        searchText = (EditText) findViewById(R.id.editText);
        submit = (Button) findViewById(R.id.submit);

        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                displaySearchResult();
            }
        });
    }

    private void displaySearchResult() {

        try {

             youtube = new YouTube.Builder(new NetHttpTransport(), new JacksonFactory(), new HttpRequestInitializer() {
                public void initialize(HttpRequest request) throws IOException {
               }
            }).setApplicationName("VideoStoreAdmin").build();

            YouTube.Search.List search = youtube.search().list("id,snippet");
            search.setKey(YOUTUBE_API_KEY);
            search.setQ(searchText.getText().toString());
            search.setType("video");
            search.setFields("items(id/kind,id/videoId,snippet/title,snippet/publishedAt,snippet/thumbnails/default/url),nextPageToken");
            search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);

            // Call the API and print results.
            SearchListResponse searchResponse = search.execute();
            List<SearchResult> searchResultList = searchResponse.getItems();
            if (searchResultList != null) {
                Log.d("TAG",searchResultList.toString());
            }
        } catch (GoogleJsonResponseException e) {
            System.err.println("There was a service error: " + e.getDetails().getCode() + " : "
                    + e.getDetails().getMessage());
        } catch (IOException e) {
            System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }

    /*
     * Prompt the user to enter a query term and return the user-specified term.
     */



}

主要错误实际上与 youtube 无关,您正在主 UI 线程上进行不允许的网络操作。

您需要使用 AsyncTask 为 运行 单独线程进行网络操作。您的网络操作将在 doInBackground() 方法中运行。

从 API 获得响应后,您需要在 onPostExecute() 方法中进行所有 UI 更改。

注意:您不能在 doInBackground() 中执行任何 UI 更改操作。它会抛出异常。

private class YoutubeSearchAPI extends AsyncTask<Void, Void, Void>{

    @Override
    protected Void doInBackground(Void... params) {
        try {

            youtube = new YouTube.Builder(new NetHttpTransport(), new JacksonFactory(), new HttpRequestInitializer() {
                public void initialize(HttpRequest request) throws IOException {
                }
            }).setApplicationName("VideoStoreAdmin").build();

            YouTube.Search.List search = youtube.search().list("id,snippet");
            search.setKey(YOUTUBE_API_KEY);
            search.setQ(searchText.getText().toString());
            search.setType("video");
            search.setFields("items(id/kind,id/videoId,snippet/title,snippet/publishedAt,snippet/thumbnails/default/url),nextPageToken");
            search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);

            // Call the API and print results.
            SearchListResponse searchResponse = search.execute();
            List<SearchResult> searchResultList = searchResponse.getItems();
            if (searchResultList != null) {
                Log.d("TAG",searchResultList.toString());
            }
        } catch (GoogleJsonResponseException e) {
            System.err.println("There was a service error: " + e.getDetails().getCode() + " : "
                    + e.getDetails().getMessage());
        } catch (IOException e) {
            System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
        } catch (Throwable t) {
            t.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        //Do All UI Changes HERE
        super.onPostExecute(aVoid);
    }
}

你可以用这行class调用这个

new YoutubeSearchAPI().execute();