Youtube API loads video but doesn't play - android-youtube-api

I have integrated my Youtube API into my app, and have created two youTubePlayerView instances. The first loads fine and allows to be selected, the second is inside of a firebase statement and won't allow me to select it. However the video loads fine into the youtube api for the second video. But it just won't play the video when selected.
code for the first video:
youTubePlayerView.initialize(Constants.youTubeKey,
new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider,
YouTubePlayer youTubePlayer, boolean b) {
// do any work here to cue video, play video, etc.
youTubePlayer.cueVideo("YbjRc2dflZU");
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider,
YouTubeInitializationResult youTubeInitializationResult) {
}
});
code for the second video:
final DatabaseReference artistsFound = Constants.artistRef
.child(userSelectedStage)
.child(userSelectedDate)
.child(userSelectedArtist);
artistsFound.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String valueFound = snapshot.getKey().toString();
if(valueFound.equals("Set Time")){
String artistSetTime = snapshot.getValue().toString();
txtVwDetArtistSetTime.setText(artistSetTime);
}else if(valueFound.equals("Featured Video")){
final String artistFeaturedVideoURL = snapshot.getValue().toString();
youTubePlayerViewFeature.initialize(Constants.youTubeKey,
new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider,
YouTubePlayer youTubePlayer, boolean b) {
// do any work here to cue video, play video, etc.
youTubePlayer.cueVideo(artistFeaturedVideoURL);
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider,
YouTubeInitializationResult youTubeInitializationResult) {
}
});
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});

Related

How can I set interstitial ads on URL clicks in WebView App?

I have implemented following code for interstitial ads .Problem I am facing is that interstitial ad is shown only on first URL click. I want to adjust ads on every URL click or every 5th URL click in WebView app .Help in this regard will highly be appreciated. Following is the code i want to be modified .
private WebView webview;
private AdView mAdView;
private InterstitialAd mInterstitialAd;
SwipeRefreshLayout mySwipeRefreshLayout;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {}
});
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(this,"ca-app-pub-3940256099942544/1033173712", adRequest,
new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
mInterstitialAd = interstitialAd;
Log.i("TAG", "onAdLoaded");
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
// Handle the error
Log.i("TAG", loadAdError.getMessage());
mInterstitialAd = null;
}
});
private class WebViewClientDemo extends WebViewClient {
#Override
//Keep webview in app when clicking links
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (mInterstitialAd != null) {
mInterstitialAd.show(MainActivity.this);
} else {
Log.d("TAG", "The interstitial ad wasn't ready yet.");
}
return super.shouldOverrideUrlLoading(view, url);
}
You need to load Ad after each show. Create a static counter variable to load it on everyth nth click.
static int instanceCounter = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LoadInterstitial();
}
private void LoadInterstitial(){
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(this,"ca-app-pub-3940256099942544/1033173712", adRequest,
new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
mInterstitialAd = interstitialAd;
Log.i("TAG", "onAdLoaded");
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
// Handle the error
Log.i("TAG", loadAdError.getMessage());
mInterstitialAd = null;
}
});
}
private class WebViewClientDemo extends WebViewClient {
#Override
//Keep webview in app when clicking links
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (mInterstitialAd != null && isDisplayAdvert()) {
mInterstitialAd.show(MainActivity.this);
LoadInterstitial();
} else {
Log.d("TAG", "The interstitial ad wasn't ready yet.");
}
return super.shouldOverrideUrlLoading(view, url);
}
private bool isDisplayAdvert(){
instanceCounter++;
if(instanceCounter==5){
instanceCounter = 0;
return true;
}
return false;
}
Thanks sir Amod Gokhale . I tried the following code and it is working too .
Would you recommend me about the better one between both codes .
private class WebViewClientDemo extends WebViewClient {
int n = 1;
#Override
//Keep webview in app when clicking links
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (mInterstitialAd != null) {
if( n%6 == 0 )
{
mInterstitialAd.show(MainActivity.this);
} n++;
}
LoadInterstitial();
return super.shouldOverrideUrlLoading(view, url);
}

