ListView 中显示的 Youtube 播放列表

Youtube Playlist shown in ListView(ListView 中显示的 Youtube 播放列表)

本文介绍了ListView 中显示的 Youtube 播放列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 GDATA 链接,我想在我的应用程序中使用它.此链接包含一个播放列表,我希望该播放列表显示在 ListView 中.然后,用户将选择他/她想要的视频,然后就可以使用本地 Youtube 应用在应用内播放.

I have a GDATA link that I want to use in my App. This link contains a playlist and I want that playlist to be displayed in a ListView. The user will then select the video he/she wants and will then be able to play it in side the app using the local Youtube App.

请指点我一个直观的教程.我知道 YouTube API 页面包含所有信息,但我可以对其进行正面或反面.

Please point me to a tutorial that is intuitive. I know that the YouTube API page contains all the info, but I can make heads or tails of it.

推荐答案

我希望这会给你一个想法试试这个(只是一个示例)如果你有更好的解决方案也请告诉我.

I hope this will give you an idea try this (just a sample) and if you have better solutions pls let me know too.

 package com.test.utubevdo;

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.util.ArrayList;

    import org.apache.http.HttpResponse;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.json.JSONArray;
    import org.json.JSONObject;

    import android.app.Activity;
    import android.app.Dialog;
    import android.app.ListActivity;
    import android.app.ProgressDialog;
    import android.content.Intent;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.view.ContextMenu;
    import android.view.ContextMenu.ContextMenuInfo;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.view.WindowManager;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.Button;
    import android.widget.Gallery;
    import android.widget.ListView;
    import android.widget.VideoView;


    public class AndroidThumbnailList extends Activity{
        ArrayList <YTBVideo> videos = new ArrayList<YTBVideo>();

    ProgressDialog progressDialog = null;
    VideoView vdovw_1 = null;
    String vdoURL = "";
    ListView listview = null;
    Gallery gallery = null;
    Dialog noDataAlert = null;


    Handler imageLoaderHandler = new Handler() {
        public void handleMessage(final Message msg) {
            progressDialog.dismiss();
            if(msg.what == 1){

                showErrorMessage("Communication Error", "Error Occured while retrieving the data from Youtube.
 Please try again");

            }else{
            System.out.println("videos  ::"+videos.size());
            //listview.setAdapter(new VideoViewAdapter(AndroidThumbnailList.this, videos));
            gallery.setAdapter(new VideoViewAdapter1(AndroidThumbnailList.this, videos));
            }

        }
    };



    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


         getWindow().setFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        //setContentView(R.layout.imagelist_layout);
        //listview = (ListView)findViewById(R.id.listView1);
         setContentView(R.layout.gallery_imagelist_layout);
         gallery  = (Gallery) findViewById(R.id.galleryView);

         gallery.setOnItemClickListener(new OnItemClickListener() {
                public void onItemClick(AdapterView parent, View view, int position, long id) {
                    Intent videoDisplayIntent =  new Intent("com.test.utubevdo.VIEW_VIDEO");
                    System.out.println("String.valueOf(view.getTag())  :::"+((YTBVideo)videos.get(position)).getId());
                    videoDisplayIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    videoDisplayIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                    videoDisplayIntent.putExtra("VIDEO_ID", ((YTBVideo)videos.get(position)).getId());
                    startActivity(videoDisplayIntent);
                }
                });
        progressDialog = ProgressDialog.show(this, "Loading Video Images", "Loading Video Images", true, false);
        //  setListAdapter(new MyThumbnaildapter(AndroidThumbnailList.this, R.layout.row, videoFileList));
    }


    /*@Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        // TODO Auto-generated method stub
        super.onCreateContextMenu(menu, v, menuInfo);

    }*/

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        try{
            DownloaderTAsk downloaderTAsk = (DownloaderTAsk) new DownloaderTAsk().execute(getApplicationContext());


        }catch (Exception e) {
            // TODO: handle exception
        }
    }


    class DownloaderTAsk extends AsyncTask{

        @Override
        protected Object doInBackground(Object... arg0) {
            // TODO Auto-generated method stub
            try{
                printVideoFEEJSONString("http://gdata.youtube.com/feeds/api/videos?alt=jsonc&q=football+-soccer&orderby=published&start-index=11&max-results=10&v=2");
                //printVideoFEEJSONString("https://gdata.youtube.com/feeds/api/videos?alt=json&q=football+-soccer&orderby=published&start-index=11&max-results=10&v=2");
                imageLoaderHandler.sendEmptyMessage(0);
            }catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();

                imageLoaderHandler.sendEmptyMessage(1);

            }
            return null;
        }
        @Override
        protected void onPostExecute(Object result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);

        }

    }



    public void printVideoFEEJSONString(String feedURL){
        BufferedReader bufferedReader = null;
        try{
            HttpClient client = new DefaultHttpClient();

            HttpGet request = new HttpGet(feedURL);
            HttpResponse response = client.execute(request);

            bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer jsonStringBuffer = new StringBuffer("");
            String line = "";
            String newLine = System.getProperty("line.separator");
            while ((line = bufferedReader.readLine()) != null) {
                jsonStringBuffer.append(line + newLine);
            }

            String appUpdatorJsonString = jsonStringBuffer.toString();
            System.out.println("YOUTUBE VIDEO FEED JSON :"+appUpdatorJsonString);

            JSONObject updaterAppJsonObject = new JSONObject(appUpdatorJsonString);
            System.out.println("YOUTUBE VIDEO FEED JSON OBJECT :"+updaterAppJsonObject);




            processYoutubeVideoFEEJSONObject(updaterAppJsonObject);



        }catch (Exception e) {
            e.printStackTrace();
            // TODO: handle exception
        }
    }


    public void processYoutubeVideoFEEJSONObject(JSONObject updaterAppJsonObject){
        JSONObject dataJSONObject = null;
        JSONArray itemsJSONArray = null;
        JSONObject itemsJSONObject = null;
        JSONObject linkJSONObject = null;
        String yvURL = "";
        YTBVideo yVideo = null;

        try{

            dataJSONObject = updaterAppJsonObject.getJSONObject("data");
            itemsJSONArray = dataJSONObject.getJSONArray("items");
            for(int i = 0; i < itemsJSONArray.length(); i++){
                yVideo = new YTBVideo();
                // for(int i = 0; i < 1; i++){
                itemsJSONObject = itemsJSONArray.getJSONObject(i);
                yVideo.setId(itemsJSONObject.getString("id"));
                yVideo.setThumbNailURL(itemsJSONObject.getJSONObject("thumbnail").getString("sqDefault"));
                yVideo.setVideoImageURL(itemsJSONObject.getJSONObject("player").getString("default"));
                yVideo.setTitle(itemsJSONObject.getString("title"));
                yvURL = itemsJSONObject.getJSONObject("player").getString("default");


                String videoURL = yvURL.substring(0,yvURL.indexOf("&"));
                vdoURL = videoURL;
                System.out.println("Youtube URL is ::"+videoURL);
                System.out.println("videoURL ::"+videoURL);
                yVideo.setThumbnailImage(preloadBitmap(yVideo));
                videos.add(yVideo);

            }

        }catch (Exception e) {
            e.printStackTrace();
            // TODO: handle exception
        }
    }



    private Bitmap preloadBitmap(YTBVideo  yTBVideo) throws MalformedURLException,IOException {
        Bitmap photoBitmap= null;
        try{

        BitmapFactory.Options  imageOptions = null;
        imageOptions = new BitmapFactory.Options();
        imageOptions.outHeight = 250;
        imageOptions.outHeight = 150;
        String FlickrPhotoPath = yTBVideo.getThumbNailURL();


        URL FlickrPhotoUrl = null;


        System.out.println("FlickrPhotoPath:::::::"+FlickrPhotoPath);
        //try {
        FlickrPhotoUrl = new URL(FlickrPhotoPath);

        HttpURLConnection httpConnection = (HttpURLConnection) FlickrPhotoUrl.openConnection();
        httpConnection.setDoInput(true);
        httpConnection.connect();
        InputStream inputStream = httpConnection.getInputStream();
        //photoBitmap = BitmapFactory.decodeStream(inputStream);
        photoBitmap = BitmapFactory.decodeStream(inputStream,null,imageOptions);
        System.out.println("photoBitmap:::::::"+photoBitmap);
        /*} catch (MalformedURLException e) {
                //e.printStackTrace();
            } catch (IOException e) {
                //e.printStackTrace();
            }*/
        }catch (Exception e) {
            // TODO: handle exception
            //showErrorMessage("communication error", "Unable to connect to Flickr Server");
            e.printStackTrace();
        }
        return photoBitmap;
    }

    protected void showErrorMessage(String messageLine1, String message)
    {       
        noDataAlert = Utiliy.getAlertMessage(getBaseContext(), this, messageLine1.toUpperCase()+":
"+message, 1);
        noDataAlert.getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
        noDataAlert.setCanceledOnTouchOutside(true);
        noDataAlert.setCancelable(true);
        Button yesButton = (Button)noDataAlert.findViewById(R.id.alert_popup_yes_button);
        yesButton.setText("  OK  ");
        yesButton.setTextSize(24);
        yesButton.setPadding(5, 5, 5, 5);
        yesButton.setVisibility(View.VISIBLE);
        yesButton.setOnClickListener(new OnClickListener(){
            public void onClick(View view){
                noDataAlert.dismiss();
                finish();
            }
        });
        noDataAlert.show();
    }
}

