Android video embedding

谁说胖子不能爱 提交于 2019-12-25 03:11:03

问题


I have an application that fetches some text from a web page , and displays it on the screen. I would like to put after the text a video from the web . How could I do that ? If I do like the following code , the application crashes ( Null pointer exception) .

My code :

LinearLayout tt= (LinearLayout)findViewById(R.id.kiu);
WebView webview;
tt.addView(fin); // fin is the TextView


        webview.getSettings().setJavaScriptEnabled(true);
        webview.loadUrl("http://www.youtube.com/embed/j4Wmjl7jxQo");
        tt.addView(webview);

main.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    android:scrollbars="vertical"

    android:background="#FFFFFF"

    >
<LinearLayout
android:id="@+id/kiu"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="0dp">

  </LinearLayout>
</ScrollView>

I can't figure out what should I do .. I would like my app to display this instead of this .


回答1:


You should post the stack trace from your exception. And highlight somehow which line it is pointing to. But off the top of my head here is what I notice:

    webview = (WebView) findViewById(R.id.webview);
    ...
    tt.addView(webview);

findViewById(id) will return null unless the view is already on the screen. You don't seem to have a WebView in your xml layout (which I assume is the one that is currently on the screen when this code is executing). Since you don't have one in there findViewById will return null to you and on the next line when you try to use a method you'll get a null pointer.

You have a few options basically what it comes down to though is you won't need both findViewById and .addView(), you'll only need one or the other.

You can either:

replace webview = (WebView) findViewById(R.id.webview); with a WebView constroctor like so: webview = new WebView(this);

Or

you can add a WebView to your xml, leave findViewById how it is now but take out tt.addView(webview);

Also be aware that since you're displaying a youtube page in a webview the user is going to see the whole page, not just a full screen movie. And it is not going to start immediately, they will have to press the start button to get it going. If you are looking for something to just play the video automatically and not show anything else you'll want a VideoView

Here is a fairly straight forward example of VideoView in action You simply have to paste your url into the path variable. Although I am unsure if it knows how to decode a youtube url or not.



来源:https://stackoverflow.com/questions/7674469/android-video-embedding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!