0

I want to get the list of videos from Youtube channel.

You will see below the class to connect to Youtube and my Activity that interacts with this class. I get an exception "java.lang.RuntimeException: Unable to start activity VideoListActivity" when calling YouTube.Search.List.execute();

I am new in android, so I think there is a stupid mistake. Please help to find it, or maybe suggest the another way to get data from Youtube.

YoutubeConnector class

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;

    }
}

VideoListActivity class

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) 
Alex Moiseenkov
  • 49
  • 1
  • 10

2 Answers2

1

You need to run the YoutubeConnector.search outside of onCreate() in an Async Thread. This basically means that the method is stalling the program and will cause the program to crash or hang. To fix, create a new class called Search for example:

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));
     }
}

Hopefully this will work :). If it does not, just post the error, and we'll get back. Good luck!

0

It looks like the problem is coming from a NetworkOnMainThreadException. Check out this example. Hope it helps!

Community
  • 1
  • 1
Mr. DROP TABLE
  • 334
  • 2
  • 9