Can queryEqual() be used to compare with an Array? [duplicate]

How do I query SQL IN clause in Firebase Android? I want to use it in a Firebase Recycler adapter to retrieve only some children based on some condition. Something like the following statement:
SQL----> select * from posts where city in(10 cities comes here)
I need a Firebase query to use that in the Firebase Recycler adapter.
The Firebase database does not have the equivalent of SQL's WHERE id IN (1,2,3). In the case of selecting by ID, Firebase's way of retrieving items is equally fast because Firebase pipelines the requests.
Your case is different though, since you're not selecting by ID. Unfortunately there is no way to directly map your query to a equivalent on the Firebase Database.
Instead of trying to make Firebase's NoSQL database do SQL tricks, I highly recommend that you start mapping your data model to something that fits better with a NoSQL database. Some great resources to kick start this process are this article on NoSQL data modeling and our new video series on Firebase for SQL developers.
Also see Firebase complex "contain" queries
I found the solution: we cannot use FirebaseRecyclerAdapter. Instead we have to create custom adapter that extends RecyclerView.ViewHolder.
For passing values to this adapter, first we have to retrieve data using addValueEventListener and then we have to pass values to our adapter.
This is my code...
final ArrayList<Timeline> timelines = new ArrayList<>();
mDatabaseTimeline.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
final Timeline timeline = dataSnapshot.getValue(Timeline.class);
if(timeline != null){
mDatabaseFriends.child(mAuth.getCurrentUser().getUid()).child("active").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (mAuth.getCurrentUser().getUid().equals(timeline.getUid()) || dataSnapshot.hasChild(timeline.getUid())) {
timelines.add(timeline);
mTimelineRecycler.setAdapter(new RecyclerAdapter(TimelineFragment.this.getContext(), timelines));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
adapter----->
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
Context context;
ArrayList<Timeline> timeline;
public RecyclerAdapter(Context context, ArrayList<Timeline> timeline) {
this.context = context;
this.timeline = timeline;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View row = inflater.inflate(R.layout.timeline_row, parent, false);
TimelineViewHolder holder = new TimelineViewHolder(row);
return holder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final String post_key = timeline.get(position).getPostkey();
((TimelineViewHolder) holder).setUsername(timeline.get(position).getUsername());
}
#Override
public int getItemCount() {
return timeline.size();
}
public class TimelineViewHolder extends RecyclerView.ViewHolder {
public TimelineViewHolder(View itemView) {
super(itemView);
view = itemView;
}
public View getView() {
return view;
}
public void setUsername(String username) {
TextView usernameTxtView = (TextView) view.findViewById(R.id.timeline_username);
usernameTxtView.setText(username);
}
}
}

What happens if user clicks on deep link in the app itself

If I have created a deep link using the branch.io that opens a specific screen in my app. If this link is also available in my app and a user clicks on it, will it open my screen? or it will do nothing as the link I am trying to open from the app is pointing to the same app?
When you click on a Branch link within a webView in your App, you will have to handle the routing to the specific Activity, after reading the Branch link parameters.
Here is a sample Activity which contains a webView and and shows a couple of Branch links. When you click on a link in the webView it reopens the webview and displays the link parameters in a Toast message if a Branch link is clicked
public class MainActivity extends AppCompatActivity {
private WebView webView_;
private Button button_;
private String TAG = "WebViewController";
private Context context_;
private static final String URL_TO_LOAD = "https://evangelosg.github.io/index.html";
private static final String BRANCH_LINK_TO_LOAD = "https://ere6.app.link/b6sS0gsCfG";
#Override
protected void onNewIntent(Intent intent) {
Log.d("WebView", "onNewIntent");
setIntent(intent);
}
#Override
protected void onResume() {
super.onResume();
Branch branch = Branch.getInstance();
branch.initSession(new Branch.BranchReferralInitListener() {
#Override
public void onInitFinished(JSONObject referringParams, BranchError error) {
if (error == null) {
Log.d(TAG, referringParams.toString());
Toast.makeText(context_, referringParams.toString(), Toast.LENGTH_LONG).show();
if (referringParams.has(BundleExtraKeys.CLICKED_BRANCH_LINK)) {
try {
boolean clickedBranchLink = referringParams.getBoolean(BundleExtraKeys.CLICKED_BRANCH_LINK);
if (clickedBranchLink) {
//do stuff!
}
} catch (JSONException e) {
Log.d("BranchTrends", e.getMessage());
}
}
} else {
Log.i("MyApp", error.getMessage());
}
}
}, this.getIntent().getData(), this);
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context_ = this;
setContentView(R.layout.activity_main);
webView_ = (WebView) findViewById(R.id.webView);
webView_.setWebViewClient(new BranchWebViewController("app.link", MainActivity.class));
webView_.loadUrl(URL_TO_LOAD);
button_ = (Button) findViewById(R.id.button);
button_.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.intent.putExtra("branch", BRANCH_LINK_TO_LOAD);
customTabsIntent.intent.putExtra("branch_force_new_session", true);
finish();
customTabsIntent.launchUrl(MainActivity.this, Uri.parse(BRANCH_LINK_TO_LOAD));
}
});
}
public class BranchWebViewController extends WebViewClient {
private String myDomain_;
private Class activityToLaunch_;
BranchWebViewController(#NonNull String myDomain, Class activityToLaunch) {
myDomain_ = myDomain;
activityToLaunch_ = activityToLaunch;
}
#Override
public void onLoadResource(WebView view, String url) {
super.onLoadResource(view, url);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
String url = request.getUrl().toString();
if (url.contains(myDomain_)) {
Intent i = new Intent(view.getContext(), activityToLaunch_);
i.putExtra("branch", url);
i.putExtra("branch_force_new_session", true);
finish();
startActivity(i);
} else {
view.loadUrl(url);
}
return true;
}
}
}
Once you read the link parameters you can route to the appropriate Activity based on the link parameters.

