[TUT] Show YouTube Feed for a Users Videos in a ListView ( JSON )

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!

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.blundell.tut"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".ui.phone.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

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.

MainActivity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="getUserYouTubeFeed"
        android:text="Get YouTube Feed for &apos;blundellp&apos;" />

    <com.blundell.tut.ui.widget.VideosListView
        android:id="@+id/videosListView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</LinearLayout>

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.blundell-apps.com/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!

Video.java

package com.blundell.tut.domain;

import java.io.Serializable;

/**
 * This is a representation of a users video off YouTube
 * @author paul.blundell
 */
public class Video implements Serializable {
	// The title of the video
	private String title;
	// A link to the video on youtube
	private String url;
	// A link to a still image of the youtube video
	private String thumbUrl;
	
	public Video(String title, String url, String thumbUrl) {
		super();
		this.title = title;
		this.url = url;
		this.thumbUrl = thumbUrl;
	}

	/**
	 * @return the title of the video
	 */
	public String getTitle(){
		return title;
	}

	/**
	 * @return the url to this video on youtube
	 */
	public String getUrl() {
		return url;
	}

	/**
	 * @return the thumbUrl of a still image representation of this video
	 */
	public String getThumbUrl() {
		return thumbUrl;
	}
}

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.

Library.java

package com.blundell.tut.domain;

import java.io.Serializable;
import java.util.List;

/**
 * This is the 'library' of all the users videos
 * 
 * @author paul.blundell
 */
public class Library implements Serializable{
	// The username of the owner of the library
	private String user;
	// A list of videos that the user owns
	private List<Video> videos;
	
	public Library(String user, List<Video> videos) {
		this.user = user;
		this.videos = videos;
	}

	/**
	 * @return the user name
	 */
	public String getUser() {
		return user;
	}

	/**
	 * @return the videos
	 */
	public List<Video> getVideos() {
		return videos;
	}
}

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.blundell-apps.com/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).

Log.java

package com.blundell.tutorial.util;

import android.content.res.Resources;
import android.content.res.Resources.NotFoundException;
import android.os.Message;

/**
 * A simple Log wrapper so that we have more control</br>
 * Here we can turn off logging for a live build or do other custom logging things
 * @author paul.blundell
 */
public class Log {

	private static final boolean live = false;
	
	private static final String TAG = "UserFeedYouTubeTut";

	public static void d(String msg){
		d(msg, null);
	}
	
	public static void d(String msg, Throwable e){
		if(!live)
			android.util.Log.d(TAG, Thread.currentThread().getName() +"| "+ msg, e);
	}
	
	public static void i(String msg){
		i(msg, null);
	}
	
	public static void i(String msg, Throwable e){
		if(!live)
			android.util.Log.i(TAG, Thread.currentThread().getName() +"| "+ msg, e);
	}
	
	public static void e(String msg){
		e(msg, null);
	}
	
	public static void e(String msg, Throwable e){
		if(!live)
			android.util.Log.e(TAG, Thread.currentThread().getName() +"| "+ msg, e);
	}

	public static String identifyMessage(Resources res, Message msg) {
		try{ 
			return res.getResourceEntryName(msg.what); 
		} 
		catch(NotFoundException ignore){ 
			return "not found";
		}
	}	
}

StreamUtils.java

package com.blundell.tutorial.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;

public class StreamUtils {

	/**
	 * A helper method to convert an InputStream into a String
	 * @param inputStream
	 * @return the String or a blank string if the IS was null
	 * @throws IOException
	 */
	public static String convertToString(InputStream inputStream) throws IOException {
		if (inputStream != null) {
			Writer writer = new StringWriter();

			char[] buffer = new char[1024];
			try {
				Reader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 1024);
				int n;
				while ((n = reader.read(buffer)) != -1) {
					writer.write(buffer, 0, n);
				}
			} finally {
				inputStream.close();
			}
			return writer.toString();
		} else {
			return "";
		}
	}
}

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!

Here’s the Search User Feed YouTube Tutorial Project Eclipse Source Files <---