<小时>

 package com.test.utubevdo;

    import java.util.List;

    import com.keyes.youtube.OpenYouTubePlayerActivity;

    import android.app.Activity;
    import android.content.Intent;
    import android.content.pm.PackageManager;
    import android.content.pm.ResolveInfo;
    import android.net.Uri;
    import android.os.Bundle;

    public class DisplayYoutubeVideo extends Activity {

    String vdoID = "";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        vdoID = (String) getIntent().getExtras().get("VIDEO_ID");

        System.out.println("vdoID   :::"+vdoID);
    }
    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        startVideo(vdoID);
    }


    private void startVideo ( String videoID ) { // default youtube app
        Intent i = new Intent ( Intent . ACTION_VIEW , Uri . parse ( "vnd.youtube:" + videoID )); 
        List < ResolveInfo > list = getPackageManager (). queryIntentActivities ( i , PackageManager . MATCH_DEFAULT_ONLY ); 
        if ( list . size () == 0 ) {
            //write you own activity to display the video, if default youtube video display class is not available or else use the default class it self
            }

        System.out.println("Intent Actin :"+i.getAction());
        startActivity ( i );
    }
}

<小时>

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

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


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


    <application android:icon="@drawable/icon" android:label="@string/app_name">

  <activity android:name="com.test.utubevdo.AndroidThumbnailList"
                  android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

  <activity android:name="com.test.utubevdo.DisplayYoutubeVideo"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="com.test.utubevdo.VIEW_VIDEO" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>

</manifest> 

这篇关于ListView 中显示的 Youtube 播放列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:ListView 中显示的 Youtube 播放列表

基础教程推荐