Youtube video for a videoview

0

I need to pass a video through the link into my android app, I tried this code:

String video="http://www.youtube.com/embed/76JpysFZ2VM";
        Uri uri= Uri.parse(video);


        vid1.setVideoURI(uri);
        vid1.start();

Complete code:

package com.eu.agendamarinhagrande;


import android.app.ProgressDialog;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.StrictMode;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;

import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.VideoView;

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


public class Index extends AppCompatActivity {


    // Progress Dialog
    private ProgressDialog pDialog;

    // Creating JSON Parser object
    // JSONParser jParser = new JSONParser();

    int a;


    // products JSONArray

    public TextView descricao1;
    public TextView descricao2;
    public TextView descricao3;
    public TextView descricao4;
    public TextView descricao5;
    public TextView descricao6;
    public TextView videodescricao1;
    public TextView videodescricao2;
    public TextView videodescricao3;
    public TextView videodescricao4;
    public TextView videodescricao5;
    public TextView videodescricao6;
    public TextView videodescricao7;

    public ImageView img1, img2, img4 , img3, img5 , img6;
    public VideoView vid1;
    ListView lista;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);

        }
        setContentView(R.layout.single_post);
        descricao1 = (TextView) findViewById(R.id.tvdescricao);
        descricao2 = (TextView) findViewById(R.id.tvdescricao2);
        descricao3 = (TextView) findViewById(R.id.tvdescricao3);
        descricao4 = (TextView) findViewById(R.id.tvdescricao4);
        descricao5 = (TextView) findViewById(R.id.tvdescricao5);
        descricao6 = (TextView) findViewById(R.id.tvdescricao6);
        videodescricao1 = (TextView) findViewById(R.id.tvdescricaovideo1);
        videodescricao2 = (TextView) findViewById(R.id.tvdescricaovideo2);
        videodescricao3 = (TextView) findViewById(R.id.tvdescricaovideo3);
        videodescricao4 = (TextView) findViewById(R.id.tvdescricaovideo4);
        videodescricao5 = (TextView) findViewById(R.id.tvdescricaovideo5);
        videodescricao6 = (TextView) findViewById(R.id.tvdescricaovideo6);
        videodescricao7 = (TextView) findViewById(R.id.tvdescricaovideo7);
        img1 = (ImageView) findViewById(R.id.img1);
         VideoView vid1=(VideoView) findViewById(R.id.videoView);
        img2 = (ImageView) findViewById(R.id.img2);
        img3 = (ImageView) findViewById(R.id.img3);
        img4 = (ImageView) findViewById(R.id.img4);
        img5 = (ImageView) findViewById(R.id.img5);
        img6 = (ImageView) findViewById(R.id.img6);
        String descricao = getIntent().getExtras().getString("descricao");
        String imagens = getIntent().getExtras().getString("imagens");

        String[] img = imagens.split(";");



        String video="http://www.youtube.com/embed/76JpysFZ2VM";
        Uri uri= Uri.parse(video);

        System.out.println("URI"+uri);
        vid1.setVideoURI(uri);
        vid1.start();


        int i;
        String[] s = descricao.split("Imagem [0-5]+");
        for (i = 0; i < s.length; i++) {
            if (i == 0) {
            if (img.length >= 1) {

                    descricao1.setText(s[i]);


                    URL url = null;
                    try {
                        url = new URL("http://www.cm-mgrande.pt" + img[0]);
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    }

                    try {
                        InputStream input = url.openConnection().getInputStream();
                        Bitmap bmp = BitmapFactory.decodeStream(input);
                        input.close();
                        BufferedReader in = new BufferedReader(
                                new InputStreamReader(url.openStream()));
                        in.close();
                        img1.setImageBitmap(bmp);

                    } catch (IOException e) {
                        e.printStackTrace();


                    }


                }
            }  if (i == 1) {
            descricao2.setText(s[i]);
            if (img.length >= 2) {



                    URL url = null;
                    try {
                        url = new URL("http://www.cm-mgrande.pt" + img[1]);
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    }

                    try {

                        InputStream input = url.openConnection().getInputStream();
                        Bitmap bmp = BitmapFactory.decodeStream(input);
                        input.close();
                        BufferedReader in = new BufferedReader(
                                new InputStreamReader(url.openStream()));
                        in.close();
                        img2.setImageBitmap(bmp);

                    } catch (IOException e) {
                        e.printStackTrace();


                    }


                }


            }
            if (i == 2) {
                descricao3.setText(s[i]);
            if (img.length >= 3) {


                    {


                        URL url = null;
                        try {
                            url = new URL("http://www.cm-mgrande.pt" + img[2]);
                        } catch (MalformedURLException e) {
                            e.printStackTrace();
                        }

                        try {

                            InputStream input = url.openConnection().getInputStream();
                            Bitmap bmp = BitmapFactory.decodeStream(input);
                            input.close();
                            BufferedReader in = new BufferedReader(
                                    new InputStreamReader(url.openStream()));
                            in.close();
                            img3.setImageBitmap(bmp);

                        } catch (IOException e) {
                            e.printStackTrace();


                        }
                    }
                }
            }if (i == 3) {
                descricao4.setText(s[i]);
                if (img.length >= 4) {



                        URL url = null;
                        try {
                            url = new URL("http://www.cm-mgrande.pt" + img[3]);
                        } catch (MalformedURLException e) {
                            e.printStackTrace();
                        }

                        try {

                            InputStream input = url.openConnection().getInputStream();
                            Bitmap bmp = BitmapFactory.decodeStream(input);
                            input.close();
                            BufferedReader in = new BufferedReader(
                                    new InputStreamReader(url.openStream()));
                            in.close();
                            img4.setImageBitmap(bmp);

                        } catch (IOException e) {
                            e.printStackTrace();


                        }
                    }
                }
            if (i == 4)

            {
            descricao5.setText(s[i]);
            if (img.length >= 5) {



                    URL url = null;
                    try {
                        url = new URL("http://www.cm-mgrande.pt" + img[4]);
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    }

                    try {

                        InputStream input = url.openConnection().getInputStream();
                        Bitmap bmp = BitmapFactory.decodeStream(input);
                        input.close();
                        BufferedReader in = new BufferedReader(
                                new InputStreamReader(url.openStream()));
                        in.close();
                        img5.setImageBitmap(bmp);

                    } catch (IOException e) {
                        e.printStackTrace();


                    }
                }
            }if (i == 5)

            {
            descricao6.setText(s[i]);
            if (img.length >= 6) {



                    URL url = null;
                    try {
                        url = new URL("http://www.cm-mgrande.pt" + img[5]);
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    }

                    try {

                        InputStream input = url.openConnection().getInputStream();
                        Bitmap bmp = BitmapFactory.decodeStream(input);
                        input.close();
                        BufferedReader in = new BufferedReader(
                                new InputStreamReader(url.openStream()));
                        in.close();
                        img6.setImageBitmap(bmp);

                    } catch (IOException e) {
                        e.printStackTrace();


                    }
                }


            }


        }


    }
}