Managing and loading assets via AssetManager (Libgdx)

Im having some issues with the AssetManager provided by Libgdx.
I get a nullpointer:
Java.lang.IllegalArgumentException: texture cannot be null.
at com.badlogic.gdx.graphics.g2d.TextureRegion.<init>(TextureRegion.java)
at com.test.test.screens.screens.MainScreen.show(MainScreen.java)
at com.badlogic.gdx.Game.setScreen(Game.java)
at com.test.test.screens.screens.SplashScreen.render(SplashScreen.java)
I´ve checked and the file it´s loading is present and correct, so it´s something in my code. And I literally have no idea what to do about it.. I was told to make sure I create not a new instance of Assets but creating an existing instance of it. Not sure if I´ve done it correctly though..
This is the class it self:
public class Assets {
public final AssetManager manager = new AssetManager();
private ObjectMap<String, Texture> textures;
private ObjectMap<String, Sound> sounds;
public final String background = "test.jpg";
public Assets() {
textures = new ObjectMap<String, Texture>();
sounds = new ObjectMap<String, Sound>();
manager.load(background, Texture.class);
}
public boolean update() {
boolean done = manager.update();
if (done) {
finishLoading();
}
return done;
}
private void finishLoading() {
textures.put(background, manager.get(background, Texture.class));
}
public Texture getTexture(String name) {
return textures.get(name);
}
public void dispose() {
manager.clear();
}
}
And at the moment I declare it like this in my MainClass:
public class MainClass extends Game {
public SpriteBatch batch;
public purchaseInterface pi;
//Calls the Assets to be implemented in other classes
public Assets assets;
public MainClass(purchaseInterface purchase, GalleryOpener opener){
this.gallery= opener;
this.pi = purchase;
}
#Override
public void create () {
batch = new SpriteBatch();
assets = new Assets();
setScreen(new SplashScreen(this));
}
#Override
public void resize(int width, int height) {
super.resize(width, height);
}
#Override
public void render () {
super.render();
}
#Override
public void dispose() {
super.dispose();
batch.dispose();
assets.dispose();
}
public Assets getAssets() {
return assets;
}
#Override
public void pause() {
super.pause();
}
#Override
public void resume() {
// TODO Auto-generated method stub
super.resume();
}
}
And for the example of loading assets to a Screen class:
public Assets assets;
public MainScreen(MainClass gam) {
game = gam;
assets = game.getAssets();
loadStore();
camera = new OrthographicCamera(screenWidth,screenHeight);
view = new StretchViewport(screenWidth, screenHeight, camera);
view.apply();
camera.translate(camera.viewportWidth / 2, camera.viewportHeight / 2);
}
public void loadStore() {
background = assets.getTexture(assets.background);
}
#Override
public void render(float delta) {
camera.update();
game.batch.setProjectionMatrix(camera.combined);
game.batch.begin();
game.batch.draw(background, 0, 0, 1000, 2000);
game.batch.end();
}
#Override
public void resize(int width, int height) {
view.update(width, height, true);
}
#Override
public void show() {
}
#Override
public void hide() {
// TODO Auto-generated method stub
}
#Override
public void pause() {
// TODO Auto-generated method stub
}
#Override
public void resume() {
}
#Override
public void dispose() {
background.dispose();
}
}
This will NOT load the background texture:
manager.load(background, Texture.class);
You need call the
manager.finishLoading();
right after the load() for that. AssetManager.load() is just store the path of an asset. AssetManager.update() loads the next item from the stored paths in an other thread, AssetManager.finishLoading() loads ALL of the items and waits for the loading thread to finish. When you would like to draw an image while you loading the other assets, you need to load first that image (in this case the "background").
The other thing, I think you store things twice for nothing (textures, sounds objectmaps). The best practice is use the asset manager to get the textures or any assets with the "get" function.
I did this:
public class LoadingScreen extends Screen {
...
#Override
public void show() {
app.assets.load("data/textures/loading.pack", TextureAtlas.class);
app.assets.finishLoading(); // this is waits for the loading finish
app.assets.load("data/textures/menu.pack", TextureAtlas.class);
app.assets.load("data/textures/sprites.pack", TextureAtlas.class);
...
}
#Override
public void render(float delta) {
if (app.assets.update()) { // this is loads the next item in an other thread
app.loadingFinished(); // this is where you will create the other screens
}
...
}
...
"app" is a Game instance, "app.assets" is an AssetManager instance. When I want to have an asset I do this (but this only can run after loading is finished!):
TextureAtlas atlas = app.assets.get("data/textures/sprites.pack", TextureAtlas.class);

how to get webview content android after loadurl

Here is My Code.
I just want to get the page content from the Webview after load the URL .
On Android, I have a WebView that is displaying a page.
How do I get the page source without requesting the page again?
It seems WebView should have some kind of WebResourceResponse () method in Android 3.0 but don't know how to use it.
public class WebActivity extends Activity {
WebView mWebView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mWebView = (WebView) findViewById(R.id.webView);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl("https://xyz.com");
mWebView.setWebViewClient(new HelloWebViewClient());
}
private class HelloWebViewClient extends WebViewClient {
public WebResourceResponse shouldInterceptRequest (WebView view, String url)
{
return null;
}
#Override
public void onPageFinished(WebView view, String url)
{
/* This call inject JavaScript into the page which just finished loading. */
mWebView.loadUrl("javascript:window.HTMLOUT.processHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}}
I know this is old, but for future visitors, the following should work.
First, you need to define an interface such as:
final class LoadingInterface {
#JavascriptInterface
public void outputHTML(final String html){
//do what ever you want with html
}
}
Then on your WebView call
webView.addJavascriptInterface(new LoadingInterface(), "INTERFACE");
In onPageFinished put:
String js = "javascript:"
+"var html = document.getElementsByTagName('html')[0].innerHTML;"
+"window.INTERFACE.outputSchedule(html);";
webView.loadUrl(js);
If you only need part of a page, you can replace getElementsByTagName('html')[0] with something like getElementById('partOfPage')

Resources