It is also mirrored on GitHub, feel free to make changes: https://github.com/blundell/YouTubeUserFeed

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

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

  1. thanks. it is perfectly fine but i want the thumbnails to be arranged in horizontal list view …. any help will be greatly appreciated . cheers ….

  2. 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?

    That would be a great improvement.

  3. 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)

    1. The thumbnails will be the size that the youtube server api sends you them at. You can stretch them in the app but they might not look to good like this android:scaleType="fitXY"

  4. 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?

  5. 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.

  6. 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.

    1. It should not be affected by ActionBar Sherlock. If you want to use this in a fragment it should just be the same, but likely where you pass context as ‘this’ you would want to pass ‘getActivity()’.

  7. Thanks for the great tutorial!

    but there is one problem: I don’t get all videos of the channel. The channel has over 100 videos and I just get 26 of them. In addition I want the newest video on the top. How can I do this?

    1. Perhaps the channel has requested they are not allowed on mobile? Newest on the top would have to be done using a Comparator on your List of objects.

  8. Hi blundell,
    This is the great tutorial …

    Thanks for your sharing..

    Could you help me to set the size of youtube thumbnail?

    I really need to bigger than current image..

    Thank you

  9. How to load the listview without pressing the button. I want to load it automatically. Which code to move from the button press into onCreate ? can you pls explain

  10. 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

  11. how to get videos from Playlist ?
    I tried but I get the following error

    org.json.JSONException: Value Playlist of type java.lang.String cannot be converted to JSONObject
    org.json.JSON.typeMismatch(JSON.java:111)
    org.json.JSONObject.(JSONObject.java:158)
    org.json.JSONObject.(JSONObject.java:171)
    com.blundell.tut.service.task.GetYouTubeUserVideosTask.run(GetYouTubeUserVideosTask.java:64)
    java.lang.Thread.run(Thread.java:856)

    Line 64 in GetYouTubeUserVideoTask activity is :

    JSONObject json = new JSONObject(jsonString);

    the playlist link I tried to get is :
    https://gdata.youtube.com/feeds/api/playlists/PL5ErH2bHcHAn1JYoQJKcMgfo_C9IrW0jK&v=2&alt=json

    even I tried to change
    String title = jsonObject.getString(“title”);
    to:
    String title = jsonObject.getJSONObject(“video”).getString(“title”);

  12. How to load the listview without pressing the button. I want to load it automatically. Please help anyone?!!

  13. Hey..your tutorial is awesome. But I want to play the video when you click it. Can you make a tutorial for that following this tutorial?

  14. Blundell…whoever you are…You’re a genius. Thanks so much for these tutorials they are the best and only tutorial I was able to find online…

  15. Hi,

    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?

    1. Using the convertView to not reload the image when it is already saved, or adding some image caching would fix this for you.

        1. 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.

  16. 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.

  17. 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?

  18. i really liked your tutorial a lot i am stuck at one place could you please help me i need array of youtube urls in my main activity could you help me please

  19. Hi there, great tutorial!

    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..

    Could you nudge me in the right direction ?

    Thanks.

    1. Have you declared the onClick method in your layout XML file? And does this match exactly to the name of the method in your Activity?

      1. I think i got it, but shouldnt the app be runnable on Android 4+ ?

        Even on your version, if you put “android:targetSdkVersion=”16″ ” in the manifest, when you click the Refresh button, the app shuts down.

        It throws a “networkOnMainThreadException”.

    2. Yes, well you already done it, i didn’t change it:

      android:onClick=”getUserYouTubeFeed”

      public void getUserYouTubeFeed(View v){

  20. Hi,

    Your tutorial is really great. But I have one question: how can I make it faster? I tried with Holder, but then thumbnails and title were shuffled as I scrolled fast. Do you have any ideas?

    1. As you’re requesting data for a playlist you need to get one more JSON object: video, i.e. instead of:

      String title = jsonObject.getString(“title”);

      use:
      String title = jsonObject.getJSONObject(“video”).getString(“title”);

  21. 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!

  22. 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.

    Thanx in advance!!!!!!

  23. just wondering, how do I add an extra Intent activity, so when I click the items on list view, the video will pop up and play in the next activity? thanks

    1. In another activity, you would start an Intent to open your new Activity, add the Video as an Intent extra and then call the original Intent from your new Activity.

  24. 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… :)