我正在制作通过应用搜索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$1.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$000(MainActivity.java:22)
05-07 12:26:33.165 26111-26111/com.dp.videostoreadmin W/System.err: at com.dp.videostoreadmin.MainActivity$1.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.
*/
}
答案 0 :(得分:3)
主要错误实际上与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);
}
}
您可以使用此行
调用此类new YoutubeSearchAPI().execute();