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

By blundell  

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.


79 Comments

  1. vineel
    Posted July 7, 2014 at 10:04 am | Permalink | Reply

    Thank you!!!It works Perfectly without a single change.

  2. raman singh bains
    Posted June 13, 2014 at 6:33 am | Permalink | Reply

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

  3. anu
    Posted May 16, 2014 at 6:23 am | Permalink | Reply

    thanks for sharing this.
    i want to add hashmap to this how can i add it.

  4. Eno
    Posted April 14, 2014 at 2:17 pm | Permalink | Reply

    Nice tuts here. How can i set up a progress dialog while the videos are loading

  5. YdniwindY
    Posted March 19, 2014 at 10:08 am | Permalink | Reply

    Cant thank you enuf, this is exactly what im looking for. Respect!!!

  6. A.M.
    Posted February 24, 2014 at 12:11 pm | Permalink | Reply

    Q-GLuydiMe4 youtube video id is not working

  7. Valdimárr Olaf
    Posted February 6, 2014 at 3:21 pm | Permalink | Reply

    I have used your example but I have trouble showing more than one item in the listView:

    http://stackoverflow.com/questions/21590231/android-java-listview-populated-with-xml-data-using-arraylist-only-displays

  8. SELASSI
    Posted January 29, 2014 at 12:58 am | Permalink | Reply

    Finaly i have found it Great job

  9. Amani Swann
    Posted December 13, 2013 at 8:46 pm | Permalink | Reply

    How could one refresh the listview with a new list of videos? I’m attempting to do so and failing miserably…

    http://stackoverflow.com/questions/20575376/properly-using-adapter-notifydatasetchanged-to-reload-a-listview

  10. Posted December 4, 2013 at 9:30 pm | Permalink | Reply

    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.

  11. Amani Swann
    Posted December 3, 2013 at 7:32 pm | Permalink | Reply

    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)

  12. Yuri
    Posted October 22, 2013 at 12:16 pm | Permalink | Reply

    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?

    • blundell
      Posted December 7, 2013 at 10:15 pm | Permalink | Reply

      Hmm I guess channels are different to usernames? Don’t know sorry

  13. raja
    Posted September 29, 2013 at 9:31 pm | Permalink | Reply

    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.

    • blundell
      Posted October 6, 2013 at 4:38 pm | Permalink | Reply

      You may need to do YouTube OAuth and sign in to get that information?

  14. ADevelop
    Posted September 4, 2013 at 1:11 pm | Permalink | Reply

    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.

    • blundell
      Posted September 15, 2013 at 11:27 am | Permalink | Reply

      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()’.

  15. deka91
    Posted September 3, 2013 at 1:41 am | Permalink | Reply

    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?

    • blundell
      Posted September 15, 2013 at 11:28 am | Permalink | Reply

      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.

  16. Posted August 23, 2013 at 9:55 am | Permalink | Reply

    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

    • blundell
      Posted September 15, 2013 at 11:33 am | Permalink | Reply

      I think this is just set in the list_item xml file?

  17. Posted August 21, 2013 at 8:14 am | Permalink | Reply

    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

    • blundell
      Posted September 15, 2013 at 11:34 am | Permalink | Reply

      new Thread(new GetYouTubeUserVideosTask(responseHandler, "blundellp")).start();

  18. Dimitris Mimis
    Posted August 20, 2013 at 4:28 pm | Permalink | Reply

    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

    • blundell
      Posted September 15, 2013 at 11:35 am | Permalink | Reply

      Maybe the new videos aren’t being returned in the JSON response yet, have you checked?

  19. Moe Hammad
    Posted July 17, 2013 at 7:40 am | Permalink | Reply

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

    • blundell
      Posted August 3, 2013 at 9:40 pm | Permalink | Reply

      think I answered this on StackOverflow, you just need to change the json you parse.

      • kim
        Posted August 15, 2013 at 2:03 pm | Permalink | Reply

        hello, How can you do that? please can you send me the link? or code?

  20. PLS HELP!!!
    Posted June 19, 2013 at 7:26 am | Permalink | Reply

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

    • blundell
      Posted June 28, 2013 at 10:08 pm | Permalink | Reply

      move the code from the button press into onCreate

  21. Janice
    Posted June 17, 2013 at 4:25 am | Permalink | Reply

    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?

    • blundell
      Posted June 28, 2013 at 10:09 pm | Permalink | Reply

      I will take a look

  22. captin
    Posted May 8, 2013 at 1:50 am | Permalink | Reply

    hi, it works now but videos don’t play in my emulator? does emulator play it?

  23. captin
    Posted April 13, 2013 at 4:44 pm | Permalink | Reply

    hey…how can I use this one if the videos I want to show are from a channel of the application in YouTube

    • blundell
      Posted April 18, 2013 at 11:24 am | Permalink | Reply

      I don’t think it makes a difference if it is on a channel, it is still a youtube video with a url

  24. Alfred
    Posted March 28, 2013 at 11:41 am | Permalink | Reply

    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…

  25. Posted March 8, 2013 at 10:36 am | Permalink | Reply

    Hey
    how can I open the video onclick the pirticular listview

  26. Ara
    Posted February 8, 2013 at 8:15 pm | Permalink | Reply

    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?

    • blundell
      Posted February 13, 2013 at 9:47 am | Permalink | Reply

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

      • Thiago
        Posted August 26, 2013 at 3:41 pm | Permalink | Reply

        I’m having the same problem, how can I solve? I do not know where to start

        • blundell
          Posted September 15, 2013 at 11:31 am | Permalink | Reply

          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.

  27. Phillip
    Posted January 29, 2013 at 10:45 am | Permalink | Reply

    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.

    • blundell
      Posted January 29, 2013 at 11:02 am | Permalink | Reply

      why thank you Phillllip your 3 hours of surfing amazes me, how is the land of spam?

  28. chan
    Posted January 17, 2013 at 12:47 am | Permalink | Reply

    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?

  29. Posted January 16, 2013 at 7:48 am | Permalink | Reply

    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

    • blundell
      Posted January 16, 2013 at 9:49 am | Permalink | Reply

      make a stackoverflow question

  30. Joao
    Posted January 8, 2013 at 9:16 pm | Permalink | Reply

    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.

    • blundell
      Posted January 9, 2013 at 9:45 am | Permalink | Reply

      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?

      • Joao
        Posted January 9, 2013 at 3:32 pm | Permalink | Reply

        If you want i could send you the whole error somewhere (e-mail, pastebin?)

      • Joao
        Posted January 9, 2013 at 3:35 pm | Permalink | Reply

        Here it is on Pastebin:

        http://pastebin.com/dhXDffjH

      • Joao
        Posted January 10, 2013 at 3:05 am | Permalink | Reply

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

        • blundell
          Posted January 10, 2013 at 9:29 am | Permalink | Reply

          Ah thanks, I will check that out

    • Joao
      Posted January 9, 2013 at 3:30 pm | Permalink | Reply

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

      android:onClick=”getUserYouTubeFeed”

      public void getUserYouTubeFeed(View v){

  31. Kamil
    Posted January 5, 2013 at 11:17 am | Permalink | Reply

    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?

    • blundell
      Posted January 7, 2013 at 9:22 am | Permalink | Reply

      What do you want to be faster? Surely the bottleneck is your internet connection speed.

  32. himanshu
    Posted December 16, 2012 at 10:33 am | Permalink | Reply

    Thanks man u save my so much time…thanks a lot again and keeping up…

  33. Yuvi
    Posted December 14, 2012 at 5:22 pm | Permalink | Reply

    hi, I tried with this link https://gdata.youtube.com/feeds/api/playlists/2B3B8DDAE8F71C46?v%E2%80%8C%E2%80%8B=2&alt=json
    but I am always getting

    Execption in catch block provided by you..
    12-14 17:15:36.949: E/Feck(975): No value for entry

    Please tell me whats wrong..

    • Kamil
      Posted January 5, 2013 at 11:13 am | Permalink | Reply

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

  34. Yuvi
    Posted December 2, 2012 at 8:22 am | Permalink | Reply

    Hi, your tut is awesome..
    Can you please tell me how to get JSON of this type of youtube urls:

    http://gdata.youtube.com/feeds/api/playlists/2B3B8DDAE8F71C46

    Thanks,
    Yuvi

  35. Pasha
    Posted November 15, 2012 at 10:53 am | Permalink | Reply

    Hi,

    I am not able to click on video list, please guide me.

    Regards,
    Pasha

    • blundell
      Posted November 16, 2012 at 9:27 am | Permalink | Reply

      Perhaps you have took focus off it, or need to add the clickable attribute. It works normally.

  36. Posted November 2, 2012 at 11:02 am | Permalink | Reply

    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!

  37. Shweta Aggarwal
    Posted October 28, 2012 at 1:33 am | Permalink | Reply

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

    • blundell
      Posted October 28, 2012 at 1:19 pm | Permalink | Reply

      What are you trying that you can’t do?

  38. lee
    Posted September 10, 2012 at 11:54 am | Permalink | Reply

    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

    • blundell
      Posted September 13, 2012 at 7:20 am | Permalink | Reply

      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.

  39. sekhar
    Posted June 23, 2012 at 7:27 am | Permalink | Reply

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

  40. Posted May 28, 2012 at 6:39 am | Permalink | Reply

    Dude, I love your work! I’m years out of England, so thanks for the Jeremy Kyle video links, & feck is now a word in my language again :o)

    • blundell
      Posted May 28, 2012 at 6:55 am | Permalink | Reply

      Haha feckin great!

  41. Posted February 25, 2012 at 1:22 am | Permalink | Reply

    Thanks a lot for sharing this with all of us you really understand what you are talking about! Bookmarked

6 Trackbacks

  1. [...] Basically what I tried was implementing the threading that is used here: http://blog.blundell-apps.com/show-youtube-user-videos-in-a-listview/ [...]

  2. [...] So for the tutorial you can switch in a SAX parser or an XmlPullParser the choice is up to you, as I’ve said in this scenario I won’t recommend either as you should use the JSON feed which is much faster and lighter for mobile. [...]

  3. [...]Show YouTube Feed for a Users Videos in a ListView[...]

Post a Comment

Your email is never shared. Required fields are marked *

*
*