Android Developer Tutorials and Blog

Hi guys, this is a Tutorial Request to show a list of videos that a user has uploaded to their youtube channel.

YouTube has some great API‘s for using the data from their website and you can retrieve this data in a few formats including XML and JSON. This tutorial will retrieve the data using JSON-C. This gives you the information in key value pairs and having the built in JSON library in android makes it easier and cleaner than having to parse a lot of XML.

So the plan is, talk to YouTube ask them for one users uploaded videos. YouTube will then send back a JSON object that we will retrieve the videos from and shove them into a list, sound easy huh.

What we’re going to do:

Create an Activity that has a button to initiate the search and a listview to display the results

Create a new thread that will talk to youtube and retrieve the JSON

Parse the JSON into nice java objects

Pass these objects to our ListView and display on the screen

One thing to note is, within our ListView we will be showing a thumbnail of the youtube video and the title, the JSON that YouTube sends back only contains a URL to the thumbnail and not the image itself. Therefore I am going to use code from one of my previous tutorials (UrlImageView) to load the image in an asynchronous manner, this means I’ll just pass the url to the imageview and it’ll go start it’s own thread to load it from the internet and display it when it has, yay.

Ok Here … we .. go.

Lets mix it up a bit and start off with the Manifest, you’ll need to add the Internet permission yes!

Lets go ahead and create the MainActivity also, the XML is simple, it contains our Button to go search YouTube and the ListView to display the user uploaded videos when they are returned to us. The ListView is a custom ListView, this makes sense so we can customise it more without the Activity having to care what is going on. Now instead of having to worry about the adapter for the list within your activity we can do it all in our own ListView and just have the Activity call one method to initialise it. It’ll also help later on if you want to save some state when you change orientation.

Next comes the MainActivity class file. Here you want to get a reference to your ListView so you can populate it, you also react to your button click here. When the button is clicked we create a new task and start it running. This task runs on another thread and not the main one. You do not want to do blocking operations on the main thread i.e. calls to internet services. Doing heavy lifting on the main thread is the number one reason for those ‘Activity Not Responding’ errors, bad. We also create a handler here and this is used to receive our data once the task has finished.

MainActivity.java

package com.blundell.tut.ui.phone;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import com.blundell.tut.R;
import com.blundell.tut.domain.Library;
import com.blundell.tut.service.task.GetYouTubeUserVideosTask;
import com.blundell.tut.ui.widget.VideosListView;
/**
* The Activity can retrieve Videos for a specific username from YouTube</br>
* It then displays them into a list including the Thumbnail preview and the title</br>
* There is a reference to each video on YouTube as well but this isn't used in this tutorial</br>
* </br>
* <b>Note<b/> orientation change isn't covered in this tutorial, you will want to override
* onSaveInstanceState() and onRestoreInstanceState() when you come to this
* </br>
* @author paul.blundell
*/
public class MainActivity extends Activity {
// A reference to our list that will hold the video details
private VideosListView listView;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (VideosListView) findViewById(R.id.videosListView);
}
// This is the XML onClick listener to retreive a users video feed
public void getUserYouTubeFeed(View v){
// We start a new task that does its work on its own thread
// We pass in a handler that will be called when the task has finished
// We also pass in the name of the user we are searching YouTube for
new Thread(new GetYouTubeUserVideosTask(responseHandler, "blundellp")).start();
}
// This is the handler that receives the response when the YouTube task has finished
Handler responseHandler = new Handler() {
public void handleMessage(Message msg) {
populateListWithVideos(msg);
};
};
/**
* This method retrieves the Library of videos from the task and passes them to our ListView
* @param msg
*/
private void populateListWithVideos(Message msg) {
// Retreive the videos are task found from the data bundle sent back
Library lib = (Library) msg.getData().get(GetYouTubeUserVideosTask.LIBRARY);
// Because we have created a custom ListView we don't have to worry about setting the adapter in the activity
// we can just call our custom method with the list of items we want to display
listView.setVideos(lib.getVideos());
}
@Override
protected void onStop() {
// Make sure we null our handler when the activity has stopped
// because who cares if we get a callback once the activity has stopped? not me!
responseHandler = null;
super.onStop();
}
}

You then want to create your task, the task takes care of talking to YouTube and making sense of what YouTube sends you back i.e. the JSON-C response. I’ve commented this heavily as it does some interesting things. The one thing I’d note is I do not do any error checking in this tutorial. Yes it catches the errors so you won’t get a forceclose but if you start this task from your activity then sit there waiting for it to finish and reply, if it gets an error .. it won’t and your activity will need to react to that. Thats just one thing to note if you want to expand on this code.

