ListView 中显示的 YouTube 播放列表

2023-12-10

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

请给我指出一个直观的教程。我知道 YouTube API 页面包含所有信息,但我可以了解其中的要点。


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

 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.\n 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()+":\n"+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> 
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ListView 中显示的 YouTube 播放列表 的相关文章

随机推荐

  • 向JTable添加加载循环

    我有一个从数据库加载数据的 JTable 因为有时数据太多 我想在Jtable内添加一个加载圆圈来通知用户数据正在加载 这是我希望的图像 这可能吗 在 Swing 中如何实现呢 PS 我不想使用进度条 我只想使用表格内的圆圈 UPDATE
  • 为什么在 LIKE 过滤器中使用下划线字符会给出所有结果?

    我写了下面的 SQL 查询LIKE健康 状况 SELECT FROM Manager WHERE managerid LIKE AND managername LIKE In the LIKE我想搜索任何下划线 但我知道我的列数据没有下划线
  • 使行延伸到 CSS 网格中的所有列

    尽管我已经指定了我希望导航延伸到哪些列 但我一直无法让我的导航完全延伸到我的列上 如果您可以看一下我的代码并指出我的错误太棒了 这是浏览器中 HTML 文件的图像 body margin 0 padding 0 container max
  • 将 datetimepicker 连接到 angularjs

    我需要使用 Angular Bootstrap 创建一个包含日期和时间的输入字段 我找到了这个日期时间选择器它看起来正是我需要的 一个字段中的日期和时间 并阻止用户错误的版本 我写了一个指令 datepickers 启动了 但它改变了视图
  • 为什么分配给 True/False 不能按我的预期工作?

    作为回答另一个问题的一部分 我编写了以下代码 乍一看其行为似乎很奇怪 print True outputs true True False print True outputs false True True print True outp
  • 谷歌地图反应没有出现

    我正在尝试使用google map react 但是当我尝试渲染它时 什么也没有出现 我错过了什么吗 import GoogleMap from google map react import React Component from re
  • 如何在Google App Engine中导入Google Cloud语音识别(python)

    我想在我的 Google App Engine python 应用程序上使用 google cloud 库 自从我在本地安装了这个库以来 我的所有测试都在我的本地工作 我原以为 GAE 默认支持它 但它是不支持 这是我得到的错误 from
  • 如何使用 Selenium RC 来验证我们的服务器端重定向(301、302)?

    我们的 Apache 配置中有很多重定向 我想用 Selenium 自动测试重定向 这导致我遇到了一些问题 调用 URL 但在重定向页面上断言 重定向后检查浏览器的URL 检查响应标头 以确定重定向类型 301 302 也许 Seleniu
  • 如何从一个类运行多个控制台?

    我有三个课程 它们都有不同的作品 但我需要一起运行它们 当我在一个类中运行所有这些时 我只得到一个控制台 并且无法更改此控制台 我想要的是在一个类中运行它们并查看每个控制台 我怎样才能做到这一点 更清楚地说 when I run first
  • 类型擦除的通用包装器是如何实现的?

    我需要为我自己的结构实现一个类型擦除包装器 非常类似于SequenceOf GeneratorOf等等 所以我开始尝试重新实现标准SequenceOf myself 我刚刚复制并粘贴了声明SequenceOf 将其重命名为MySequenc
  • 无法访问 Android 中的传感器

    我正在编写一个指南针应用程序 但由于某种原因无法访问所需的传感器 我已经实施了SensorEventListener以这种方式连接并注册我的传感器 sensorManager SensorManager getSystemService C
  • 为什么枚举已安装的 MSI 包如此慢?

    这是此的后续question 我使用这个稍微修改过的脚本来枚举所有已安装的 MSI 包 strComputer Set objWMIService GetObject winmgmts impersonationLevel imperson
  • 比较 2 个 CSV 文件并写下所有差异

    我有 3 个包含用户信息的 CSV 文件 CSV1 是所有非活动用户的 主 列表 CSV2 是需要停用的当前用户列表 CSV3 是需要激活的用户列表 我想要的是有一个可以从另一个脚本 创建 CSV2 3 的脚本 调用的 PowerShell
  • 在 C# 的类构造函数中调用异步方法[重复]

    这个问题在这里已经有答案了 目前我正在使用 C 开发一个通用应用程序 在应用程序中 我使用 sqlite 作为数据库 正如您现在可能的那样 它具有异步方法 我有一个带有一些 null 属性的类 我将使用从数据库获取的数据来填充它们 但它应该
  • 如何使用phonegap/jQueryMobile从OpenCart获取JSON格式的产品

    无论如何 是否可以使用 Ajax JavaScript jQuery 从我的 OpenCart 商店中从 PhoneGap 移动应用程序获取 JSON 格式的产品目录 OpenCart 允许这样的事情吗 欢迎任何想法或代码 OcJoy 进展
  • 使用 Json 数据改造 POST 方法收到错误代码 400:错误请求

    我想使用 JSON 数据 提供 JSON 作为 JsonObject 在 Retrofit 中调用 POST 方法 Magento REST API 为此 我按照邮递员的要求拨打电话 对我来说工作得很好 我已经完成了 android 部分如
  • 重写我的分数文本文件以确保它只有最后 4 个分数 (python)

    以前 在 SO 用户的帮助下 我已经能够找到如何使用字典中的 maxlength 属性在 Python 文档中存储最多 4 个键 现在 我想走得更远 下面是一个包含所有内容的文本文件recent我的参与者 戴夫 杰克和亚当 Jack 10
  • 检索插入行的索引

    我试图使我正在处理的项目的数据库表保持良好和规范化 但我遇到了问题 我试图弄清楚如何在表中插入一行 然后找出 auto incremented 的值id列设置为以便我可以将附加数据插入到另一个表中 我知道有这样的功能mysql insert
  • 通常是什么导致haskell中出现“错误C堆栈溢出”

    Hugs Haskell 实现中 错误 C 堆栈溢出 的常见原因是什么 如果您习惯于通常进行尾递归分解的函数式语言 则可能会出现这种情况 假设你有一个函数 sum go 0 where go accum accum go accum x x
  • ListView 中显示的 YouTube 播放列表

    我有一个GDATA我想在我的应用程序中使用的链接 此链接包含一个播放列表 我希望该播放列表显示在ListView 然后 用户将选择他 她想要的视频 然后就可以使用本地 Youtube 应用程序在应用程序中播放该视频 请给我指出一个直观的教程