I did not succeed. Could someone help me?

I need a code not too big and easy to understand!

    
asked by anonymous 02.07.2015 / 14:03

2 answers

2

Well after several attempts I found two ways to solve the problem one of the ways is to use the Youtube Android Player api, that there is installation of libraries and everything else but it is the one in my opinion the recommended.

I did not use it because it involved a few lines of code so I figured out what to do through a WebView is the example here:

mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setPluginState(PluginState.ON);
mWebView.loadUrl("http://www.youtube.com/embed/" + videoID + "?autoplay=1&vq=small");
mWebView.setWebChromeClient(new WebChromeClient());
    
03.07.2015 / 15:55
0

This is a specific class, that works , for this type of application. Here's how it works, in the comments and adapt to your code. Note that there are not only 3 lines that make a video run correctly:

public class MeuVideoViewActivity extends Activity {
    private VideoView videoView;
    private MediaController mController;
    private Uri uriYouTube;

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

        //VideoView
        setContentView(R.layout.activity_video_view);
        videoView = (VideoView) findViewById(R.id.videoView);
        mController = new MediaController(this);
        videoView.setMediaController(mController);
        videoView.requestFocus();

        /*
        CASO O VIDEO ESTEJA NO SEU DISPOSITIVO

        Uri uri = Uri.parse("android.resource://" + this.getPackageName() + "/"
                + R.raw.sample);
        videoView.setVideoURI(uri);
        videoView.start();*/