GetYouTubeUserVideosTask.java

package com.blundell.tut.service.task;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import com.blundell.tut.domain.Library;
import com.blundell.tut.domain.Video;
import com.blundell.tutorial.util.Log;
import com.blundell.tutorial.util.StreamUtils;
/**
* This is the task that will ask YouTube for a list of videos for a specified user</br>
* This class implements Runnable meaning it will be ran on its own Thread</br>
* Because it runs on it's own thread we need to pass in an object that is notified when it has finished
*
* @author paul.blundell
*/
public class GetYouTubeUserVideosTask implements Runnable {
// A reference to retrieve the data when this task finishes
public static final String LIBRARY = "Library";
// A handler that will be notified when the task is finished
private final Handler replyTo;
// The user we are querying on YouTube for videos
private final String username;
/**
* Don't forget to call run(); to start this task
* @param replyTo - the handler you want to receive the response when this task has finished
* @param username - the username of who on YouTube you are browsing
*/
public GetYouTubeUserVideosTask(Handler replyTo, String username) {
this.replyTo = replyTo;
this.username = username;
}
@Override
public void run() {
try {
// Get a httpclient to talk to the internet
HttpClient client = new DefaultHttpClient();
// Perform a GET request to YouTube for a JSON list of all the videos by a specific user
HttpUriRequest request = new HttpGet("https://gdata.youtube.com/feeds/api/videos?author="+username+"&v=2&alt=jsonc");
// Get the response that YouTube sends back
HttpResponse response = client.execute(request);
// Convert this response into a readable string
String jsonString = StreamUtils.convertToString(response.getEntity().getContent());
// Create a JSON object that we can use from the String
JSONObject json = new JSONObject(jsonString);
// For further information about the syntax of this request and JSON-C
// see the documentation on YouTube http://code.google.com/apis/youtube/2.0/developers_guide_jsonc.html
// Get are search result items
JSONArray jsonArray = json.getJSONObject("data").getJSONArray("items");
// Create a list to store are videos in
List<Video> videos = new ArrayList<Video>();
// Loop round our JSON list of videos creating Video objects to use within our app
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// The title of the video
String title = jsonObject.getString("title");
// The url link back to YouTube, this checks if it has a mobile url
// if it doesnt it gets the standard url
String url;
try {
url = jsonObject.getJSONObject("player").getString("mobile");
} catch (JSONException ignore) {
url = jsonObject.getJSONObject("player").getString("default");
}
// A url to the thumbnail image of the video
// We will use this later to get an image using a Custom ImageView
// Found here http://blog.blundellapps.co.uk/imageview-with-loading-spinner/
String thumbUrl = jsonObject.getJSONObject("thumbnail").getString("sqDefault");
// Create the video object and add it to our list
videos.add(new Video(title, url, thumbUrl));
}
// Create a library to hold our videos
Library lib = new Library(username, videos);
// Pack the Library into the bundle to send back to the Activity
Bundle data = new Bundle();
data.putSerializable(LIBRARY, lib);
// Send the Bundle of data (our Library) back to the handler (our Activity)
Message msg = Message.obtain();
msg.setData(data);
replyTo.sendMessage(msg);
// We don't do any error catching, just nothing will happen if this task falls over
// an idea would be to reply to the handler with a different message so your Activity can act accordingly
} catch (ClientProtocolException e) {
Log.e("Feck", e);
} catch (IOException e) {
Log.e("Feck", e);
} catch (JSONException e) {
Log.e("Feck", e);
}
}
}

When the task is complete your handler is notified and the message the handler gets has a bundle attached (just like when you attach extras to an Intent). From this bundle we can retrieve the list of videos that YouTube has told us the user we searched for uploaded, in this case ‘blundellp’ me!
We’re storing each YouTube video in an object of our own called Video, this has a title, url, and thumbnail url. If you notice I like to make my objects immutable, this means you set all the fields on them in the constructor and once that has happened the fields cannot change and you can only retrieve what they are. This helps when your stepping through code and you then know crazy things can’t happen after instantiation. This isn’t always possible in practice, but it is here!

The videos are then stored in an ArrayList, which we want to pass back to our activity in the bundle. I know you remembered the List interface doesn’t implement serialisable in Java so we then wrap that list in another object which we are calling a Library, for good measure we’ll store the username we searched for in the Library as well. Again this object is immutable.

