0

i am trying to play a youtube video in android through NanoHTTPD android web server library using a html form by providing the youtube id of some video in the served html file into the html form. So far i got the youtube video player working. And i also get the form post parameter from the html. But i having trouble combining the two.

AndroidWebServer.class

package com.martin.androidwebplayer;

import android.app.Activity;
import android.content.Context;

import fi.iki.elonen.NanoHTTPD;


import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;


public class AndroidWebServer extends NanoHTTPD {

    private static final String TAG = "HTTPServer";
    private Context ctx;


    public AndroidWebServer(int port, Context ctx) {
        super(port);
        this.ctx = ctx;
        try {
            Log.d("TAG", "Starting web server..");
            start();
        }
        catch(IOException ioe) {
            Log.e(TAG, "Unable to start the server");
            ioe.printStackTrace();
        }

    }



    @Override
    public Response serve(IHTTPSession session) {
        Map<String, String> parms = session.getParms();
        String content = null;
        content = readFile().toString();
        if (session.getMethod() == Method.POST) {
            Map<String, String> files = new HashMap<String, String>();
            try {
                session.parseBody(files);

            } catch (IOException e) {
                e.printStackTrace();
            } catch (ResponseException e) {
                e.printStackTrace();
            }
            **youtube(String.valueOf(session.getParms().get("fname")));**
            return newFixedLengthResponse(String.valueOf(session.getParms().get("fname")));
        }

        return newFixedLengthResponse(content );
    }

    private StringBuffer readFile() {
        BufferedReader reader = null;
        StringBuffer buffer = new StringBuffer();
        try {
            reader = new BufferedReader(
                    new InputStreamReader
                            (ctx.getAssets().open("index.html"), "UTF-8"));


            String mLine;
            while ((mLine = reader.readLine()) != null) {
                buffer.append(mLine);
                buffer.append("\n");
            }
        }
        catch(IOException ioe) {
            ioe.printStackTrace();
        }
        finally {
            if (reader != null)
                try {
                    reader.close();
                }
                catch (IOException ioe) {}
        }

        return buffer;
    }

    public void stopServer() {
        this.stop();
    }

    public void youtube(String link) {

        // Get reference to the view of Video player
        YouTubePlayerView ytPlayer = (YouTubePlayerView) ((Activity)ctx).findViewById(R.id.ytPlayer);

        String api_key = "apikey";
        ytPlayer.initialize(
                api_key,
                new YouTubePlayer.OnInitializedListener() {
                    // Implement two methods by clicking on red
                    // error bulb inside onInitializationSuccess
                    // method add the video link or the playlist
                    // link that you want to play In here we
                    // also handle the play and pause
                    // functionality
                    @Override
                    public void onInitializationSuccess(
                            YouTubePlayer.Provider provider,
                            YouTubePlayer youTubePlayer, boolean b) {
                        youTubePlayer.loadVideo(link);
                        youTubePlayer.play();
                    }

                    // Inside onInitializationFailure
                    // implement the failure functionality
                    // Here we will show toast
                    @Override
                    public void onInitializationFailure(YouTubePlayer.Provider provider,
                                                        YouTubeInitializationResult
                                                                youTubeInitializationResult) {
                    }
                });
    }
    }

MainActivity.class

package com.martin.androidwebplayer;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubePlayerView;

import java.io.IOException;

public class MainActivity extends YouTubeBaseActivity {

    private AndroidWebServer aws;
    private YouTubePlayerView ytPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        YouTubePlayerView ytPlayer = (YouTubePlayerView) findViewById(R.id.ytPlayer);
        aws = new AndroidWebServer(8180, MainActivity.this);
    }
}

assets/index.html

<html>
<head>
    <title>CSS Contact Form</title>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css"/>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
       function formSubmit(){
        var fname = document.getElementById("fname").value;
        var dataString = 'fname='+ fname;
        jQuery.ajax({
        url: "http://192.168.100.42:8180",
        data: dataString,
        type: "POST",
        success:function(data){
        $("#myForm").html(data);
        },
        error:function (){}
        });
  return true;
}
       </script>
</head>
<body>
<h2>Contact Form</h2>
<form class="form" action="" method="post">
    <p class="name">
    <div id="myForm">
        <input type="text" name="fname" id="fname"/>
        <label for="fname">Name</label>
    </p>
    </div>
        <p class="submit" >
            <input type="button" onclick="formSubmit();" value="Send"/>
        </p>
</form>

</body>

</html>

  • It is unclear wich trouble that would be. Please tell better what should happen and what happens instead. – blackapps Nov 28 '21 at 06:18
  • Further you cannot use strings or stringreaders to put a videofile is so i do not understand that you got the playing working – blackapps Nov 28 '21 at 06:26
  • when i write the youtube video id in the html form and then click post it should pass the parameter from the form to the youtube player method. i got the youtube player working by giving it a hardcoded youtube video id on method call – evilcomputer12 Nov 28 '21 at 11:21
  • Sorry, ,you explained nothing more. I do not understand your scenario.,. And you did sayu noting about a video file in a String. – blackapps Nov 28 '21 at 11:26

0 Answers0