        //Aproveitando o recarregamento anterior
        if (savedInstanceState != null) {
            int loc = savedInstanceState.getInt("Loc");
            Log.i("Localização: ", loc + "");
            uriYouTube = Uri.parse(savedInstanceState.getString("url"));
            videoView.setVideoURI(uriYouTube);
            videoView.seekTo(loc);
            videoView.setOnPreparedListener(new OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    Log.v("Preparação", "ok");
                    mp.start();
                }
            });
        } else {

            //Setando o link e iniciando o AsyncTask
            RTSPUrlTask truitonTask = new RTSPUrlTask();
            truitonTask.execute("http://www.youtube.com/embed/76JpysFZ2VM");
        }

    }

    //Função que starta o vídeo(SIMPLES COMO VOCÊ FEZ)

    void startPlaying(String url) {
        uriYouTube = Uri.parse(url);
        videoView.setVideoURI(uriYouTube);
        videoView.start();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("Loc", videoView.getCurrentPosition());
        outState.putString("url", uriYouTube.toString());
    }

    //Menus opcionais

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.video_view, menu);
        return true;
    }

    //Iniciando AsyncTask para rodar o vídeo em segundo plano

    private class RTSPUrlTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {
            String response = getRTSPVideoUrl(urls[0]);
            return response;
        }

        @Override
        protected void onPostExecute(String result) {
            startPlaying(result);
        }

        public String getRTSPVideoUrl(String urlYoutube) {
            try {

                //API NECESSÁRIA
                String gdy = "http://gdata.youtube.com/feeds/api/videos/";
                DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance()
                        .newDocumentBuilder();
                String id = extractYoutubeId(urlYoutube);
                URL url = new URL(gdy + id);
                HttpURLConnection connection = (HttpURLConnection) url
                        .openConnection();
                Document doc = dBuilder.parse(connection.getInputStream());
                Element el = doc.getDocumentElement();
                NodeList list = el.getElementsByTagName("media:content");
                String cursor = urlYoutube;
                for (int i = 0; i < list.getLength(); i++) {
                    Node node = list.item(i);
                    if (node != null) {
                        NamedNodeMap nodeMap = node.getAttributes();
                        HashMap<String, String> maps = new HashMap<String, String>();
                        for (int j = 0; j < nodeMap.getLength(); j++) {
                            Attr att = (Attr) nodeMap.item(j);
                            maps.put(att.getName(), att.getValue());
                        }
                        if (maps.containsKey("yt:format")) {
                            String f = maps.get("yt:format");
                            if (maps.containsKey("url"))
                                cursor = maps.get("url");
                            if (f.equals("1"))
                                return cursor;
                        }
                    }
                }
                return cursor;
            } catch (Exception ex) {
                return urlYoutube;
            }
        }

        public String extractYoutubeId(String url) throws MalformedURLException {
            String query = new URL(url).getQuery();
            String[] param = query.split("&");
            String id = null;
            for (String row : param) {
                String[] param1 = row.split("=");
                if (param1[0].equals("v")) {
                    id = param1[1];
                }
            }
            return id;
        }
    }

}

Leave full network (Internet) access and read from the external storage device on your AndroidManifest.xml :

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

Source

    
02.07.2015 / 15:35