i'm stuck with implementing following youtube method.
public abstract void loadVideos (List<String> videoIds)
Loads and plays a list of videos.
basically this is part of my code.
My ultimate goal is when user click on listitem that video plays or it automatically plays all three videos.
Can someone please help me.
private static final String1[] arry = {
new String1("Androidify App", "irH3OSOskcE", false),
new String1("Chrome Speed Tests", "nCgQDjiotG0", false),
new String1("Playlist: Google I/O 2012", "PL56D792A831D0C362", true)};
private static final String KEY_CURRENTLY_SELECTED_ID = "currentlySelectedId";
private YouTubePlayerView youTubePlayerView;
private YouTubePlayer player;
private ArrayAdapter<String1> videoAdapter1;
private ListView videoChooser1;
private StringBuilder logString;
private MyPlayerStateChangeListener playerStateChangeListener;
private MyPlaylistEventListener playlistEventListener;
private int currentlySelectedPosition;
private String currentlySelectedId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player_controls_demo);
youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_view);
videoChooser1 = (ListView) findViewById(R.id.listView1);
logString = new StringBuilder();
videoAdapter1 = new ArrayAdapter<String1>(this, android.R.layout.simple_list_item_1, arry);
videoChooser1.setAdapter(videoAdapter1);
videoChooser1.setOnItemClickListener(this);
youTubePlayerView.initialize(DeveloperKey.DEVELOPER_KEY, this);
playlistEventListener = new MyPlaylistEventListener();
playerStateChangeListener = new MyPlayerStateChangeListener();
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player,
boolean wasRestored) {
this.player = player;
player.setPlaylistEventListener(playlistEventListener);
player.setPlayerStateChangeListener(playerStateChangeListener);
if (!wasRestored) {
playVideoAtSelection();
}
}
#Override
protected YouTubePlayer.Provider getYouTubePlayerProvider() {
return youTubePlayerView;
}
private void playVideoAtSelection() {
String1 selectedEntry = videoAdapter1.getItem(currentlySelectedPosition);
if (selectedEntry.id != currentlySelectedId && player != null) {
currentlySelectedId = selectedEntry.id;
if (selectedEntry.isPlaylist) {
player.loadPlaylist(selectedEntry.id);
} else {
player.loadVideo(selectedEntry.id);
player.loadVideos(List<String>,selectedEntry.id);
}
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int pos, long id)
{
currentlySelectedPosition = pos;
playVideoAtSelection();
}
#Override
protected void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
state.putString(KEY_CURRENTLY_SELECTED_ID, currentlySelectedId);
}
#Override
protected void onRestoreInstanceState(Bundle state) {
super.onRestoreInstanceState(state);
currentlySelectedId = state.getString(KEY_CURRENTLY_SELECTED_ID);
}
private void log(String message) {
logString.append(message + "\n");
// eventLog.setText(logString);
}
private final class MyPlaylistEventListener implements PlaylistEventListener {
#Override
public void onNext() {
log("NEXT VIDEO");
}
#Override
public void onPrevious() {
log("PREVIOUS VIDEO");
}
#Override
public void onPlaylistEnded() {
log("PLAYLIST ENDED");
}
}
private final class MyPlayerStateChangeListener implements PlayerStateChangeListener {
String playerState = "UNINITIALIZED";
#Override
public void onLoading() {
playerState = "LOADING";
log(playerState);
}
#Override
public void onLoaded(String videoId) {
playerState = String.format("LOADED %s", videoId);
log(playerState);
}
#Override
public void onAdStarted() {
playerState = "AD_STARTED";
log(playerState);
}
#Override
public void onVideoStarted() {
playerState = "VIDEO_STARTED";
log(playerState);
}
#Override
public void onVideoEnded() {
playerState = "nCgQDjiotG0";
log(playerState);
}
#Override
public void onError(ErrorReason arg0) {
// TODO Auto-generated method stub
}
}
private static final class String1 {
public final String title;
public final String id;
public final boolean isPlaylist;
public String1(String title, String videoId, boolean isPlaylist) {
this.title = title;
this.id = videoId;
this.isPlaylist = isPlaylist;
}
#Override
public String toString() {
return title;
}
}
After few tries i figured it out, it is partially working in case if anyone else needs it
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player,
boolean wasRestored) {
this.player = player;
player.setPlaylistEventListener(playlistEventListener);
player.setPlayerStateChangeListener(playerStateChangeListener);
if (!wasRestored) {
ArrayList arrayList = new ArrayList();
arrayList.add((Object)("irH3OSOskcE"));
arrayList.add((Object)("nCgQDjiotG0"));
arrayList.add((Object)("irH3OSOskcE"));
player.loadVideos((List)(arrayList));
//playVideoAtSelection();
}
}
Related
We are currently using admob's interstitial ad in our app. What we have in our first splash screen is:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
getWindow().setNavigationBarColor(getResources().getColor(R.color.colorPrimary));
}
setContentView(R.layout.activity_splash);
mContext = this;
requestNewInterstitialList();
}
private void requestNewInterstitialList() {
InterstitialAd mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId(getString(R.string.gl_start_app_inter));
mInterstitialAd.loadAd(new AdRequest.Builder().build());
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdOpened() {
super.onAdOpened();
mContext.finish();
}
#Override
public void onAdLoaded() {
super.onAdLoaded();
if (mInterstitialAd != null && mInterstitialAd.isLoaded()) {
Intent intent = new Intent(SplashActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
mInterstitialAd.show();
}
}
});
}
I requested interstitial from onCreate() in our splash screen. Notice that in interstitial ad in onAdLoaded() I started MainActivity.class via intent and this will definitely start that screen without closing interstitial ad! So, it will just start new screen in background and show interstitial ad at a time! After that in onAdOpened() of ad I just finished my current activity(Splash screen) and that also that not affect the interstitial ad and in mean while when user close the ad in the behind main screen is loaded!
Now situation is that we have some sponsors and they want show custom built interstitial ad in our App! So, I made that in DialogFragment:
public class DF_Interstitial_Ad extends DialogFragment {
private LayoutInterstitialAdBinding mBinding;
private Context mContext;
private String adUrl;
private SimpleExoPlayer player;
private PlayerView exoPlayerView;
private long playBackPosition = 0;
private boolean isPlayerReady = false;
private boolean isOnPause = false;
private InterAdListener mAdListener = null;
public DF_Interstitial_Ad(#NonNull Context mContext, #NonNull String adUrl) {
this.mContext = mContext;
this.adUrl = adUrl;
mBinding = DataBindingUtil.inflate(LayoutInflater.from(mContext), R.layout.layout_interstitial_ad, null,
false);
dataSourceFactory = buildDataSourceFactory();
exoPlayerView = mBinding.playerAd;
initializePlayer();
}
private class ModelInterStitialAd {
private String title;
private String description;
private String appIconUrl;
private String videoUrl;
private String installUrl;
private float rattings;
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public String getAppIconUrl() {
return appIconUrl;
}
public String getVideoUrl() {
return videoUrl;
}
public String getInstallUrl() {
return installUrl;
}
public float getRattings() {
return rattings;
}
}
//region Data source...
private DataSource.Factory dataSourceFactory;
private MediaSource mediaSource;
private AdsLoader adsLoader;
private void releaseAdsLoader() {
if (adsLoader != null) {
adsLoader.release();
adsLoader = null;
Objects.requireNonNull(exoPlayerView.getOverlayFrameLayout()).removeAllViews();
}
}
private void releasePlayer() {
if (player != null) {
playBackPosition = player.getCurrentPosition();
player.release();
player = null;
mediaSource = null;
Log.i("Player>>>", "Player released");
}
if (adsLoader != null) {
releaseAdsLoader();
}
}
private DataSource.Factory buildDataSourceFactory() {
return MyApplication.getInstance().buildDataSourceFactory(null);
}
//endregion
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(STYLE_NORMAL, R.style.FullScreenDialog);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Objects.requireNonNull(Objects.requireNonNull(getDialog()).getWindow()).addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
if (mAdListener != null) {
mAdListener.onShow();
}
playPausePlayer(true);
return mBinding.getRoot();
}
#Override
public void onResume() {
super.onResume();
isOnPause = false;
playPausePlayer(true);
}
#Override
public void onPause() {
super.onPause();
isOnPause = true;
playPausePlayer(true);
}
#Override
public void onDestroy() {
super.onDestroy();
if (mAdListener != null) {
mAdListener.onClose();
}
releasePlayer();
}
//region Player zone...
private void initializePlayer() {
player = new SimpleExoPlayer.Builder(mContext).build();
player.setPlayWhenReady(false);
exoPlayerView.setPlayer(player);
exoPlayerView.setBackgroundColor(Color.BLACK);
exoPlayerView.setUseController(false);
mBinding.viewMain.setOnClickListener(v -> {
if (isPlayerReady)
if (player != null) {
if (player.getPlaybackState() == Player.STATE_ENDED) {
mBinding.ivPlayVideo.setVisibility(View.VISIBLE);
playBackPosition = 0;
playPausePlayer(true);
} else {
if (player.getPlayWhenReady()) {
playPausePlayer(false);
mBinding.ivPlayVideo.setVisibility(View.VISIBLE);
} else {
playPausePlayer(true);
mBinding.ivPlayVideo.setVisibility(View.GONE);
}
}
}
});
player.addListener(new Player.EventListener() {
#Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
if (playbackState == Player.STATE_ENDED) {
mBinding.ivPlayVideo.setVisibility(View.VISIBLE);
} else if (playbackState == Player.STATE_READY) {
if (!isPlayerReady) {
isPlayerReady = true;
if (mAdListener != null) {
mAdListener.onLoaded();
}
}
if (isOnPause)
playPausePlayer(false);
}
}
});
prepareExoPlayer();
}
private void prepareExoPlayer() {
mediaSource = buildMediaSource(Uri.parse(adUrl));
player.prepare(mediaSource, true, false);
}
private MediaSource buildMediaSource(Uri uri) {
CacheDataSourceFactory cacheDataSourceFactory = new CacheDataSourceFactory(VideoCache.getInstance(mContext),
dataSourceFactory);
#C.ContentType int type = Util.inferContentType(uri, null);
switch (type) {
case C.TYPE_HLS:
return new HlsMediaSource.Factory(cacheDataSourceFactory).setAllowChunklessPreparation(true).createMediaSource(uri);
case C.TYPE_OTHER:
return new ProgressiveMediaSource.Factory(cacheDataSourceFactory).createMediaSource(uri);
case C.TYPE_DASH:
case C.TYPE_SS:
default:
throw new IllegalStateException("Unsupported type: " + type);
}
}
private void playPausePlayer(boolean play) {
if (player != null) {
if (play) {
player.seekTo(playBackPosition);
player.setPlayWhenReady(true);
player.getPlaybackState();
mBinding.ivPlayVideo.setVisibility(View.GONE);
} else {
playBackPosition = player.getCurrentPosition();
player.setPlayWhenReady(false);
player.getPlaybackState();
mBinding.ivPlayVideo.setVisibility(View.VISIBLE);
}
}
}
//endregion
public void setmAdListener(InterAdListener mAdListener) {
this.mAdListener = mAdListener;
}
public boolean isLoaded() {
return isPlayerReady;
}
}
This is my DialogFragment in which I implemented my own custom interstitial ad. So, after that I just request it regularly same as admob's interstitial ad from splash screen like:
private void requestMyInterstitialAd() {
DF_Interstitial_Ad dfInterstitialAd = new DF_Interstitial_Ad(mContext, "https://booads.s3.ap-south-1.amazonaws.com/output.mp4");
dfInterstitialAd.setmAdListener(new InterAdListener() {
#Override
public void onLoaded() {
super.onLoaded();
if (dfInterstitialAd != null && dfInterstitialAd.isLoaded()) {
Intent intent = new Intent(SplashActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
dfInterstitialAd.show(getSupportFragmentManager(), "SplashScreen");
}
}
#Override
public void onShow() {
super.onShow();
}
#Override
public void onClose() {
super.onClose();
}
});
}
It is show next screen(MainActivity) in front of screen rather than DialogFragment of ad! So, what to do? for showing ad in front of user and in mean while open next activity behind the ad! I already tried showing ad in activity rather than DialogFragment but its also not working for me!
I am using quickblox for my android application. I am able to register, login user, even add custom objects and retrieve them from the quick-blox server, but in chatting listing screen my count is coming wrong.
I am getting issue with unread count
Here is my code flow:-
public class ConversationFragment extends Fragment implements Observer, DialogsManager.ManagingDialogsCallbacks {
ConversationViewModel conversationViewModel;
FragmentConversationBinding binding;
QBChatDialogMessageListener allDialogsMessagesListener;
SystemMessagesListener systemMessagesListener;
QBSystemMessagesManager systemMessagesManager;
QBIncomingMessagesManager incomingMessagesManager;
private DialogsManager dialogsManager;
public ConversationFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_conversation, container, false);
getActivity().getWindow().setBackgroundDrawableResource(R.drawable.bg_img);
View view = binding.getRoot();
systemMessagesListener = new SystemMessagesListener();
dialogsManager = new DialogsManager();
return view;
}
private void setUpModel() {
Bundle mBundle = getArguments();
if (mBundle != null) {
conversationViewModel = new ConversationViewModel(getActivity(), binding, getArguments().getString("DialogIdData"));
} else {
conversationViewModel = new ConversationViewModel(getActivity(), binding, "");
}
binding.setConversationViewModel(conversationViewModel);
setUpObserver(conversationViewModel);
}
private void setUpObserver(ConversationViewModel observer) {
observer.addObserver(this);
}
#Override
public void update(Observable o, Object arg) {
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onResume() {
super.onResume();
setUpModel();
}
#Override
public void onPause() {
super.onPause();
unregisterQbChatListeners();
}
public void unregisterQbChatListeners() {
if (incomingMessagesManager != null) {
incomingMessagesManager.removeDialogMessageListrener(allDialogsMessagesListener);
}
if (systemMessagesManager != null) {
systemMessagesManager.removeSystemMessageListener(systemMessagesListener);
}
dialogsManager.removeManagingDialogsCallbackListener(this);
}
#Override
public void onDialogCreated(QBChatDialog chatDialog) {
}
#Override
public void onDialogUpdated(String chatDialog) {
}
#Override
public void onNewDialogLoaded(QBChatDialog chatDialog) {
}
private class SystemMessagesListener implements QBSystemMessageListener {
#Override
public void processMessage(final QBChatMessage qbChatMessage) {
dialogsManager.onSystemMessageReceived(qbChatMessage);
}
#Override
public void processError(QBChatException e, QBChatMessage qbChatMessage) {
}
}
private BroadcastReceiver mNotificationReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
}
};
}
Here is my Fragment viewModel code :-
public class ConversationViewModel extends Observable implements DialogsManager.ManagingDialogsCallbacks {
private static final int REQUEST_DIALOG_ID_FOR_UPDATE = 165;
public Context mContext;
FragmentConversationBinding binding;
private ActionMode currentActionMode;
public QBRequestGetBuilder requestBuilder;
private int skipRecords = 0;
private DialogsAdapter dialogsAdapter;
private QBChatDialogMessageListener allDialogsMessagesListener;
private SystemMessagesListener systemMessagesListener;
private QBSystemMessagesManager systemMessagesManager;
private QBIncomingMessagesManager incomingMessagesManager;
private DialogsManager dialogsManager;
private QBUser currentUser;
private String id;
public ConversationViewModel(Context mContext, FragmentConversationBinding binding, String Dialogid) {
this.mContext = mContext;
this.binding = binding;
this.id = Dialogid;
initUI();
}
public void initUI() {
allDialogsMessagesListener = new AllDialogsMessageListener();
systemMessagesListener = new SystemMessagesListener();
dialogsManager = new DialogsManager();
currentUser = ChatHelper.getCurrentUser();
initList();
registerQbChatListeners();
if (QbDialogHolder.getInstance().getDialogs().size() > 0) {
loadDialogsFromQb(true, true);
} else {
loadDialogsFromQb(false, true);
}
if (!id.isEmpty()) {
loadUpdatedDialog(id);
id = "";
} else {
updateDialogsList();
}
}
public void initList() {
dialogsAdapter = new DialogsAdapter(mContext, new ArrayList<>(QbDialogHolder.getInstance().getDialogs().values()));
binding.listDialogsChats.setAdapter(dialogsAdapter);
binding.listDialogsChats.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
QBChatDialog selectedDialog = (QBChatDialog) parent.getItemAtPosition(position);
if (currentActionMode == null) {
ChatActivity.startForResult(((Activity) mContext), REQUEST_DIALOG_ID_FOR_UPDATE, selectedDialog);
} else {
dialogsAdapter.toggleSelection(selectedDialog);
}
}
});
binding.listDialogsChats.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
QBChatDialog selectedDialog = (QBChatDialog) parent.getItemAtPosition(position);
dialogsAdapter.selectItem(selectedDialog);
return true;
}
});
requestBuilder = new QBRequestGetBuilder();
binding.swipyRefreshLayout.setOnRefreshListener(new SwipyRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh(SwipyRefreshLayoutDirection direction) {
requestBuilder.setSkip(skipRecords += ChatHelper.DIALOG_ITEMS_PER_PAGE);
loadDialogsFromQb(true, false);
}
});
}
private void loadUpdatedDialog(String dialogId) {
ChatHelper.getInstance().getDialogById(dialogId, new QbEntityCallbackImpl<QBChatDialog>() {
#Override
public void onSuccess(QBChatDialog result, Bundle bundle) {
QbDialogHolder.getInstance().addDialog(result);
updateDialogsAdapter();
}
#Override
public void onError(QBResponseException e) {
}
});
}
public void updateDialogsList() {
requestBuilder.setSkip(skipRecords = 0);
loadDialogsFromQb(true, true);
}
#Override
public void onDialogCreated(QBChatDialog chatDialog) {
updateDialogsAdapter();
}
#Override
public void onDialogUpdated(String chatDialog) {
updateDialogsAdapter();
}
#Override
public void onNewDialogLoaded(QBChatDialog chatDialog) {
updateDialogsAdapter();
}
private void registerQbChatListeners() {
incomingMessagesManager = QBChatService.getInstance().getIncomingMessagesManager();
systemMessagesManager = QBChatService.getInstance().getSystemMessagesManager();
if (incomingMessagesManager != null) {
incomingMessagesManager.addDialogMessageListener(allDialogsMessagesListener != null
? allDialogsMessagesListener : new AllDialogsMessageListener());
}
if (systemMessagesManager != null) {
systemMessagesManager.addSystemMessageListener(systemMessagesListener != null
? systemMessagesListener : new SystemMessagesListener());
}
dialogsManager.addManagingDialogsCallbackListener(this);
}
private class SystemMessagesListener implements QBSystemMessageListener {
#Override
public void processMessage(final QBChatMessage qbChatMessage) {
dialogsManager.onSystemMessageReceived(qbChatMessage);
}
#Override
public void processError(QBChatException e, QBChatMessage qbChatMessage) {
}
}
private class AllDialogsMessageListener extends QbChatDialogMessageListenerImp {
#Override
public void processMessage(final String dialogId, final QBChatMessage qbChatMessage, Integer senderId) {
if (!senderId.equals(ChatHelper.getCurrentUser().getId())) {
dialogsManager.onGlobalMessageReceived(dialogId, qbChatMessage);
}
}
}
public void updateDialogsAdapter() {
dialogsAdapter.updateList(new ArrayList<>(QbDialogHolder.getInstance().getDialogs().values()));
}
public void loadDialogsFromQb(final boolean silentUpdate, final boolean clearDialogHolder) {
if (!silentUpdate) {
binding.progressDialogs.setVisibility(View.VISIBLE);
}
ChatHelper.getInstance().getDialogs(requestBuilder, new QBEntityCallback<ArrayList<QBChatDialog>>() {
#Override
public void onSuccess(ArrayList<QBChatDialog> dialogs, Bundle bundle) {
binding.progressDialogs.setVisibility(View.GONE);
binding.swipyRefreshLayout.setRefreshing(false);
if (clearDialogHolder) {
QbDialogHolder.getInstance().clear();
}
QbDialogHolder.getInstance().addDialogs(dialogs);
updateDialogsAdapter();
}
#Override
public void onError(QBResponseException e) {
binding.progressDialogs.setVisibility(View.GONE);
binding.swipyRefreshLayout.setRefreshing(false);
Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
Here is my Chat Activity:-
public class ChatActivity extends BindingActivity<ActivityChatBinding> implements OnImagePickedListener {
ChatViewModel chatViewModel;
public static final int REQUEST_CODE_ATTACHMENT = 721;
public static final String EXTRA_DIALOG_ID = "dialogId";
#Override
protected int getLayoutId() {
return R.layout.activity_chat;
}
public static void startForResult(Activity activity, int code, QBChatDialog dialogId) {
Intent intent = new Intent(activity, ChatActivity.class);
intent.putExtra(ChatActivity.EXTRA_DIALOG_ID, dialogId);
activity.startActivityForResult(intent, code);
}
#Override
public void setInitBinding() {
getWindow().setBackgroundDrawableResource(R.drawable.bg_img);
chatViewModel = new ChatViewModel(this, binding);
binding.setChatViewModel(chatViewModel);
}
#Override
protected void setUpObserver() {
chatViewModel.addObserver(this);
}
#Override
public void update(Observable o, Object arg) {
}
#Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
#Override
public void onBackPressed() {
binding.getChatViewModel().releaseChat();
binding.getChatViewModel().sendDialogId();
super.onBackPressed();
}
#Override
public void onImagePicked(int requestCode, File file) {
switch (requestCode) {
case REQUEST_CODE_ATTACHMENT:
binding.getChatViewModel().attachmentPreviewAdapter.add(file);
break;
}
}
#Override
public void onImagePickError(int requestCode, Exception e) {
Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
}
#Override
public void onImagePickClosed(int requestCode) {
}
}
Chat Activity View Model :-
public class ChatViewModel extends Observable {
public Context mContext;
ActivityChatBinding binding;
public static final String TAG = ChatActivity.class.getSimpleName();
public static final int REQUEST_CODE_ATTACHMENT = 721;
public static final String PROPERTY_SAVE_TO_HISTORY = "save_to_history";
public static final String EXTRA_DIALOG_ID = "dialogId";
public ChatAdapter chatAdapter;
public AttachmentPreviewAdapter attachmentPreviewAdapter;
public QBChatDialog qbChatDialog;
public ArrayList<QBChatMessage> unShownMessages;
public int skipPagination = 0;
public ChatMessageListener chatMessageListener;
QBPrivacyList qbPrivacyList;
public static boolean mBlock;
public static int userId, recipientId;
public QBPrivacyListsManager privacyListsManager;
public ObservableField<String> chatMessage = new ObservableField<>("");
public ChatViewModel(Context mContext, ActivityChatBinding binding) {
this.mContext = mContext;
this.binding = binding;
Log.v(TAG, "onCreate ChaActivity on Thread ID = " + Thread.currentThread().getId());
qbChatDialog = (QBChatDialog) ((Activity) mContext).getIntent().getSerializableExtra(EXTRA_DIALOG_ID);
Log.v(TAG, "deserialized dialog = " + qbChatDialog);
qbChatDialog.initForChat(QBChatService.getInstance());
chatMessageListener = new ChatMessageListener();
qbPrivacyList = new QBPrivacyList();
privacyListsManager = QBChatService.getInstance().getPrivacyListsManager();
qbChatDialog.addMessageListener(chatMessageListener);
initViews();
initChat();
}
public void initViews() {
try {
recipientId = qbChatDialog.getRecipientId();
userId = qbChatDialog.getUserId();
getPrivacyList();
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
} catch (XMPPException.XMPPErrorException e) {
e.printStackTrace();
} catch (SmackException.NoResponseException e) {
e.printStackTrace();
}
attachmentPreviewAdapter = new AttachmentPreviewAdapter(mContext,
new AttachmentPreviewAdapter.OnAttachmentCountChangedListener() {
#Override
public void onAttachmentCountChanged(int count) {
binding.attachmentContainer.setVisibility(count == 0 ? View.GONE : View.VISIBLE);
}
},
new AttachmentPreviewAdapter.OnAttachmentUploadErrorListener() {
#Override
public void onAttachmentUploadError(QBResponseException e) {
Toast.makeText(mContext, e.toString(), Toast.LENGTH_SHORT).show();
}
});
binding.attachmentAdapter.setAdapter(attachmentPreviewAdapter);
}
public void onAttachmentsClick(View view) {
new ImagePickHelper().pickAnImage(((FragmentActivity) mContext), REQUEST_CODE_ATTACHMENT);
}
private void initChat() {
switch (qbChatDialog.getType()) {
case PRIVATE:
loadDialogUsers();
break;
default:
Toaster.shortToast(String.format("%s %s", getString(R.string.chat_unsupported_type), qbChatDialog.getType().name()));
((Activity) mContext).finish();
break;
}
}
public void loadDialogUsers() {
ChatHelper.getInstance().getUsersFromDialog(qbChatDialog, new QBEntityCallback<ArrayList<QBUser>>() {
#Override
public void onSuccess(ArrayList<QBUser> users, Bundle bundle) {
String chatName = QbDialogUtils.getDialogName(qbChatDialog);
binding.dialogName.setText(chatName);
loadChatHistory();
}
#Override
public void onError(QBResponseException e) {
Toast.makeText(mContext, e.toString(), Toast.LENGTH_SHORT).show();
}
});
}
public void loadChatHistory() {
ChatHelper.getInstance().loadChatHistory(qbChatDialog, skipPagination, new QBEntityCallback<ArrayList<QBChatMessage>>() {
#Override
public void onSuccess(ArrayList<QBChatMessage> messages, Bundle args) {
Collections.reverse(messages);
if (chatAdapter == null) {
chatAdapter = new ChatAdapter(mContext, qbChatDialog, messages);
chatAdapter.setPaginationHistoryListener(new PaginationHistoryListener() {
#Override
public void downloadMore() {
loadChatHistory();
}
});
chatAdapter.setOnItemInfoExpandedListener(new ChatAdapter.OnItemInfoExpandedListener() {
#Override
public void onItemInfoExpanded(final int position) {
if (isLastItem(position)) {
((Activity) mContext).runOnUiThread(new Runnable() {
#Override
public void run() {
binding.listChat.setSelection(position);
}
});
} else {
binding.listChat.smoothScrollToPosition(position);
}
}
private boolean isLastItem(int position) {
return position == chatAdapter.getCount() - 1;
}
});
if (unShownMessages != null && !unShownMessages.isEmpty()) {
List<QBChatMessage> chatList = chatAdapter.getList();
for (QBChatMessage message : unShownMessages) {
if (!chatList.contains(message)) {
chatAdapter.add(message);
}
}
}
binding.listChat.setAdapter(chatAdapter);
binding.listChat.setAreHeadersSticky(false);
binding.listChat.setDivider(null);
} else {
chatAdapter.addList(messages);
binding.listChat.setSelection(messages.size());
}
binding.progressBar.setVisibility(View.GONE);
}
#Override
public void onError(QBResponseException e) {
binding.progressBar.setVisibility(View.GONE);
skipPagination -= ChatHelper.CHAT_HISTORY_ITEMS_PER_PAGE;
Toast.makeText(mContext, e.toString(), Toast.LENGTH_SHORT).show();
}
});
skipPagination += ChatHelper.CHAT_HISTORY_ITEMS_PER_PAGE;
QBRestChatService.markMessagesAsRead(qbChatDialog.getDialogId(), null);
}
public class ChatMessageListener extends QbChatDialogMessageListenerImp {
#Override
public void processMessage(String s, QBChatMessage qbChatMessage, Integer integer) {
showMessage(qbChatMessage);
}
}
public void showMessage(QBChatMessage message) {
if (chatAdapter != null) {
chatAdapter.add(message);
scrollMessageListDown();
} else {
if (unShownMessages == null) {
unShownMessages = new ArrayList<>();
}
unShownMessages.add(message);
}
}
public void scrollMessageListDown() {
binding.listChat.setSelection(binding.listChat.getCount() - 1);
}
public void onSendChatClick(View view) {
int totalAttachmentsCount = attachmentPreviewAdapter.getCount();
Collection<QBAttachment> uploadedAttachments = attachmentPreviewAdapter.getUploadedAttachments();
if (!uploadedAttachments.isEmpty()) {
if (uploadedAttachments.size() == totalAttachmentsCount) {
for (QBAttachment attachment : uploadedAttachments) {
sendChatMessage(null, attachment);
}
} else {
Toaster.shortToast(R.string.chat_wait_for_attachments_to_upload);
}
}
String text = binding.getChatViewModel().chatMessage.get().trim();
if (!TextUtils.isEmpty(text)) {
sendChatMessage(text, null);
}
}
public void sendChatMessage(String text, QBAttachment attachment) {
QBChatMessage chatMessage = new QBChatMessage();
if (attachment != null) {
chatMessage.addAttachment(attachment);
} else {
chatMessage.setBody(text);
}
chatMessage.setProperty(PROPERTY_SAVE_TO_HISTORY, "1");
chatMessage.setDateSent(System.currentTimeMillis() / 1000);
chatMessage.setMarkable(true);
if (!QBDialogType.PRIVATE.equals(qbChatDialog.getType()) && !qbChatDialog.isJoined()) {
Toaster.shortToast("You're still joining a group chat, please wait a bit");
return;
}
try {
qbChatDialog.sendMessage(chatMessage);
if (QBDialogType.PRIVATE.equals(qbChatDialog.getType())) {
showMessage(chatMessage);
}
if (attachment != null) {
attachmentPreviewAdapter.remove(attachment);
} else {
binding.getChatViewModel().chatMessage.set("");
}
} catch (SmackException.NotConnectedException e) {
Log.w(TAG, e);
Toaster.shortToast("Can't send a message, You are not connected to chat");
}
}
public void leaveGroupDialog() {
try {
ChatHelper.getInstance().leaveChatDialog(qbChatDialog);
} catch (XMPPException | SmackException.NotConnectedException e) {
Log.w(TAG, e);
}
}
public void releaseChat() {
qbChatDialog.removeMessageListrener(chatMessageListener);
if (!QBDialogType.PRIVATE.equals(qbChatDialog.getType())) {
leaveGroupDialog();
}
}
public void sendDialogId() {
Intent result = new Intent();
result.putExtra(EXTRA_DIALOG_ID, qbChatDialog.getDialogId());
((Activity) mContext).setResult(RESULT_OK, result);
}
public void finishActivity(View view) {
((Activity) mContext).finish();
}
public void clickButtonBlock(View view) {
AppUtils.dialog(mContext);
if (mBlock) {
onClickUnblock();
} else {
onClickBlock();
}
}
public void getPrivacyList() throws SmackException.NotConnectedException, XMPPException.XMPPErrorException, SmackException.NoResponseException {
QBPrivacyListsManager privacyListsManager = QBChatService.getInstance().getPrivacyListsManager();
QBPrivacyList privacyList = privacyListsManager.getPrivacyList("public");
List<QBPrivacyListItem> items = privacyList.getItems();
int i;
for (i = 0; i < privacyList.getItems().size(); i++) {
QBPrivacyListItem item = items.get(i);
String valueForType = item.getValueForType();
String[] splitvalueType = valueForType.split("-");
String blockId = splitvalueType[0];
if (blockId.equalsIgnoreCase(String.valueOf(recipientId))) {
mBlock = true;
binding.tvBlock.setText("Unblock");
break;
} else {
binding.tvBlock.setText("Block");
}
}
}
}
The problem is chatDialog.getUnreadMessageCount() giving me count 2 when I once enter in chat room and come back to my chat listing page.
Description on issue:-
Example:-
I have installed my application in two devices. when i send message from one (Device A) to other (Device B).The device B will display correct Unread count i.e 1 . Now when i click on chat dialog and get entered inside the chat room (of Device B). and come back to it's listing page and then again try to send message from Device A to device B . This time the unread count comes as 2 but it should be one as i already viewed my previous message. This get more worse if i try to open my chat room again to read the message(Device B) and get back to my listing page(Device B) after reading the message . This time if I send the message from Device A to Device B, Then the count came out as "5" just for my one message this thing is making me sick, I debugged the whole code, it's chatDialog .getUnreadMessageCount() who is returning me count "5", I don't know why my previous messages are not counted as being read messages and why everytime I open chat room one additional number gets added up inside the unread count.Please help me out , i am scratching my head from past two days.
Your help will be greatly Appreciated.
Thanks
Problem is that your AllDialogsMessageListener is not getting unregistered so unregister it by calling unregisterQbChatListeners(); when you will be opening your chat room screen . Every thing will work fine once you do that.
This what i mean :-
binding.listDialogsChats.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
QBChatDialog selectedDialog = (QBChatDialog) parent.getItemAtPosition(position);
if (currentActionMode == null) {
unregisterQbChatListeners();
ChatActivity.startForResult(((Activity) mContext), REQUEST_DIALOG_ID_FOR_UPDATE, selectedDialog);
} else {
dialogsAdapter.toggleSelection(selectedDialog);
}
}
});
private void unregisterQbChatListeners() {
if (incomingMessagesManager != null) {
incomingMessagesManager.removeDialogMessageListrener(allDialogsMessagesListener);
}
if (systemMessagesManager != null) {
systemMessagesManager.removeSystemMessageListener(systemMessagesListener);
}
dialogsManager.removeManagingDialogsCallbackListener(this);
}
cheers!!!
Please use this code below :
QBChatService.markMessagesAsRead("YOUR_DIALOG_ID", null, new QBEntityCallback<Void>() {
#Override
public void onSuccess(Void aVoid, Bundle bundle) {
QBRequestGetBuilder requestBuilder = new QBRequestGetBuilder();
requestBuilder.eq("_id", Team.getCurrent().getChatId());
QBChatService.getChatDialogs(null, requestBuilder, new QBEntityCallback<ArrayList<QBDialog>>() {
#Override
public void onSuccess(ArrayList<QBDialog> qbDialogs, Bundle bundle) {
if (qbDialogs != null && qbDialogs.size() > 0) {
QBDialog dialog = qbDialogs.get(0);//here you get your dialog with unreadMessageCount = 0
}
}
#Override
public void onError(QBResponseException e) {
}
});
}
#Override
public void onError(QBResponseException e) {
}
});
I am trying to implement to play youtube video in my app using youtubeplayer view when user clicks on button but its just playing for a millisecond,after that it just stop.App is not crashing but video is also not playing.
Code for the same is-
public class PlayVideo extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
public static final String API_KEY = "xxxx";
String videoId;
String url="http://www.youtube.com/xxx";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/** attaching layout xml **/
setContentView(R.layout.activity_video_view);
/** Initializing YouTube player view **/
YouTubePlayerView youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_player);
youTubePlayerView.initialize(API_KEY, this);
videoId=getYoutubeVideoId(url);
Log.e("id",videoId);
//videoId=getIntent().getExtras().getString("url");
}
#Override
public void onInitializationFailure(Provider provider, YouTubeInitializationResult result) {
Toast.makeText(this, "Failured to Initialize!", Toast.LENGTH_LONG).show();
}
#Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored) {
/** add listeners to YouTubePlayer instance **/
player.setPlayerStateChangeListener(playerStateChangeListener);
player.setPlaybackEventListener(playbackEventListener);
/** Start buffering **/
if (!wasRestored) {
player.cueVideo(videoId);
}
}
private PlaybackEventListener playbackEventListener = new PlaybackEventListener() {
#Override
public void onBuffering(boolean arg0) {
Log.e("on","buffer");
}
#Override
public void onPaused() {
Log.e("on","pause");
}
#Override
public void onPlaying() {
Log.e("on","play");
}
#Override
public void onSeekTo(int arg0) {
Log.e("on","seekto");
}
#Override
public void onStopped() {
Log.e("on","stop");
}
};
private PlayerStateChangeListener playerStateChangeListener = new PlayerStateChangeListener() {
#Override
public void onAdStarted() {
Log.e("on","ad");
}
#Override
public void onLoaded(String arg0) {
Log.e("on","loaded");
}
#Override
public void onLoading() {
Log.e("on","loading");
}
#Override
public void onVideoEnded() {
Log.e("on","vidEnd");
}
#Override
public void onVideoStarted() {
Log.e("on","vidStart");
}
#Override
public void onError(ErrorReason arg0) {
// TODO Auto-generated method stub
}
};
public static String getYoutubeVideoId(String youtubeUrl)
{
String video_id="";
if (youtubeUrl != null && youtubeUrl.trim().length() > 0 && youtubeUrl.startsWith("http"))
{
String expression = "^.*((youtu.be"+ "\\/)" + "|(v\\/)|(\\/u\\/w\\/)|(embed\\/)|(watch\\?))\\??v?=?([^#\\&\\?]*).*"; // var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
CharSequence input = youtubeUrl;
Pattern pattern = Pattern.compile(expression,Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(input);
if (matcher.matches())
{
String groupIndex1 = matcher.group(7);
if(groupIndex1!=null && groupIndex1.length()==11)
video_id = groupIndex1;
}
}
return video_id;
}
}
xml file-
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.youtube.player.YouTubePlayerView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/youtube_player"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fff"
android:padding="5dp" />
warning in logcat-
W/YouTubeAndroidPlayerAPI(8722): YouTube video playback stopped due to unauthorized overlay on top of player. The YouTubePlayerView is not contained inside its ancestor com.google.android.youtube.player.YouTubePlayerView{41c88550 V.E..... ........ 0,0-480,270 #7f05003d app:id/youtube_player}. The distances between the ancestor's edges and that of the YouTubePlayerView is: left: -8, top: -8, right: -8, bottom: -8 (these should all be positive).
This issue is solved by using youtubeplayer fragment rather than youtubeplayer view.Code for the same is-
xml-
<LinearLayout 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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".MainActivity" >
<fragment
android:name="com.google.android.youtube.player.YouTubePlayerFragment"
android:id="#+id/youtubeplayerfragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
java file-
public class PlayVideo extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener{
public static final String DEVELOPER_KEY = "your api key";
private static final int RECOVERY_DIALOG_REQUEST = 1;
String url="your video url";
String VIDEO_ID;
YouTubePlayerFragment myYouTubePlayerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_view);
myYouTubePlayerFragment = (YouTubePlayerFragment)getFragmentManager()
.findFragmentById(R.id.youtubeplayerfragment);
myYouTubePlayerFragment.initialize(DEVELOPER_KEY, this);
VIDEO_ID=getYoutubeVideoId(url);
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider,
YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show();
} else {
String errorMessage = String.format(
"There was an error initializing the YouTubePlayer (%1$s)",
errorReason.toString());
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
}
#Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player,
boolean wasRestored) {
if (!wasRestored) {
player.cueVideo(VIDEO_ID);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_DIALOG_REQUEST) {
// Retry initialization if user performed a recovery action
getYouTubePlayerProvider().initialize(DEVELOPER_KEY, this);
}
}
protected YouTubePlayer.Provider getYouTubePlayerProvider() {
return (YouTubePlayerView)findViewById(R.id.youtubeplayerfragment);
}
public static String getYoutubeVideoId(String youtubeUrl)
{
String video_id="";
if (youtubeUrl != null && youtubeUrl.trim().length() > 0 && youtubeUrl.startsWith("http"))
{
String expression = "^.*((youtu.be"+ "\\/)" + "|(v\\/)|(\\/u\\/w\\/)|(embed\\/)|(watch\\?))\\??v?=?([^#\\&\\?]*).*"; // var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
CharSequence input = youtubeUrl;
Pattern pattern = Pattern.compile(expression,Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(input);
if (matcher.matches())
{
String groupIndex1 = matcher.group(7);
if(groupIndex1!=null && groupIndex1.length()==11)
video_id = groupIndex1;
}
}
return video_id;
}
}
Add internet permission in your manifest file.
I am using YouTubeFragment in an Android app and getting following crash on Android 4+ devices.
java.lang.IllegalStateException: Not connected. Call connect() and wait for onConnected() to be called.
at com.google.android.youtube.player.a.at.i(Unknown Source)
at com.google.android.youtube.player.a.an.k(Unknown Source)
at com.google.android.youtube.player.a.an.a(Unknown Source)
at com.google.android.youtube.player.a.ao.<init>(Unknown Source)
at com.google.android.youtube.player.a.f.a(Unknown Source)
at com.google.android.youtube.player.q.a(Unknown Source)
at com.google.android.youtube.player.a.at.g(Unknown Source)
at com.google.android.youtube.player.a.ax.a(Unknown Source)
at com.google.android.youtube.player.a.aw.a(Unknown Source)
at com.google.android.youtube.player.a.av.handleMessage(Unknown Source)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5450)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1187)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
at dalvik.system.NativeStart.main(Native Method)
The fragment is being started like this:
XYouTubeFragment yFragment = XYouTubeFragment.newInstance(ytVideoId);
activity.commitFragment(yFragment);
and defined like this:
public class XYouTubeFragment extends YouTubePlayerSupportFragment {
public static XYouTubeFragment newInstance(String url) {
XYouTubeFragment youTubeFrag = new XYouTubeFragment();
Bundle bundle = new Bundle();
bundle.putString("url", url);
youTubeFrag.setArguments(bundle);
youTubeFrag.init();
return youTubeFrag;
}
private void init() {
initialize(Constants.YOUTUBE_API_KEY, new OnInitializedListener() {
#Override
public void onInitializationFailure(Provider arg0, YouTubeInitializationResult arg1) { }
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
player.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
if (!wasRestored) {
player.loadVideo(getArguments().getString("url"), 0);
}
}
});
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
MainActivity activity = (MainActivity) getActivity();
activity.getSupportActionBar().hide();
activity.findViewById(R.id.alert_list).setVisibility(View.GONE);
}
}
Any idea what could be wrong?
public class YoutubeManager implements YouTubePlayer.OnInitializedListener {
String VideoTitle;
String VideoIdLoaded;
boolean videoTitleEnabled;
boolean isPreLoaded;
public void loadVideoWithId(String videoId) {
}
public static final String DEFAULT_API_KEY = "Your api key";
String appKey;
String searchKey;
String videoId_local;
String userId_local;
boolean firstRun;
Activity mActivity;
YouTubePlayer mYoutubePlayer;
private YouTubeFragment youTubePlayerFragment;
private MyPlayerStateChangeListener myPlayerStateChangeListener;
private MyPlaybackEventListener myPlaybackEventListener;
public YoutubeManager(Activity activity, String key, int containerId, int windowWidth, int windowHeight) {
mActivity = activity;
appKey = key;
searchKey = null;
videoId_local = null;
userId_local = null;
firstRun = true;
offsetTime = 0D;
myPlayerStateChangeListener = new MyPlayerStateChangeListener();
myPlaybackEventListener = new MyPlaybackEventListener();
FragmentManager fragmentManager = activity.getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
YouTubePlayerFragment = new YouTubeFragment();
ViewGroup.MarginLayoutParams params =
new ViewGroup.MarginLayoutParams(windowWidth / 2,
windowHeight / 2);
params.setMargins(0, 0, 0, 0);
youTubePlayerFragment.setLayoutParams(params);
fragmentTransaction.add(containerId, youTubePlayerFragment);
fragmentTransaction.commit();
youTubePlayerFragment.initialize(key, this);
}
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player,
boolean wasRestored) {
mYoutubePlayer = player;
mYoutubePlayer.setPlayerStateChangeListener(myPlayerStateChangeListener);
mYoutubePlayer.setPlaybackEventListener(myPlaybackEventListener);
if (!wasRestored) {
mYoutubePlayer.cueVideo("nCgQDjiotG0");
} else {
//TEST of video playback
mYoutubePlayer.cueVideo("nCgQDjiotG0");
play(null);
}
}
public void onInitializationFailure(YouTubePlayer.Provider provider,
YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
//errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show();
} else {
//String errorMessage = String.format(getString(R.string.error_player), errorReason.toString());
//Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
}
public void loadVideoWithId(String videoToLoad) {
videoId_local = videoToLoad;
mYoutubePlayer.cueVideo(videoId_local);
}
//Users
public String getLocalUserID() {
return videoId_local;
}
;
public void addUser(String userId) {
}
;
public void removeUser(String userId) {
}
public void removeAllUsers() {
}
//External Playback
public void play(String userId) {
mYoutubePlayer.play();
}
public void pause(String userId) {
mYoutubePlayer.pause();
}
public void stop(String userId) {
}
public void close(String userId) {
}
private final class MyPlayerStateChangeListener implements PlayerStateChangeListener {
#Override
public void onAdStarted() {
Log.INFO("YOUTUBE", "onAdStarted()");
}
#Override
public void onError(
com.google.android.youtube.player.YouTubePlayer.ErrorReason arg0) {
Log.INFO("YOUTUBE", "onError(): " + arg0.toString());
}
#Override
public void onLoaded(String arg0) {
Log.INFO("YOUTUBE", "onLoaded(): " + arg0);
}
#Override
public void onLoading() {
Log.INFO("YOUTUBE", "onLoading()");
}
#Override
public void onVideoEnded() {
Log.INFO("YOUTUBE", "onVideoEnded()");
}
#Override
public void onVideoStarted() {
Log.INFO("YOUTUBE", "onVideoStarted()");
}
}
private final class MyPlaybackEventListener implements PlaybackEventListener {
#Override
public void onBuffering(boolean arg0) {
Log.INFO("YOUTUBE", "onBuffering(): " + String.valueOf(arg0));
}
#Override
public void onPaused() {
}
#Override
public void onPlaying() {
}
#Override
public void onSeekTo(int arg0) {
}
#Override
public void onStopped() {
}
}
}
I am using youtube player api in my application,I have used the following code
xml:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rel1"
android:background="#edeae5">
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtubeplayerview"
android:layout_width="match_parent"
android:layout_height="200dp"/>
</RelativeLayout>
my Activity:
public class EditBloop extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_bloop);
youTubePlayerView = (YouTubePlayerView)findViewById(R.id.youtubeplayerview);
youTubePlayerView.initialize(API_KEY, this);
}
But here I am using YouTubeBaseActivity,but in my application I want youTubePlayer in a Fragment.
How can I achieve this? I have seen some of the links using YouTubePlayerSupportfragment but I didnt understand them.
Please suggest.
You can do as below
public class MainActivity extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener{
public static final String API_KEY = "key";
public static final String VIDEO_ID = "o7VVHhK9zf0";
private YouTubePlayer youTubePlayer;
private YouTubePlayerFragment youTubePlayerFragment;
private TextView textVideoLog;
private Button btnViewFullScreen;
private static final int RQS_ErrorDialog = 1;
private MyPlayerStateChangeListener myPlayerStateChangeListener;
private MyPlaybackEventListener myPlaybackEventListener;
String log = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
youTubePlayerFragment = (YouTubePlayerFragment)getFragmentManager()
.findFragmentById(R.id.youtubeplayerfragment);
youTubePlayerFragment.initialize(API_KEY, this);
}
#Override
public void onInitializationFailure(Provider provider,
YouTubeInitializationResult result) {
if (result.isUserRecoverableError()) {
result.getErrorDialog(this, RQS_ErrorDialog).show();
} else {
Toast.makeText(this,
"YouTubePlayer.onInitializationFailure(): " + result.toString(),
Toast.LENGTH_LONG).show();
}
}
#Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player,
boolean wasRestored) {
youTubePlayer = player;
Toast.makeText(getApplicationContext(),
"YouTubePlayer.onInitializationSuccess()",
Toast.LENGTH_LONG).show();
youTubePlayer.setPlayerStateChangeListener(myPlayerStateChangeListener);
youTubePlayer.setPlaybackEventListener(myPlaybackEventListener);
if (!wasRestored) {
player.cueVideo(VIDEO_ID);
}
}
private final class MyPlayerStateChangeListener implements PlayerStateChangeListener {
private void updateLog(String prompt){
log += "MyPlayerStateChangeListener" + "\n" +
prompt + "\n\n=====";
textVideoLog.setText(log);
};
#Override
public void onAdStarted() {
updateLog("onAdStarted()");
}
#Override
public void onError(
com.google.android.youtube.player.YouTubePlayer.ErrorReason arg0) {
updateLog("onError(): " + arg0.toString());
}
#Override
public void onLoaded(String arg0) {
updateLog("onLoaded(): " + arg0);
}
#Override
public void onLoading() {
updateLog("onLoading()");
}
#Override
public void onVideoEnded() {
updateLog("onVideoEnded()");
}
#Override
public void onVideoStarted() {
updateLog("onVideoStarted()");
}
}
private final class MyPlaybackEventListener implements PlaybackEventListener {
private void updateLog(String prompt){
log += "MyPlaybackEventListener" + "\n-" +
prompt + "\n\n=====";
textVideoLog.setText(log);
};
#Override
public void onBuffering(boolean arg0) {
updateLog("onBuffering(): " + String.valueOf(arg0));
}
#Override
public void onPaused() {
updateLog("onPaused()");
}
#Override
public void onPlaying() {
updateLog("onPlaying()");
}
#Override
public void onSeekTo(int arg0) {
updateLog("onSeekTo(): " + String.valueOf(arg0));
}
#Override
public void onStopped() {
updateLog("onStopped()");
}
}
}
The xml
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
android:name="com.google.android.youtube.player.YouTubePlayerFragment"
android:id="#+id/youtubeplayerfragment"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"/>