Finally in the Activity when this Library is retrieved from the task it is passed to our custom listview that uses a custom adapter to read the list, take the YouTube video title and thumbnail url and populate one list row for each video.

VideoListView.java

package com.blundell.tut.ui.widget;
import java.util.List;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ListAdapter;
import android.widget.ListView;
import com.blundell.tut.domain.Video;
import com.blundell.tut.ui.adapter.VideosAdapter;
/**
* A custom ListView that takes a list of videos to display</br>
* As you can see you don't call setAdapter you should call setVideos and the rest is done for you.</br>
* </br>
* Although this is a simple custom view it is good practice to always use custom views when you can
* it allows you to encapsulate your work and keep your activity as a delegate whenever possible</br>
* This list could be further customised without any hard graft, whereas if you had put this into the activity</br>
* it would have been a real pain to pull out further down the road.</br>
* </br>
* One example is we could switch out the adapter we are using, to something that displays scrolling images or whatever,
* and our activity never need know!</br>
*
* @author paul.blundell
*/
public class VideosListView extends ListView {
public VideosListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public VideosListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public VideosListView(Context context) {
super(context);
}
public void setVideos(List<Video> videos){
VideosAdapter adapter = new VideosAdapter(getContext(), videos);
setAdapter(adapter);
}
@Override
public void setAdapter(ListAdapter adapter) {
super.setAdapter(adapter);
}
}

The VideoAdapter uses the UrlImageView to load the thumbnails. Apart from that it is a simple view adapter.

VideoAdaper.java

package com.blundell.tut.ui.adapter;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.blundell.tut.R;
import com.blundell.tut.domain.Video;
import com.blundell.tut.ui.widget.UrlImageView;
/**
* This adapter is used to show our Video objects in a ListView
* It hasn't got many memory optimisations, if your list is getting bigger or more complex
* you may want to look at better using your view resources: http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/List14.html
* @author paul.blundell
*/
public class VideosAdapter extends BaseAdapter {
// The list of videos to display
List<Video> videos;
// An inflator to use when creating rows
private LayoutInflater mInflater;
/**
* @param context this is the context that the list will be shown in - used to create new list rows
* @param videos this is a list of videos to display
*/
public VideosAdapter(Context context, List<Video> videos) {
this.videos = videos;
this.mInflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return videos.size();
}
@Override
public Object getItem(int position) {
return videos.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// If convertView wasn't null it means we have already set it to our list_item_user_video so no need to do it again
if(convertView == null){
// This is the layout we are using for each row in our list
// anything you declare in this layout can then be referenced below
convertView = mInflater.inflate(R.layout.list_item_user_video, null);
}
// We are using a custom imageview so that we can load images using urls
// For further explanation see: http://blog.blundellapps.co.uk/imageview-with-loading-spinner/
UrlImageView thumb = (UrlImageView) convertView.findViewById(R.id.userVideoThumbImageView);
TextView title = (TextView) convertView.findViewById(R.id.userVideoTitleTextView);
// Get a single video from our list
Video video = videos.get(position);
// Set the image for the list item
thumb.setImageDrawable(video.getThumbUrl());
// Set the title for the list item
title.setText(video.getTitle());
return convertView;
}
}

That’s it! The last two files here are just for completeness, I have a custom Log class so I can control the log message that I output. Also a utility class to convert the InputStream that is retrieved from talking to YouTube into a string (because it’s actually just JSON-C).

That’s Definitely it! You now should be able to query YouTube to retrieve a JSON object, parse this JSON object into a domain object of your own, pass a list of domain objects to a view and have it display the user uploaded videos on your phone screen, magic!

I really really really recommend following a similar package structure to what is outlines in this project, it makes your code so much more maintainable in the long run and if you follow any of my other tutorials you’ll recognise the pattern and learn that, that much quicker 😉

P.s. that is a video on my YouTube channel of me attempting to grow a moustache! It was for charity, so if you could up vote it that’d be a great help.

94 thoughts on “[TUT] Show YouTube Feed for a Users Videos in a ListView ( JSON )”

Hi , this is amaaazing tuturial ,it helps me to much
but i have aproblem : in my chanel anout 100 video but it appear just 25 video how can I fix it ??
and i need the videos to arrenge according to date how I can do it ??

Sorry, but i have some errors, should i use async-task?
(ignore the X, just replaced)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
at java.net.InetAddress.lookupHostByName(InetAddress.java:385)

