实现这些ListActivity以在URL中显示视频

时间:2014-06-03 06:34:22

标签: android video android-intent android-listview

我需要实现这些ListActivity.java

ListActivity.java:

package com.sit.fth.activity;

public class ListActivity extends Activity {
    private ListView lv;
    private String[] groupArray = {"Category1", "Category2", "Category3"};
    private String[][] childArray = {{"Test Greater glory Part-3","Greater glory Part-1"},
        {"What does","SundayService ( 19_01_14 )"}, {"Greater glory Part-3", "SundayService ( 19_01_14 )Tamil"}};

    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.list1);
        lv = (ListView) findViewById(R.id.listview);

        String[] data = getIntent().getStringArrayExtra("strArray");
        AdapterView.OnItemClickListener clickListener = null;

        // If no data received means this is the first activity
        if (data == null) {
            data = groupArray;
            clickListener = new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                                        int position, long id) {
                    Intent intent = new Intent(ListActivity.this, ListActivity.class);
                    intent.putExtra("strArray", childArray[position]);
                    startActivity(intent);
                }
            };
        }

        ArrayAdapter adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, data);

        lv.setAdapter(adapter);
        lv.setTextFilterEnabled(true);
        lv.setOnItemClickListener(clickListener);

     }

}  

list1.java:

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

    <ListView
        android:id="@+id/listview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

如果我单击ListView.Another ListView中显示的Category1

我的问题是,如果我点击TestGreater Glory Part-3,视频必须从网址显示。我不知道如何将ListActivity类实现到以下编码。

的strings.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
 <string name="str_video">VIDEO</string>
<string name="api_host">URL Here</string>

</resources> 

YouTubePlayActivity.java:

package com.sit.fth.activity;

