I can parse an href url just following the documentation:
Document doc = Jsoup.connect("http://jsoup.org").get();
Element link = doc.select("a").first();
String relHref = link.attr("href"); // == "/"
String absHref = link.attr("abs:href"); // "http://jsoup.org/"
but i try to extract a link url from css in this webpage: http://multiplayer.it/notizie/133685-assassins-creed-unity-ecco-come-assassins-creed-unity-sfrutta-lhardware-di-nuova-generazione.html
i need take the link of image banner. The id is: id="content_heading" but the image is loaded by css.
<div id="content_heading" style="background: url(http://images.multiplayer.it/thumbs/images/2014/06/10/assassins_creed_unity_jpg_1600x0_upscale_q85.jpg) center center; background-size: cover;">
How can i extract the url? this is the Asynktask
private class ContentViewImgUrl extends AsyncTask<String,String,String> {
#Override
protected void onPreExecute()
{
}
#Override
protected String doInBackground(String... params) {
try {
final Document doc = Jsoup.connect(URL).timeout(30000).get();
runOnUiThread(new Runnable() {
#Override
public void run() {
Element rootElement = doc.body().getElementById("top_ads_container");
Elements elements = rootElement.getElementsByTag("header");
for(Element element : elements){
imgUrlPost = element.select("div.content_heading").text();
}
}
});
} catch (Exception e) {
Log.e("ESEMPIO", "ERROR");
}
return null; // MODIFIED HERE
}
#Override
protected void onPostExecute(String result)
{
Toast.makeText(SingleActivity.this, "url "+ imgUrlPost, Toast.LENGTH_SHORT).show();
}
}
The toast not works.. It returns only Url and nothing else.
Thanks
UDPATE:
private class ContentViewImgUrl extends AsyncTask<Void,Void,Void> {
final Pattern pattern = Pattern.compile("url\\((.+?)\\)");
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(Void... params) {
try {
final Document doc = Jsoup.connect(URL).timeout(30000).get();
runOnUiThread(new Runnable() {
#Override
public void run() {
String url = doc.getElementById("content_heading").attr("style").toString();
Matcher matcher = pattern.matcher(url);
matcher.find();
System.out.println(matcher.group(1));
}
});
urlnew = new URL(matcher.group(1));
postBitmap = BitmapFactory.decodeStream(urlnew.openConnection().getInputStream());
} catch (Exception e) {
Log.e("ESEMPIO", "ERROR");
}
return null; // MODIFIED HERE
}
#Override
protected void onPostExecute(Void result) {
Toast.makeText(SingleActivity.this, "url "+ urlnew, Toast.LENGTH_SHORT).show();
postImage = (ImageView) findViewById(R.id.postimage);
postImage.setImageBitmap(postBitmap);
}
}
where urlnew i declared it as public URL urlnew and postBitmap as Bitmap
SECOND UDPATE:
private class ContentViewImgUrl extends AsyncTask<Void,Void,Void> {
final Pattern pattern = Pattern.compile("url\\((.+?)\\)");
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(Void... params) {
try {
final Document doc = Jsoup.connect(URL).timeout(30000).get();
runOnUiThread(new Runnable() {
#Override
public void run() {
String url = doc.getElementById("content_heading").attr("style").toString();
Matcher matcher = pattern.matcher(url);
if(matcher.find()){
System.out.println(matcher.group(1));
indirizzostringaimg = matcher.group(1);
imgloader = ImageLoader.getInstance();
imgloader.init(ImageLoaderConfiguration.createDefault(getActivity()));
System.out.println(urlnew);
} else {
Toast.makeText(getActivity(), "Pic url error", Toast.LENGTH_SHORT).show();
}
}
});
} catch (Exception e) {
Log.e("ESEMPIO", "ERROR");
}
return null; // MODIFIED HERE
}
#Override
protected void onPostExecute(Void result) {
if(matcher.find()){
DisplayImageOptions opt = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.refresh)
.showImageForEmptyUri(R.drawable.refresh)
.cacheInMemory()
.imageScaleType(ImageScaleType.IN_SAMPLE_INT)
.cacheOnDisc()
.build();
imgloader.displayImage(indirizzostringaimg, postimage_main, opt);
} else {
Toast.makeText(getActivity(), "Pic url error", Toast.LENGTH_SHORT).show();
}
}
}
Here is a complete working example. Get the part that interests you.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
public class Main {
public static void main(String[] args) {
String html = "<div id=\"content_heading\" style=\"background: url(http://images.multiplayer.it/thumbs/images/2014/06/10/assassins_creed_unity_jpg_1600x0_upscale_q85.jpg) center center; background-size: cover;\"></div>";
final Pattern pattern = Pattern.compile("url\\((.+?)\\)");
try {
Document doc = Jsoup.parse(html);
String url = doc.getElementById("content_heading").attr("style").toString();
Matcher matcher = pattern.matcher(url);
matcher.find();
System.out.println(matcher.group(1));
} catch(Exception e) {
e.printStackTrace();
}
}
}
Update
private class ContentViewImgUrl extends AsyncTask<String,String,String> {
final Pattern pattern = Pattern.compile("url\\((.+?)\\)");
#Override
protected void onPreExecute() {}
#Override
protected String doInBackground(String... params) {
try {
final Document doc = Jsoup.connect(URL).timeout(30000).get();
runOnUiThread(new Runnable() {
#Override
public void run() {
String url = doc.getElementById("content_heading").attr("style").toString();
Matcher matcher = pattern.matcher(url);
matcher.find();
System.out.println(matcher.group(1));
}
});
} catch (Exception e) {
Log.e("ESEMPIO", "ERROR");
}
return null; // MODIFIED HERE
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(SingleActivity.this, "url "+ imgUrlPost, Toast.LENGTH_SHORT).show();
}
}
Related
I have a PDF file on my Firebase. I am using the AndroidPDFViewer library. Then I retrieve data using AsyncTask.
I want to know how to stop my ProgressBar using the isFinishedI() function in my view class, as this while loop doesn't exit ?
public class PDFHandler {
private PDFView pdfView = null;
private RetriverPDFStream retriverPDFStream;
private RetriverPDFStream getRetriverPDFStream(){ return this.retriverPDFStream; }
public void setPdfView(PDFView pdfView)
{
this.pdfView = pdfView;
}
public void openOnline(String link)
{
retriverPDFStream = new RetriverPDFStream();
retriverPDFStream.execute(link);
}
public boolean isFinished ()
{
if(getRetriverPDFStream().getStatus() == AsyncTask.Status.RUNNING){
return false;
}else{
return true;
}
}
//This class to retrieve pdf online asynchronously
public class RetriverPDFStream extends AsyncTask<String,Void, InputStream> {
#Override
protected InputStream doInBackground(String... strings) {
InputStream inputStream = null;
try{
URL url = new URL(strings[0]);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
if(urlConnection.getResponseCode() == 200)
{
inputStream = new BufferedInputStream(urlConnection.getInputStream());
}
}catch (IOException e){
return null;
}
return inputStream;
}
#Override
protected void onPostExecute(InputStream inputStream) {
pdfView.fromStream(inputStream).load();
}
}
}
On create method
protected void onCreate(Bundle savedInstanceState) {
pdfView = findViewById(R.id.pdfView);
progressBar = findViewById(R.id.progressBar);
//This is function read PDF from URL
PDFHandler pdfHandler = new PDFHandler();
pdfHandler.setPdfView(pdfView);
pdfHandler.openOnline(link);
progressBar.setVisibility(View.VISIBLE);
while(!pdfHandler.isFinished()){
progressBar.setVisibility(View.INVISIBLE);
}
public boolean isFinished ()
{
if(getRetriverPDFStream().getStatus() == AsyncTask.Status.FINISHED)
{
return true;
}
else
{
return false;
}
}
I keep getting an an error when trying to call WowZa GoCoder SDK's PlayerActivity and I am unable to understand the cause. The error appears when mStreamPlayerView.play(mStreamPlayerConfig, statusCallback) is called. Would really appreciate help on where i am going wrong
vodFragment.java
public class vodFragment extends Fragment {
private int mColumnCount = 1;
ListView videoView;
ArrayList <Vidoes> videoList;
private static String value;
String videoName;
String url = "http://192.168.43.149/twende/channelVOD.php";
public vodFragment() {
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (getActivity().getActionBar() != null) {
getActivity().getActionBar().setTitle(value);
}
View view = inflater.inflate(R.layout.fragment_vod_list, container, false);
videoView = (ListView) view.findViewById(R.id.listView);
videoList = new ArrayList<Vidoes>();
JSONObject channelInfo = new JSONObject();
try {
channelInfo.put("channelName", value);
channelInfo.put("channelOwner", "dan");
postJSONObject(url,channelInfo);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return view;
}
public static void setChannel(String channel){
value = channel;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
}
public void postJSONObject(final String myurl, final JSONObject parameters) {
class postJSONObject extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
loadIntoVodView(s);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(Void... voids) {
HttpURLConnection conn = null;
try {
StringBuffer response = null;
URL url = new URL(myurl);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
conn.setRequestMethod("POST");
OutputStream out = new BufferedOutputStream(conn.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
writer.write(parameters.toString());
writer.close();
out.close();
int responseCode = conn.getResponseCode();
System.out.println("responseCode" + responseCode);
switch (responseCode) {
case 200:
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (conn != null) {
try {
conn.disconnect();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
return null;
}
}
postJSONObject postJSONObject = new postJSONObject();
postJSONObject.execute();
}
private void loadIntoVodView(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
final String[] videos = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
videos[i] = removeExtension(obj.getString("title"));
Vidoes vidoe = new Vidoes();
vidoe.setTitle(videos[i]);
videoList.add(vidoe);
}
VideoListAdapter adapter = new VideoListAdapter(getActivity(), R.layout.vodparsedata, videoList);
videoView.setAdapter(adapter);
videoView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
videoName = Arrays.asList(videos).get(position);
Intent intent = new Intent(getActivity(), PlayerActivity.class);
String message = videoName+".mp4";
intent.putExtra("videoName", message);
startActivity(intent);
System.out.println("arr: " + Arrays.asList(videos).get(position));
}
});
}
public static String removeExtension(String fileName) {
if (fileName.indexOf(".") > 0) {
return fileName.substring(0, fileName.lastIndexOf("."));
} else {
return fileName;
}
}
}
PlayerActivity.java
public class PlayerActivity extends GoCoderSDKActivityBase {
final private static String TAG = PlayerActivity.class.getSimpleName();
String videoName;
private WOWZPlayerView mStreamPlayerView = null;
private WOWZPlayerConfig mStreamPlayerConfig = new WOWZPlayerConfig();
private MultiStateButton mBtnPlayStream = null;
private MultiStateButton mBtnSettings = null;
private MultiStateButton mBtnMic = null;
private MultiStateButton mBtnScale = null;
private SeekBar mSeekVolume = null;
private ProgressDialog mBufferingDialog = null;
private StatusView mStatusView = null;
private TextView mHelp = null;
private TimerView mTimerView = null;
private ImageButton mStreamMetadata = null;
private boolean mUseHLSPlayback = false;
private WOWZPlayerView.PacketThresholdChangeListener packetChangeListener = null;
private VolumeChangeObserver mVolumeSettingChangeObserver = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stream_player);
mRequiredPermissions = new String[]{};
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
videoName= null;
} else {
videoName= extras.getString("videoName");
}
} else {
videoName= (String) savedInstanceState.getSerializable("videoName");
}
System.out.print(videoName);
mStreamPlayerConfig.setIsPlayback(true);
mStreamPlayerConfig.setHostAddress("192.168.43.149");
mStreamPlayerConfig.setApplicationName("Dark Souls 2 Channel");
mStreamPlayerConfig.setStreamName(videoName);
mStreamPlayerConfig.setPortNumber(1935);
mStreamPlayerView = (WOWZPlayerView) findViewById(R.id.vwStreamPlayer);
mBtnPlayStream = (MultiStateButton) findViewById(R.id.ic_play_stream);
mBtnSettings = (MultiStateButton) findViewById(R.id.ic_settings);
mBtnMic = (MultiStateButton) findViewById(R.id.ic_mic);
mBtnScale = (MultiStateButton) findViewById(R.id.ic_scale);
mTimerView = (TimerView) findViewById(R.id.txtTimer);
mStatusView = (StatusView) findViewById(R.id.statusView);
mStreamMetadata = (ImageButton) findViewById(R.id.imgBtnStreamInfo);
mHelp = (TextView) findViewById(R.id.streamPlayerHelp);
mSeekVolume = (SeekBar) findViewById(R.id.sb_volume);
WOWZStatusCallback statusCallback = new StatusCallback();
mStreamPlayerView.play(mStreamPlayerConfig, statusCallback);
mTimerView.setVisibility(View.GONE);
mStreamPlayerView.play(mStreamPlayerConfig, statusCallback);
if (sGoCoderSDK != null) {
/*
Packet change listener setup
*/
final PlayerActivity activity = this;
packetChangeListener = new WOWZPlayerView.PacketThresholdChangeListener() {
#Override
public void packetsBelowMinimumThreshold(int packetCount) {
WOWZLog.debug("Packets have fallen below threshold "+packetCount+"... ");
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(activity, "Packets have fallen below threshold ... ", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void packetsAboveMinimumThreshold(int packetCount) {
WOWZLog.debug("Packets have risen above threshold "+packetCount+" ... ");
activity.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(activity, "Packets have risen above threshold ... ", Toast.LENGTH_SHORT).show();
}
});
}
};
mStreamPlayerView.setShowAllNotificationsWhenBelowThreshold(false);
mStreamPlayerView.setMinimumPacketThreshold(20);
mStreamPlayerView.registerPacketThresholdListener(packetChangeListener);
///// End packet change notification listener
mTimerView.setTimerProvider(new TimerView.TimerProvider() {
#Override
public long getTimecode() {
return mStreamPlayerView.getCurrentTime();
}
#Override
public long getDuration() {
return mStreamPlayerView.getDuration();
}
});
mSeekVolume.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (mStreamPlayerView != null && mStreamPlayerView.isPlaying()) {
mStreamPlayerView.setVolume(progress);
}
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
// listen for volume changes from device buttons, etc.
mVolumeSettingChangeObserver = new VolumeChangeObserver(this, new Handler());
getApplicationContext().getContentResolver().registerContentObserver(android.provider.Settings.System.CONTENT_URI, true, mVolumeSettingChangeObserver);
mVolumeSettingChangeObserver.setVolumeChangeListener(new VolumeChangeObserver.VolumeChangeListener() {
#Override
public void onVolumeChanged(int previousLevel, int currentLevel) {
if (mSeekVolume != null)
mSeekVolume.setProgress(currentLevel);
if (mStreamPlayerView != null && mStreamPlayerView.isPlaying()) {
mStreamPlayerView.setVolume(currentLevel);
}
}
});
mBtnScale.setState(mStreamPlayerView.getScaleMode() == WOWZMediaConfig.FILL_VIEW);
// The streaming player configuration properties
mStreamPlayerConfig = new WOWZPlayerConfig();
mBufferingDialog = new ProgressDialog(this);
mBufferingDialog.setTitle(R.string.status_buffering);
mBufferingDialog.setMessage(getResources().getString(R.string.msg_please_wait));
mBufferingDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getResources().getString(R.string.button_cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
cancelBuffering(dialogInterface);
}
});
// testing player data event handler.
mStreamPlayerView.registerDataEventListener("onMetaData", new WOWZDataEvent.EventListener(){
#Override
public WOWZDataMap onWZDataEvent(String eventName, WOWZDataMap eventParams) {
String meta = "";
if(eventParams!=null)
meta = eventParams.toString();
WOWZLog.debug("onWZDataEvent -> eventName "+eventName+" = "+meta);
return null;
}
});
// testing player data event handler.
mStreamPlayerView.registerDataEventListener("onStatus", new WOWZDataEvent.EventListener(){
#Override
public WOWZDataMap onWZDataEvent(String eventName, WOWZDataMap eventParams) {
if(eventParams!=null)
WOWZLog.debug("onWZDataEvent -> eventName "+eventName+" = "+eventParams.toString());
return null;
}
});
// testing player data event handler.
mStreamPlayerView.registerDataEventListener("onTextData", new WOWZDataEvent.EventListener(){
#Override
public WOWZDataMap onWZDataEvent(String eventName, WOWZDataMap eventParams) {
if(eventParams!=null)
WOWZLog.debug("onWZDataEvent -> "+eventName+" = "+eventParams.get("text"));
return null;
}
});
} else {
mHelp.setVisibility(View.GONE);
mStatusView.setErrorMessage(WowzaGoCoder.getLastError().getErrorDescription());
}
}
#Override
protected void onDestroy() {
if (mVolumeSettingChangeObserver != null)
getApplicationContext().getContentResolver().unregisterContentObserver(mVolumeSettingChangeObserver);
super.onDestroy();
}
/**
* Android Activity class methods
*/
#Override
protected void onResume() {
super.onResume();
syncUIControlState();
}
#Override
protected void onPause() {
if (mStreamPlayerView != null && mStreamPlayerView.isPlaying()) {
mStreamPlayerView.stop();
// Wait for the streaming player to disconnect and shutdown...
mStreamPlayerView.getCurrentStatus().waitForState(WOWZState.IDLE);
}
super.onPause();
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
public boolean isPlayerConfigReady()
{
return false;
}
/*
Click handler for network pausing
*/
public void onPauseNetwork(View v)
{
Button btn = (Button)findViewById(R.id.pause_network);
if(btn.getText().toString().trim().equalsIgnoreCase("pause network")) {
WOWZLog.info("Pausing network...");
btn.setText("Unpause Network");
mStreamPlayerView.pauseNetworkStack();
}
else{
WOWZLog.info("Unpausing network... btn.getText(): "+btn.getText());
btn.setText("Pause Network");
mStreamPlayerView.unpauseNetworkStack();
}
}
/**
* Click handler for the playback button
*/
public void onTogglePlayStream(View v) {
if (mStreamPlayerView.isPlaying()) {
mStreamPlayerView.stop();
} else if (mStreamPlayerView.isReadyToPlay()) {
if(!this.isNetworkAvailable()){
displayErrorDialog("No internet connection, please try again later.");
return;
}
// if(!this.isPlayerConfigReady()){
// displayErrorDialog("Please be sure to include a host, stream, and application to playback a stream.");
// return;
// }
mHelp.setVisibility(View.GONE);
WOWZStreamingError configValidationError = mStreamPlayerConfig.validateForPlayback();
if (configValidationError != null) {
mStatusView.setErrorMessage(configValidationError.getErrorDescription());
} else {
// Set the detail level for network logging output
mStreamPlayerView.setLogLevel(mWZNetworkLogLevel);
// Set the player's pre-buffer duration as stored in the app prefs
float preBufferDuration = GoCoderSDKPrefs.getPreBufferDuration(PreferenceManager.getDefaultSharedPreferences(this));
mStreamPlayerConfig.setPreRollBufferDuration(preBufferDuration);
// Start playback of the live stream
mStreamPlayerView.play(mStreamPlayerConfig, this);
}
}
}
/**
* WOWZStatusCallback interface methods
*/
#Override
public synchronized void onWZStatus(WOWZStatus status) {
final WOWZStatus playerStatus = new WOWZStatus(status);
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
WOWZStatus status = new WOWZStatus(playerStatus.getState());
switch(playerStatus.getState()) {
case WOWZPlayerView.STATE_PLAYING:
// Keep the screen on while we are playing back the stream
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
if (mStreamPlayerConfig.getPreRollBufferDuration() == 0f) {
mTimerView.startTimer();
}
// Since we have successfully opened up the server connection, store the connection info for auto complete
GoCoderSDKPrefs.storeHostConfig(PreferenceManager.getDefaultSharedPreferences(PlayerActivity.this), mStreamPlayerConfig);
// Log the stream metadata
WOWZLog.debug(TAG, "Stream metadata:\n" + mStreamPlayerView.getMetadata());
break;
case WOWZPlayerView.STATE_READY_TO_PLAY:
// Clear the "keep screen on" flag
WOWZLog.debug(TAG, "STATE_READY_TO_PLAY player activity status!");
if(playerStatus.getLastError()!=null)
displayErrorDialog(playerStatus.getLastError());
playerStatus.clearLastError();
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
mTimerView.stopTimer();
break;
case WOWZPlayerView.STATE_PREBUFFERING_STARTED:
WOWZLog.debug(TAG, "Dialog for buffering should show...");
showBuffering();
break;
case WOWZPlayerView.STATE_PREBUFFERING_ENDED:
WOWZLog.debug(TAG, "Dialog for buffering should stop...");
hideBuffering();
// Make sure player wasn't signaled to shutdown
if (mStreamPlayerView.isPlaying()) {
mTimerView.startTimer();
}
break;
default:
break;
}
syncUIControlState();
}
});
}
#Override
public synchronized void onWZError(final WOWZStatus playerStatus) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
displayErrorDialog(playerStatus.getLastError());
syncUIControlState();
}
});
}
public void onToggleMute(View v) {
mBtnMic.toggleState();
if (mStreamPlayerView != null)
mStreamPlayerView.mute(!mBtnMic.isOn());
mSeekVolume.setEnabled(mBtnMic.isOn());
}
public void onToggleScaleMode(View v) {
int newScaleMode = mStreamPlayerView.getScaleMode() == WOWZMediaConfig.RESIZE_TO_ASPECT ? WOWZMediaConfig.FILL_VIEW : WOWZMediaConfig.RESIZE_TO_ASPECT;
mBtnScale.setState(newScaleMode == WOWZMediaConfig.FILL_VIEW);
mStreamPlayerView.setScaleMode(newScaleMode);
}
public void onStreamMetadata(View v) {
WOWZDataMap streamMetadata = mStreamPlayerView.getMetadata();
WOWZDataMap streamStats = mStreamPlayerView.getStreamStats();
// WOWZDataMap streamConfig = mStreamPlayerView.getStreamConfig().toDataMap();
WOWZDataMap streamConfig = new WOWZDataMap();
WOWZDataMap streamInfo = new WOWZDataMap();
streamInfo.put("- Stream Statistics -", streamStats);
streamInfo.put("- Stream Metadata -", streamMetadata);
//streamInfo.put("- Stream Configuration -", streamConfig);
DataTableFragment dataTableFragment = DataTableFragment.newInstance("Stream Information", streamInfo, false, false);
getFragmentManager().beginTransaction()
.add(android.R.id.content, dataTableFragment)
.addToBackStack("metadata_fragment")
.commit();
}
public void onSettings(View v) {
// Display the prefs fragment
GoCoderSDKPrefs.PrefsFragment prefsFragment = new GoCoderSDKPrefs.PrefsFragment();
prefsFragment.setFixedSource(true);
prefsFragment.setForPlayback(true);
getFragmentManager().beginTransaction()
.replace(android.R.id.content, prefsFragment)
.addToBackStack(null)
.commit();
}
private void syncUIControlState() {
boolean disableControls = (!(mStreamPlayerView.isReadyToPlay() || mStreamPlayerView.isPlaying()) || sGoCoderSDK == null);
if (disableControls) {
mBtnPlayStream.setEnabled(false);
mBtnSettings.setEnabled(false);
mSeekVolume.setEnabled(false);
mBtnScale.setEnabled(false);
mBtnMic.setEnabled(false);
mStreamMetadata.setEnabled(false);
} else {
mBtnPlayStream.setState(mStreamPlayerView.isPlaying());
mBtnPlayStream.setEnabled(true);
if (mStreamPlayerConfig.isAudioEnabled()) {
mBtnMic.setVisibility(View.VISIBLE);
mBtnMic.setEnabled(true);
mSeekVolume.setVisibility(View.VISIBLE);
mSeekVolume.setEnabled(mBtnMic.isOn());
mSeekVolume.setProgress(mStreamPlayerView.getVolume());
} else {
mSeekVolume.setVisibility(View.GONE);
mBtnMic.setVisibility(View.GONE);
}
mBtnScale.setVisibility(View.VISIBLE);
mBtnScale.setVisibility(mStreamPlayerView.isPlaying() && mStreamPlayerConfig.isVideoEnabled() ? View.VISIBLE : View.GONE);
mBtnScale.setEnabled(mStreamPlayerView.isPlaying() && mStreamPlayerConfig.isVideoEnabled());
mBtnSettings.setEnabled(!mStreamPlayerView.isPlaying());
mBtnSettings.setVisibility(mStreamPlayerView.isPlaying() ? View.GONE : View.VISIBLE);
mStreamMetadata.setEnabled(mStreamPlayerView.isPlaying());
mStreamMetadata.setVisibility(mStreamPlayerView.isPlaying() ? View.VISIBLE : View.GONE);
}
}
private void showBuffering() {
try {
if (mBufferingDialog == null) return;
mBufferingDialog.show();
}
catch(Exception ex){}
}
private void cancelBuffering(DialogInterface dialogInterface) {
if(mStreamPlayerConfig.getHLSBackupURL()!=null || mStreamPlayerConfig.isHLSEnabled()){
mStreamPlayerView.stop(true);
}
else if (mStreamPlayerView != null && mStreamPlayerView.isPlaying()) {
mStreamPlayerView.stop(true);
}
}
private void hideBuffering() {
if (mBufferingDialog.isShowing())
mBufferingDialog.dismiss();
}
#Override
public void syncPreferences() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
mWZNetworkLogLevel = Integer.valueOf(prefs.getString("wz_debug_net_log_level", String.valueOf(WOWZLog.LOG_LEVEL_DEBUG)));
mStreamPlayerConfig.setIsPlayback(true);
if (mStreamPlayerConfig != null)
GoCoderSDKPrefs.updateConfigFromPrefsForPlayer(prefs, mStreamPlayerConfig);
}
private class StatusCallback implements WOWZStatusCallback {
#Override
public void onWZStatus(WOWZStatus wzStatus) {
}
#Override
public void onWZError(WOWZStatus wzStatus) {
}
}
}
The error I get is;
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.wowza.gocoder.sdk.sampleapp/com.wowza.gocoder.sdk.sampleapp.PlayerActivity}: java.lang.RuntimeException: Invalid surface: null
You start the stream in onCreate. At this time the Surface used by WOWZPlayerView is not ready yet and the app crashes with the 'Invalid surface' error.
If you look at the sample test in the GoCoder SDK, the playback is started when the user clicks a button. Eg. when the Surface is valid.
Create a button and move your 'mStreamPlayerView.play(mStreamPlayerConfig, statusCallback);' to the button.onClick.
Or ... use any GoCoder SDK v1.7 and more recent.
Please, let me know if I can help any further.
Thanks
I am getting these error when retrieving ucoz.api.ru (oauth 1.0a) token using scribe library oauth (4.2.0) on android :
Caused by: com.github.scribejava.core.exceptions.OAuthException:
Response body is incorrect. Can't extract token and secret from this:
'{"oauth_token":"NAzoveaGm5XIlBvLcLRxUvamEK8P2.BAlQZ.M.aV","oauth_token_secret":"SJsqC0IfFAKS3BkdauQ3bY4ha01PDHTlFIy7GSro","oauth_callback_confirmed":"true"}'
at
com.github.scribejava.core.extractors.AbstractOAuth1TokenExtractor.extract(AbstractOAuth1TokenExtractor.java:42)
at
com.github.scribejava.core.extractors.AbstractOAuth1TokenExtractor.extract(AbstractOAuth1TokenExtractor.java:32)
at
com.github.scribejava.core.extractors.AbstractOAuth1TokenExtractor.extract(AbstractOAuth1TokenExtractor.java:19)
at
com.github.scribejava.core.oauth.OAuth10aService.getRequestToken(OAuth10aService.java:49)
at
com.vasyaevstropov.oauth10test.MainActivity.request(MainActivity.java:96)
at
com.vasyaevstropov.oauth10test.MainActivity$1$1.doInBackground(MainActivity.java:61)
at
com.vasyaevstropov.oauth10test.MainActivity$1$1.doInBackground(MainActivity.java:53)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
My source code:
final OAuth10aService service = new ServiceBuilder(CONSUMER_KEY)
.apiSecret(CONSUMER_SECRET)
.debug()
.build(UcozApi.instance());
final Scanner in = new Scanner(System.in);
// Obtain the Request Token
final OAuth1RequestToken requestToken = service.getRequestToken(); // <<--- Error is in this place
System.out.println(service.getAuthorizationUrl(requestToken));
final String oauthVerifier = in.nextLine();
// Trade the Request Token and Verfier for the Access Token
OAuth1AccessToken accessToken = null;
try {
accessToken = service.getAccessToken(requestToken, oauthVerifier);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
Ucozapi module:
public class UcozApi extends com.github.scribejava.core.builder.api.DefaultApi10a {
private static final String AUTHORIZE_URL = "http://uapi.ucoz.com/accounts/oauthauthorizetoken=%s";
private static final String REQUEST_TOKEN_RESOURCE = "http://uapi.ucoz.com/accounts/oauthgetrequesttoken";
private static final String ACCESS_TOKEN_RESOURCE = "http://uapi.ucoz.com/accounts/oauthgetaccesstoken";
protected UcozApi() {
}
private static final UcozApi INSTANCE = new UcozApi();
public static UcozApi instance() {
return INSTANCE;
}
#Override
public String getAccessTokenEndpoint() {
return ACCESS_TOKEN_RESOURCE;
}
#Override
public String getRequestTokenEndpoint() {
return REQUEST_TOKEN_RESOURCE;
}
#Override
public String getAuthorizationUrl(OAuth1RequestToken requestToken) {
return String.format(AUTHORIZE_URL, requestToken.getToken());
}
}
Can somebody help me?
I answer my question. This code will work good with scribe-java library:
MainActivity:
import com.github.scribejava.core.builder.ServiceBuilder;
import com.github.scribejava.core.model.OAuth1AccessToken;
import com.github.scribejava.core.model.OAuth1RequestToken;
import com.github.scribejava.core.oauth.OAuth10aService;
import com.vasyaevstropov.oauthtest.ucoz.UcozApi;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
public class MainActivity extends AppCompatActivity {
Button button;
public WebView webView;
String verifier;
OAuth1RequestToken requestToken = null;
OAuth10aService service;
OAuth1AccessToken accessToken;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
webView.clearCache(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDisplayZoomControls(false);
service = new ServiceBuilder("murka1")
.apiSecret("DqUQJzeCPmwD9CRqbHo6sGBzKCb5U4")
.debug()
.build(UcozApi.instance());
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new AsyncTask<Void, Void, String>() {
protected String doInBackground(Void... params) {
String PROTECTED_RESOURCE_URL = "http://artmurka.com/uapi/shop/request?page=categories";
try {
requestToken = service.getRequestToken();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
String url = service.getAuthorizationUrl(requestToken);
return url;
}
#Override
protected void onPostExecute(String result) {
loadURL(result);
}
}.execute();
}
});
}
public void loadURL(final String url) {
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Uri uri = Uri.parse(url);
if (url.contains("oauth_verifier")) {
webView.setVisibility(webView.GONE);
Log.d("Log.d", url);
verifier = uri.getQueryParameter("oauth_verifier");
Toast.makeText(getApplicationContext(), verifier, Toast.LENGTH_SHORT).show();
getAccessToken();
}
return false;
}
});
webView.loadUrl(url);
}
private void getAccessToken() {
new AsyncTask<Void, Void, OAuth1AccessToken>() {
protected OAuth1AccessToken doInBackground(Void... params) {
try {
accessToken = service.getAccessToken(requestToken, verifier);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return accessToken;
}
#Override
protected void onPostExecute(OAuth1AccessToken result) {
Toast.makeText(getApplicationContext(), "Token = " + result.getToken() + "Secret = " + result.getTokenSecret(), Toast.LENGTH_LONG).show();
}
}.execute();
}
#Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
}
UcozApi
public class UcozApi extends DefaultApi10a {
private static final String AUTHORIZE_URL = "http://uapi.ucoz.com/accounts/oauthauthorizetoken?oauth_token=%s";
protected UcozApi() {
}
private static class InstanceHolder {
private static final UcozApi INSTANCE = new UcozApi();
}
public static UcozApi instance() {
return InstanceHolder.INSTANCE; }
#Override
public String getAccessTokenEndpoint(){
return "http://uapi.ucoz.com/accounts/oauthgetaccesstoken"; }
#Override
public String getRequestTokenEndpoint() {
return "http://uapi.ucoz.com/accounts/oauthgetrequesttoken"; }
#Override
public String getAuthorizationUrl(OAuth1RequestToken requestToken) {
return String.format(AUTHORIZE_URL, requestToken.getToken()); }
#Override
public TokenExtractor<OAuth1AccessToken> getAccessTokenExtractor() {
return OAuth1AccessUcozTokenExtractor.instance();
}
#Override
public TokenExtractor<OAuth1RequestToken> getRequestTokenExtractor() {
return OAuth1RequestUcozTokenExtractor.instance();
}
}
OAuth1RequestUcozTokenExtractor
import com.github.scribejava.core.model.OAuth1RequestToken;
public class OAuth1RequestUcozTokenExtractor extends AbstractOauth1UcozTokenExtractor<OAuth1RequestToken> {
protected OAuth1RequestUcozTokenExtractor() {
}
#Override
protected OAuth1RequestToken createToken(String token, String secret, String response) {
return new OAuth1RequestToken(token, secret, response);
}
private static class InstanceHolder {
private static final OAuth1RequestUcozTokenExtractor INSTANCE = new OAuth1RequestUcozTokenExtractor();
}
public static OAuth1RequestUcozTokenExtractor instance() {
return InstanceHolder.INSTANCE;
}
}
OAuth1AccessUcozTokenExtractor
public class OAuth1AccessUcozTokenExtractor extends AbstractOauth1UcozTokenExtractor<OAuth1AccessToken> {
protected OAuth1AccessUcozTokenExtractor() {
}
#Override
protected OAuth1AccessToken createToken(String token, String secret, String response) {
return new OAuth1AccessToken(token, secret, response);
}
private static class InstanceHolder {
private static final OAuth1AccessUcozTokenExtractor INSTANCE = new OAuth1AccessUcozTokenExtractor();
}
public static OAuth1AccessUcozTokenExtractor instance() {
return InstanceHolder.INSTANCE;
}
}
AbstractOauth1UcozTokenExtractor
public abstract class AbstractOauth1UcozTokenExtractor<T extends OAuth1Token> implements TokenExtractor<T> {
private Pattern OAUTH_TOKEN_PATTERN = Pattern.compile("\"oauth_token\"\\s*:\\s*\"(\\S*?)\"");
private Pattern OAUTH_TOKEN_SECRET_PATTERN = Pattern.compile("\"oauth_token_secret\"\\s*:\\s*\"(\\S*?)\"");
#Override
public T extract(Response response) throws IOException {
final String body = response.getBody();
Preconditions.checkEmptyString(body,
"Response body is incorrect. " + "Can't extract a token from an empty string");
final String token = extract(body, OAUTH_TOKEN_PATTERN);
final String secret = extract(body, OAUTH_TOKEN_SECRET_PATTERN);
return createToken(token, secret, body);
}
private String extract(String response, Pattern p) {
final Matcher matcher = p.matcher(response);
if (matcher.find() && matcher.groupCount() >= 1) {
return OAuthEncoder.decode(matcher.group(1));
} else {
throw new OAuthException("Response body is incorrect. Can't extract token and secret from this: '"
+ response + "'", null);
}
}
protected abstract T createToken(String token, String secret, String response);
}
I want to show string from another string in my MainActivity, but the string is getting printed in console. Here is my code:
public class MainActivity extends AppCompatActivity {
Button start;
public TextView showText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showText= (TextView)findViewById(R.id.textView);
start = (Button)findViewById(R.id.button);
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RetrieveFeedTask click1 = new RetrieveFeedTask();
click1.execute();
showText.setText(click1.getString());
}
});
}
}
And the class:
class RetrieveFeedTask extends AsyncTask<Void, Void, String> {
static final String API_URL = "http://numbersapi.com/random/trivia?json";
private Exception exception;
public String finalString;
protected void onPreExecute() { }
protected String doInBackground(Void... urls) {
try {
URL url = new URL(API_URL );
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
while ((finalString = bufferedReader.readLine()) != null) {
stringBuilder.append(finalString).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
if(response == null) {
response = "THERE WAS AN ERROR";
}
try {
JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
finalString = object.getString("text");
Log.i("Here",finalString);
} catch (JSONException e) {
}
}
public String getString() {
return this.finalString;
}
}
You require the finalString before it's populated with your data. the onPostExecute is executed after the doInBackground so you should pass your text view to your task and set it's value in the onPostExecute
public TextView showText;
public RetrieveFeedTask(TextView showText) { this.showText = showText; }
protected void onPostExecute(String response) {
if(response == null) {
response = "THERE WAS AN ERROR";
}
try {
JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
finalString = object.getString("text");
showText.setText(finalString ); // add this
Log.i("Here",finalString);
} catch (JSONException e) {
}
}
The problem is that showText.setText(click1.getString()); of your activity is called earlier than finalString = object.getString("text"); of your task.
Solution:
Create an interface:
public interface DataCallback {
void onNewData(String data);
}
and implement it in your activity:
public class MainActivity extends ... implements DataCallback
public void onNewData(String data) {
showText.setText(data);
}
Pass the interface to your asynctask when you create it:
RetrieveFeedTask click1 = new RetrieveFeedTask(this);
Call the interface inside the task in onPostExecute() to notify the activity that there is new data:
JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
finalString = object.getString("text");
callback.onNewData(finalString);
I simply want to play youtube url in WebView or VideoView. Suppose this . I have followed number of tutorials.But I am unable to find a way.
WebViewActivity
In onCreate()
webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setPluginState(PluginState.ON);
// webView.getSettings().setPluginsEnabled(true);
final Activity activity = this;
webView.setWebChromeClient(new WebChromeClient()
{
public void onProgressChanged(WebView view , int progress)
{
// Activities and WebViews measure progress with different
// scales.
// The progress meter will automatically disappear when we reach
// 100%
activity.setProgress(progress * 1000);
}
});
webView.setWebViewClient(new MyOwnWebViewClient());
webView.loadData(playVideo, "text/html", "utf-8");
//webView.loadUrl("http://www.androidbegin.com/tutorial/AndroidCommercial.3gp");
//webView.loadUrl("file:///android_asset/Videos/" + extra + ".htm");
webView.setWebViewClient(new MyOwnWebViewClient());
And MyOwnWebViewClient is
public class MyOwnWebViewClient extends WebViewClient
{
#Override
public boolean shouldOverrideUrlLoading(WebView view , String url)
{
view.loadUrl(url);
return true;
}
}
VideoActivity
In onCreate()
new VideoViewTask(VideoActivity.this, videoView).execute();
Where VideoViewTask.java is
public class VideoViewTask extends AsyncTask<String, Void, String>
{
ProgressDialog progressDialog;
Context contexto;
VideoView videoViewo;
public VideoViewTask(Context context,VideoView videoView)
{
contexto = context;
videoViewo = videoView;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = ProgressDialog.show(contexto, "", "Loading Video wait...", true);
}
#Override
protected String doInBackground(String... arg0)
{
String videoUrl = "";
try
{
String url = "http://www.androidbegin.com/tutorial/AndroidCommercial.3gp";//"http://www.youtube.com/watch?v=1FJHYqE0RDg";
videoUrl = getUrlVideoRTSP(url);
//Log.e("Video url for playing=========>>>>>", videoUrl);
}
catch (Exception e)
{
//Log.e("Login Soap Calling in Exception", e.toString());
}
return videoUrl;
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
progressDialog.dismiss();
videoViewo.setVideoURI(Uri.parse(result));
MediaController mc = new MediaController(contexto);
videoViewo.setMediaController(mc);
videoViewo.requestFocus();
videoViewo.start();
mc.show();
}
public static String getUrlVideoRTSP(String urlYoutube)
{
try
{
String gdy = "http://gdata.youtube.com/feeds/api/videos/";
DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
String id = extractYoutubeId(urlYoutube);
URL url = new URL(gdy + id);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
Document doc = documentBuilder.parse(connection.getInputStream());
Element el = doc.getDocumentElement();
NodeList list = el.getElementsByTagName("media:content");///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)
{
Log.e("Get Url Video RTSP Exception======>>", ex.toString());
}
return urlYoutube;
}
protected static String extractYoutubeId(String url) throws MalformedURLException
{
String id = null;
try
{
String query = new URL(url).getQuery();
if (query != null)
{
String[] param = query.split("&");
for (String row : param)
{
String[] param1 = row.split("=");
if (param1[0].equals("v"))
{
id = param1[1];
}
}
}
else
{
if (url.contains("embed"))
{
id = url.substring(url.lastIndexOf("/") + 1);
}
}
}
catch (Exception ex)
{
Log.e("Exception", ex.toString());
}
return id;
}
}
I simply want to play youtube url in my app. I have also try it by calling watchYoutubeVideo("oKiYuIsPxYk");
Where
public void watchYoutubeVideo(String id)
{
try
{
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube:" + id));
startActivity(intent);
}
catch (ActivityNotFoundException ex)
{
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.youtube.com/watch?v=" + id));
startActivity(intent);
}
}
please follow like below example. i have tried with android developers videos.its working fine.playing with in app only.
WebView wv=(WebView)findViewById(R.id.webview);
wv.getSettings().setJavaScriptEnabled(true);
//wv.getSettings().setPluginsEnabled(true);
final String mimeType = "text/html";
final String encoding = "UTF-8";
String html = getHTML();
wv.setWebChromeClient(new WebChromeClient() {
});
wv.loadDataWithBaseURL("", html, mimeType, encoding, "");
add above code in oncreate
public String getHTML() {
String html = "<iframe class=\"youtube-player\" style=\"border: 0; width: 100%; height: 95%; padding:0px; margin:0px\" id=\"ytplayer\" type=\"text/html\" src=\"http://www.youtube.com/embed/"
+ "s-4J7cijPAo"
+ "?fs=0\" frameborder=\"0\">\n"
+ "</iframe>\n";
return html;
insert your youtube video id like above.