hi, this is a wonderful tutorial, thank you! it works perfectly ! the best one of its kind…!

i have a problem though……i replaced the channel name with another channel name – which has 200+ videos…..but the list shows only about thirty…..why so? i want ALL of the videos to be displayed…..what do i do for this?

and another question – how do i pass one video’s link to another activity through intent-extra so that i can play it in the new activity? just a little pointer would help and i’d do the rest …thanks a lot…..

Hi, the API is probably paged, so it only returns the first 30. Pagination is another tutorial all together. To pass the the link to another activity, you’ll need to set a click listener on the adapter or on an item in the view. Then just pass the Video object around

Thank you very much for this great tutorial. I really appreciated it. I wonder if there a possibility to limit the first result to 10 items (?max-results=10) with &start-index=1) and setup new buttons to fetch next 10 items within the same username channel?

How could one increase the size of the thumbnails? I attempted to set UrlImageView to android:layout_width=”80dip”
android:layout_height=”80dip” but the thumbnail did not get bigger (only the black space around it)

Hi blundell,
This tutorial is what an awesome tut I’m looking for. Thank you so much. But this is my problem: I used many values for ‘username’ in GetYouTubeUserVideoTask.java and they work great. Then I created my own channel and upload many videos onto that. When I run the project, logCat said:

10-23 02:15:15.648: E/UserFeedYouTubeTut(756): main| Feck
10-23 02:15:15.648: E/UserFeedYouTubeTut(756): org.json.JSONException: No value for items.
I check this link: https://gdata.youtube.com/feeds/api/videos?author=“+username+”&v=2&alt=jsonc (username is now my channel name), and find out that it has no items. How can I fix this?

Hi blundell,
Thank you so much for your tutorial. I solved my problem very soon. But I could not able get the videos from my youtube account. I am unable to understand how to do it. How get api access for my channel. can you please guide me. it helps me a lot.

How would you convert this to fragments using actionBarSherlock? Ive been trying for almost a week and cannot figure it out. Always some kind of error. I have correctly added actionBarSherlock as a library. Just doesnt want to seem to work inside a fragment no matter what I try. Please help.

Hello and thanks for the really good work you have made here.It is very helpfull.
I implement all this code to my app and it works brilliantly.Although today I notice that the list of the youtube video does not refresh with newer stuff altought the uploader has many new videos.
It has stacked to some video 15 days ago .
Could you help me

Your tutorial helped me! Thanks a lot! The problem I’m facing is that if there are many videos and the user scrolls down the images of the video start loading – which is understandable. But when the user scrolls back up, the images start re-loading again.

Shouldn’t it be this way that if the images have already loaded they shouldn’t be reloading again?

You could start with an in memory cache, i.e. a HashMap , becareful you could run out of phone memory fast, but this could hold the URL against the Bitmap, therefore if it is already downloaded it will be pulled from the cache else download from the net.

I have been surfing online more than three hours nowadays, but I by no
means discovered any attention-grabbing article like yours.
It’s beautiful value enough for me. In my view, if all web owners and bloggers made just right content material as you did, the web shall be a lot more helpful than ever before.

Great tutorial! I have spent countless hours trying to modifying your code but to no success. Since the release of the new youtube API i wanted to incorporate some of the features into your code. Mainly when you click on a video it will play in your app instead of prompting out of the app.

Could you create another tutorial on how to implement new youtube API?

I’ve been trying to add it to my app so i can get a base on which to work but im struggling.

I got the code errorless, and when i run it, on clicking the button on the activity_main.xml, i get a java.lang.IllegalStateException (could not execute method of activity) at android.view.View$1.onClick and the list goes on, but starts there..

Hey there. GREAT tutorial. This is the only place on the web where i could find a step-by-step tutorial about querying youtube. Even Stackoverflow answers where “you need the youtube java api” which is really really really vague to use for beginners. 10 tumbs up for you!

Hello Sir,
I have go through the code embedded with this tutorial, Show YouTube Feed for a Users Videos in a ListView ( JSON ).It is really appreciated. But sir i want to embed this code in my app but i am not able to do that because the package structures used by you are not allowing me to add my code in it. Can you simplify it.

Hi, I am new to android. I am reading this tutorial.It was nice,but i want to display the youtube videos by using gdata framework with response of xml not jsonc.
Can you please share the tutorial for displaying the videos with xml response data. Thanks in Advance…