public class YoutubePlayActivity extends YouTubeFailureRecoveryActivity {
    public static final String DEVELOPER_KEY = "DEVELOPER_KEY_HERE";
    private String videoId;
    private YouTubePlayerView youTubeView;
    private ActionBar actionabar;
    private int position;

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);

        setContentView(R.layout.youtube_play);

        position = getIntent().getExtras().getInt("position");

        Bundle bundle = getIntent().getExtras();
        videoId = bundle.getString("videoid");

        FrameLayout frameLayout = (FrameLayout) findViewById(R.id.youtube_view);
        youTubeView = new YouTubePlayerView(this);
        frameLayout.addView(youTubeView);
        youTubeView.initialize(DEVELOPER_KEY, this);

        ((TextView) findViewById(R.id.header_title)).setText(bundle
                .getString("title"));

        actionabar = getActionBar();
        //actionabar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        actionabar.setDisplayHomeAsUpEnabled(true);

    }

    @Override
    public void onInitializationSuccess(YouTubePlayer.Provider provider,
            YouTubePlayer player, boolean wasRestored) {
        if (!wasRestored) {
            try {
                if (videoId != null) {
                    // 2GPfZYwYZoQ
                    player.cueVideo(videoId);
                } else {
                    Toast.makeText(getApplicationContext(),
                            "Not a Valid Youtube Video", Toast.LENGTH_SHORT)
                            .show();
                }
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(),
                        "Not a Valid Youtube Video", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected YouTubePlayer.Provider getYouTubePlayerProvider() {
        return youTubeView;
    }
}

我需要实施ListActivity.java类来获取网址中显示的视频。

1 个答案:

答案 0 :(得分:1)

这是一个列出类别的应用程序(您提供)。点击某个类别后,它的视频将从JSON文件中加载,并显示为另一个ListView

点击视频时,url and title会发送到YoutubeActivity。 YoutubeActivity然后启动播放该视频的播放器。

我相信你想要更复杂的东西,但你可以很容易地添加其他功能(例如从json获取其他字段)。如果您还想要导入类别,那么您需要另一个json结构,例如array of categories - &gt; array of videos

<强> ListActivity:

package com.example.youtubecatplayer;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by Simon on 2014 Jul 08.
 */
public class ListActivity extends Activity {
    // Categories must be pre-set
    private String[] data = {"Category1", "Category2", "Category3"};
    private final String JSONUrl = "http://tfhapp.fathershouse.in/api/video.php";
    private final String TAG_VIDEOS = "videos";
    private final String TAG_CAT = "video_category";
    private final String TAG_URL = "video_url";
    private final String TAG_TITLE = "video_title";

    private List<String> videoTitles = new ArrayList<String>();
    private List<String> videoURLs = new ArrayList<String>();
    private ArrayAdapter adapter;

    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.list1);
        ListView listView = (ListView) findViewById(R.id.listview);

        Bundle extras = getIntent().getExtras();
        AdapterView.OnItemClickListener clickListener = null;

        // Category view:
        if (extras == null) {
            clickListener = new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                                        int position, long id) {
                    Intent intent = new Intent(ListActivity.this, ListActivity.class);
                    intent.putExtra("categoryName", data[position]);
                    startActivity(intent);
                }
            };
            adapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_list_item_1, data);
        }
        else { // Child view
            // Get the category of this child
            String categoryName = extras.getString("categoryName");
            if (categoryName == null)
                finish();

            // Populate list with videos of "categoryName", by looping JSON data
            new JSONParse(categoryName).execute();

            clickListener = new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                                        int position, long id) {
                    Intent intent = new Intent(ListActivity.this, YoutubeActivity.class);
                    // Send video url and title to YoutubeActivity
                    intent.putExtra("videoUrl", videoURLs.get(position));
                    intent.putExtra("videoTitle", videoTitles.get(position));
                    startActivity(intent);
                }
            };
            adapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_list_item_1, videoTitles);
        }

        listView.setAdapter(adapter);
        listView.setTextFilterEnabled(true);
        listView.setOnItemClickListener(clickListener);
    }

    private class JSONParse extends AsyncTask<String, String, JSONObject> {
        private ProgressDialog pDialog;
        private String categoryName;

        // Constructor // Get the categoryName of which videos will be found
        public JSONParse(String category) {
            this.categoryName = category;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Create a loading dialog when getting the videos
            pDialog = new ProgressDialog(ListActivity.this);
            pDialog.setMessage("Getting Videos...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
        @Override
        protected JSONObject doInBackground(String... args) {
            JSONParser jParser = new JSONParser();
            // Get JSON from URL
            JSONObject json = jParser.getJSONFromUrl(JSONUrl);
            if (json == null)
                return null;

            try {
                // Get video array
                JSONArray videos = json.getJSONArray(TAG_VIDEOS);

                // Loop all videos
                for (int i=0; i<videos.length(); i++) {
                    JSONObject video = videos.getJSONObject(i);
                    Log.e("JSON:", "cat: "+video.getString(TAG_CAT)+",title: "+video.getString(TAG_TITLE)+", url: "+video.getString(TAG_URL));
                    // Check if video belongs to "categoryName"
                    if (video.getString(TAG_CAT).equals(categoryName)) {
                        addVideo(video);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return json;
        }

        private void addVideo(JSONObject video) {
            try {
                // Add title and URL to their respective arrays
                videoTitles.add(video.getString(TAG_TITLE));
                videoURLs.add(video.getString(TAG_URL));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        protected void onPostExecute(JSONObject json) {
            // Close the "loading" dialog
            pDialog.dismiss();
            if (json == null) {
                // Do something when there's no internet connection
                // Or there are no videos to be displayed
            }
            else // Let the adapter notify ListView that it has new items
                adapter.notifyDataSetChanged();
        }
    }
}
// Example JSON video item
// {"videoid":"59","video_type":"Youtube","language":"english","date":"08 Jul 2014",
// "video_title":"What does","video_category":"Category2","video_url":"P84FGn49b4A"},

<强> YoutubeActivity:

package com.example.youtubecatplayer;

import android.app.ActionBar;
import android.os.Bundle;
import android.widget.Toast;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;
/**
 * Created by Simon on 2014 Jul 08.
 */
public class YoutubeActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener{
    public static final String DEVELOPER_KEY = "DEV_KEY";
    private String videoId;
    private ActionBar actionabar;

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.youtube_activity);

        Bundle bundle = getIntent().getExtras();
        videoId = bundle.getString("videoUrl");
        this.setTitle(bundle.getString("videoTitle"));
        //((TextView) findViewById(R.id.videoTitle)).setText(bundle.getString("videoTitle"));

        YouTubePlayerView playerView = (YouTubePlayerView)findViewById(R.id.youtubeplayerview);
        playerView.initialize(DEVELOPER_KEY, this);

        actionabar = getActionBar();
        //actionabar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        actionabar.setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player,
                                        boolean wasRestored) {
        if (!wasRestored) {
            try {
                if (videoId != null) {
                    // 2GPfZYwYZoQ
                    player.cueVideo(videoId);
                } else {
                    Toast.makeText(getApplicationContext(),
                            "Not a Valid Youtube Video", Toast.LENGTH_SHORT)
                            .show();
                }
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(),
                        "Not a Valid Youtube Video", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onInitializationFailure(YouTubePlayer.Provider provider,
                                        YouTubeInitializationResult youTubeInitializationResult) {
    }
}

<强> JSONParser:

package com.example.youtubecatplayer;
/**
 * Created by Simon on 2014 Jul 08.
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.Charset;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
    public JSONParser() {
    }

    public JSONObject getJSONFromUrl(String url) {
        InputStream input = null;
        String jsonStr = null;
        JSONObject jsonObj = null;
        try {
            // Make the request
            input = new URL(url).openStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(input,
                    Charset.forName("UTF-8")));
            StringBuilder strBuilder = new StringBuilder();
            int ch;
            while ((ch = reader.read()) != -1)
                strBuilder.append((char) ch);

            input.close();
            jsonStr = strBuilder.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
        // try parse the string to a JSON object
        try {
            jsonObj = new JSONObject(jsonStr);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }
        // return JSON String
        return jsonObj;
    }
}

注意:您需要在AndroidManifest.xml中使用互联网权限:

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

您需要在项目中实施YoutubeAPI。

  1. Download YouTube API

  2. build.gradle compile files('libs/YouTubeAndroidPlayerApi.jar')

  3. 编辑:

    我只是尝试重新创建这个项目,它运作得很好。这是我的布局和清单文件,也许它们会给你带来麻烦。

    Android Manifest:

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.simas.myapplication" >
        <uses-permission android:name="android.permission.INTERNET" />
        <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
            <activity
                android:name=".ListActivity"
                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=".YoutubeActivity"
                android:label="@string/app_name" >
            </activity>
    
        </application>
    
    </manifest>
    

    <强> youtube_activity.xml:

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                  android:orientation="vertical"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent">
    
        <com.google.android.youtube.player.YouTubePlayerView
            android:id="@+id/youtubeplayerview"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    
    </LinearLayout>
    

    <强> list1.xml:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:paddingBottom="@dimen/activity_vertical_margin"
        tools:context=".ListActivity">
    
        <ListView
            android:id="@+id/listview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    
    </RelativeLayout>
    

    不要忘记更改开发人员密钥,否则您会看到播放器初始化问题。