我想从YouTube频道获取视频列表。
您将在下面看到与此类相互作用的YouTube和我的活动。我会得到一个例外" java.lang.runtimeException:无法启动活动videoListactivity "呼叫 youtube.search.list.list.execute();
我是Android的新手,所以我认为这是一个愚蠢的错误。请帮助找到它,或者建议另一种方式从YouTube获取数据。
youtubeconnector类
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.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class YoutubeConnector {
private static YouTube youtube;
private static YouTube.Search.List query;
public static final String KEY = DeveloperKey.DEVELOPER_KEY;
public static List<VideoItem> search() throws IOException {
youtube = new YouTube.Builder(new NetHttpTransport(), new JacksonFactory(), new HttpRequestInitializer() {
@Override
public void initialize(HttpRequest httpRequest) throws IOException {
}
}).setApplicationName(R.string.app_name).build();
query = youtube.search().list("id,snippet");
query.setKey(KEY);
query.setType("video");
query.setChannelId("**************");
query.setFields("items(id/videoId,snippet/title,snippet/description,snippet/thumbnails/default/url)");
SearchListResponse response = query.execute();
List<SearchResult> results = response.getItems();
List<VideoItem> items = new ArrayList<VideoItem>();
for (SearchResult result : results) {
VideoItem item = new VideoItem();
item.setTitle(result.getSnippet().getTitle());
item.setDescription(result.getSnippet().getDescription());
item.setThumbnailURL(result.getSnippet().getThumbnails().getDefault().getUrl());
item.setId(result.getId().getVideoId());
items.add(item);
}
return items;
}
}
视频抗性类
public class VideoListActivity extends ListActivity{
List<VideoItem> videoFileList;
public class VideoAapter extends ArrayAdapter{
//.....................
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
videoFileList = YoutubeConnector.search();
} catch (IOException e) {
e.printStackTrace();
}
setListAdapter(new VideoAapter(VideoListActivity.this, R.layout.list_item_video, videoFileList));
}
}
logcat
06-16 18:14:56.926 30817-30817/com.example.alex.youtubecanal W/art: Failed to find OatDexFile for DexFile /data/data/com.example.alex.youtubecanal/files/instant-run/dex/slice-slice_5-classes.dex ( canonical path /data/data/com.example.alex.youtubecanal/files/instant-run/dex/slice-slice_5-classes.dex) with checksum 0x7eb43558 in OatFile /data/data/com.example.alex.youtubecanal/cache/slice-slice_5-classes.dex
06-16 18:14:57.631 30817-30817/com.example.alex.youtubecanal I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
06-16 18:14:57.631 30817-30817/com.example.alex.youtubecanal I/System.out: (HTTPLog)-Static: isShipBuild true
06-16 18:14:57.631 30817-30817/com.example.alex.youtubecanal I/System.out: (HTTPLog)-Thread-1-786658172: SmartBonding Enabling is false, SHIP_BUILD is true, log to file is false, DBG is false
06-16 18:14:57.631 30817-30817/com.example.alex.youtubecanal I/System.out: (HTTPLog)-Thread-1-786658172: SMARTBONDING_FEATURE_ENABLED is false
06-16 18:14:57.636 30817-30817/com.example.alex.youtubecanal I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
06-16 18:14:57.636 30817-30817/com.example.alex.youtubecanal I/System.out: KnoxVpnUidStorageknoxVpnSupported API value returned is false
06-16 18:14:57.636 30817-30817/com.example.alex.youtubecanal D/AndroidRuntime: Shutting down VM
06-16 18:14:57.641 30817-30817/com.example.alex.youtubecanal E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.alex.youtubecanal, PID: 30817
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.alex.youtubecanal/com.example.alex.youtubecanal.VideoListActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3133)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3243)
at android.app.ActivityThread.access$1000(ActivityThread.java:218)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1718)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6917)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:245)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:128)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:370)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:298)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:399)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:110)
at com.android.okhttp.internal.http.DelegatingHttpsURLConnection.connect(DelegatingHttpsURLConnection.java:89)
at com.android.okhttp.internal.http.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:25)
at com.google.api.client.http.javanet.NetHttpRequest.execute(NetHttpRequest.java:93)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:981)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
at com.example.alex.youtubecanal.YoutubeConnector.search(YoutubeConnector.java:37)
at com.example.alex.youtubecanal.VideoListActivity.onCreate(VideoListActivity.java:58)
at android.app.Activity.performCreate(Activity.java:6609)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1134)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3086)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3243)
at android.app.ActivityThread.access$1000(ActivityThread.java:218)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1718)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6917)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
您需要在异步线程中运行onCreate()
外的YoutubeConnector.search
。这基本上意味着该方法正在拖延程序,并导致程序崩溃或挂起。要修复,创建一个名为搜索的新类,例如:
searchClass.java:
import android.os.AsyncTask;
import java.io.IOException;
public class Search extends AsyncTask<String, Void, Void> {
@Override
protected Void doInBackground(String... params) {
try {
videoFileList = YoutubeConnector.search();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String a){
VideoListActivity.context.updateAdapter();
}
}
videoListactivity.java:
public class VideoListActivity extends ListActivity{
static List<VideoItem> videoFileList;
static Context context;
public class VideoAapter extends ArrayAdapter{
//.....................
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Search search= new Search();
search.execute(new String[]{});
}
public void updateAdapter(ArrayList<String> list) {
setListAdapter(new VideoAapter(VideoListActivity.this,R.layout.list_item_video, videoFileList));
}
}
希望这会起作用:)。如果没有,只需发布错误,我们就会返回。祝你好运!
看起来这个问题来自networkonmainthreadexception。查看此示例。希望它有帮助!