How to show the interstitial ads on second click? - android

Anybody know how to show the interstitial ads when the user click the button second time.I mean when the user click the button once then the ad should not appear but whenever the user click the same button second time then the ad must show..
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
ShowInterstitial showInterstitial;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showInterstitial = new ShowInterstitial(this);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.app_bar);
/*toolbar = findViewById(R.id.app_bar);
toolbar.setTitle("hell");
toolbar.*/
}
int counter = 0;
public void onClick(View view) {
if(view.getId() == R.id.ll1 ) {
counter++;
if (counter == 2) {
counter = 0;
Intent intent = new Intent(this, AggregatesActivity.class);
startActivity(intent);
if (showInterstitial != null && ShowInterstitial.isLoaded())
showInterstitial.showInterstitial();
}
}
and ShowInterstitial code is here which i calling in different activities.
public class ShowInterstitial {
private InterstitialAd mInterstitialAd;
private Context context;
private boolean isAddReplace = false;
public ShowInterstitial(Context context) {
this.context = context;
mInterstitialAd = newInterstitialAd(context);
loadInterstitial();
}
private InterstitialAd newInterstitialAd(final Context context) {
InterstitialAd interstitialAd = new InterstitialAd(context);
/*if (!isAddReplace)
interstitialAd.setAdUnitId(context.getString(R.string.interstitial_one));*/
interstitialAd.setAdUnitId(context.getString(R.string.interstitial_one));
interstitialAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
isAddReplace = !isAddReplace;
}
#Override
public void onAdFailedToLoad(int errorCode) {
}
#Override
public void onAdClosed() {
goToNextLevel();
}
});
return interstitialAd;
}
public boolean showInterstitial() {
if (mInterstitialAd != null && mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
goToNextLevel();
}
return false;
}
public void loadInterstitial() {
// Disable the next level button and load the ad.
AdRequest adRequest = new AdRequest.Builder()
.setRequestAgent("android_studio:ad_template").build();
mInterstitialAd.loadAd(adRequest);
}
private void goToNextLevel() {
// Show the next level and reload the ad to prepare for the level after.
mInterstitialAd = newInterstitialAd(context);
loadInterstitial();
}
}

#Sufyan Hashmi you need a int variable whose value will increase on every click whenever the value is 2 you should call load inerestitial ad and assign the variable's value zero.
int counter = 0;
if(view.getId()==R.id.ll1)
{
counter++;
if (counter == 2) {
counter = 0;
Intent intent = new Intent(this, AggregatesActivity.class);
startActivity(intent);
if (showInterstitial != null && showInterstitial.isLoaded())
showInterstitial.showInterstitial();
}
}

How to show the interstitial ads on second click in android?
You can take boolean variable and manage click event based on that boolean variable
Example : take a boolean variable with true value
Than inside ClickListener when user clicks the button check that boolean variable is true means use clicked first time the button
and change the value of boolean variable to false
SAMPLE CODE
take one boolean variable
boolean isFirstTimeClick=true;
Now make your ClickListener like this
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(isFirstTimeClick){
isFirstTimeClick=false;
Toast.makeText(PicturePreviewActivity.this, "First Time Click", Toast.LENGTH_SHORT).show();
}else {
isFirstTimeClick=true;
Toast.makeText(PicturePreviewActivity.this, "Second Time Click", Toast.LENGTH_SHORT).show();
}
}
});

Related

Admob interstitial ad latency issues when loading ad

I am trying to implement interstitial ad in a fragment, when button is clicked the fragment doesn't open other activity , but loads data in same fragment so i can't use the they way people say interstisial ad should be used when navigating between activities. instead i am using the ad for only once when button is clicked .it works but takes sometime .how to deal with it?
it only works if user pressed the button after few seconds of launching the app.
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
root = inflater.inflate(R.layout.fragment_home, container, false);
Button btn=root.findViewById(R.id.btn);
initAds();
btn.setOnClickListener(this);
return root;
}
#Override
public void onClick(View view){
initAdsCallBack();
}
private void initAds(){
MobileAds.initialize(requireActivity(), new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(#NonNull InitializationStatus initializationStatus) {
createNonPersonalisedAd();
}
});
}
}
private void createNonPersonalisedAd() {
Bundle networkExtrasBundle = new Bundle();
networkExtrasBundle.putInt("rdp", 1);
AdManagerAdRequest adRequest = (AdManagerAdRequest) new AdManagerAdRequest.Builder()
.addNetworkExtrasBundle(AdMobAdapter.class, networkExtrasBundle)
.build();
createInterstitialAd(adRequest);
}
private void createInterstitialAd(AdRequest adRequest){
AdManagerInterstitialAd.load(requireActivity(),getResources().getString(R.string.str_iterstitial), (AdManagerAdRequest) adRequest,
new AdManagerInterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull AdManagerInterstitialAd interstitialAd) {
// The mAdManagerInterstitialAd reference will be null until
// an ad is loaded.
mAdManagerInterstitialAd = interstitialAd;
Log.i(TAG, "onAdLoaded");
///// best place to callback is here coz its successfully loaded here
mAdManagerInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback(){
#Override
public void onAdDismissedFullScreenContent() {
// Called when fullscreen content is dismissed.
Log.d("TAG", "The ad was dismissed.");
createInterstitialAd(adRequest);
}
#Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
// Called when fullscreen content failed to show.
Log.d("TAG", "The ad failed to show.");
}
#Override
public void onAdShowedFullScreenContent() {
// Called when fullscreen content is shown.
// Make sure to set your reference to null so you don't
// show it a second time.
mAdManagerInterstitialAd = null;
Log.d("TAG", "The ad was shown.");
}
});
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
// Handle the error
Log.i(TAG, loadAdError.getMessage());
mAdManagerInterstitialAd = null;
}
});
}
private void initAdsCallBack(){
if (mAdManagerInterstitialAd != null) {
mAdManagerInterstitialAd.show(requireActivity());
debugToast("ad shown");
} else {
Log.e("Tad didn't show");
}
}
Consider pre-loading your interstitial ads to reduce latency when displaying them to your users. For more information about pre-loading your interstitial ads refer to the AdMob Interstitial Ad developer guidelines for apps developed for Android

How to use backbutton to unselect all item in gridview?

i'm using backbutton as interface from activity but it's not working properly for me because on backpress showing 0 size of arraylist
// here is the activity class from where i'm getting backbutton interface..
public class Multiple_Images extends AppCompatActivity {
#Override
public void onBackPressed() {
if(twice ==true){
Intent intent =new Intent(this,MainActivity.class);
startActivity(intent);
}ImageAdapter imageAdapter =new ImageAdapter(this);
imageAdapter.onBackPress();
Toast.makeText(this, "Press twice", Toast.LENGTH_SHORT).show();
twice =true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
twice =false; } }, 2000); }}
//here is the adapter class here i'm using backbutton
public class ImageAdapter extends BaseAdapter implements onBackPressListener {
ArrayList<String> selectedArraylist ;
#Override
public boolean onBackPress() {
selectedArraylist.clear();
Toast.makeText(context, "All values unselected", Toast.LENGTH_SHORT).show();
return true;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
urimodel=new ArrayList<>();
final ImageView imageGrid ;
Activity activity = (Activity) context;
actionMode = activity.startActionMode(new Actionmode());
final GridModel gridModel=(GridModel) this.getItem(i);
if(view==null) {
view = LayoutInflater.from(context).inflate(R.layout.model, null);
selectedArraylist =new ArrayList<>();
}
final CardView cardView= (CardView)view.findViewById(R.id.cardview_image);
imageGrid = (ImageView) view.findViewById(R.id.grid_image);
// gridText = (TextView) view.findViewById(R.id.grid_text);
imageGrid.setScaleType(ImageView.ScaleType.CENTER_CROP);
// imageGrid.setScaleType(ImageView.ScaleType.CENTER_CROP);
Picasso.get().load(gridModel.getImage()).resize(200,200).into(imageGrid);
if (selectedArraylist.contains(gridModel.getImage_text())) {
cardView.setCardBackgroundColor(CARD_SELECTED_COLOR);
}else {
cardView.setCardBackgroundColor(Color.WHITE);
}
return view;
}
}
Simply you can do this inside onBackPressed
#Override
public void onBackPressed() {
if (twice == true) {
super.onBackPressed(); //this backs to the previous activity, if you want to stay with Intent, add finish() after startActivity()
return;
} else {
for (int i = 0; i < list.size(); i++) {
if (gridView.isItemChecked(i)) {
gridView.setItemChecked(i, false);
}
}
//selectedArraylist.clear(); this is clearing your array of selected items
}
twice = true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
twice = false;
}
}, 2000);
}
I don't know, why did you put selectedArraylist =new ArrayList<>(); in adapter getView() method. getView() is fired every time, when a new list item is inflated, that mean every time, when you are changing adapters source, scrolling list this method is called, and every time you are initialize you array, and all data inside lost. You should treat an adapter class just like a tool for displaying items, and all actions like above make outside adapter.
pretty much easy,
I give you my own project code, hope it help you.
StudentFragment.java:
private void MultiSelected_Student(int position) {
Student data = adapter_class.getItem(position);
if (data != null) {
if (selectedIds.contains(data)) selectedIds.remove(data);
else selectedIds.add(data);
}
}
private void Remove_MultiSelected() {
try {
selectedIds.clear();
} catch (Exception e) {
e.printStackTrace();
}
}
public void Group_UnSelect() {
Remove_MultiSelected();
MultiSelected = false;
fab.setVisibility(View.GONE);
homeeActivity.studentsMultiSelect = false;
notifyy();
}
private void notifyy() {
adapter_class.notifyDataSetChanged();
}
HomeActivity.java:
public boolean studentsMultiSelect = false;
#Override
public void onBackPressed() {
if (studentsMultiSelect) {
studentFragment.Group_UnSelect();
} else {
super.onBackPressed();
}
}

Revmob in Libgdx

Hello I am trying to integrated Banner Ad using RevMob in Libgdx. But it is not displaying for some reason.
I am using the following code.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_game_new);
AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration();
// cfg.useGL20 = false;
final RelativeLayout gameLayout = new RelativeLayout(this);
RevMobIntegration revmob = new RevMobIntegration(this);
RelativeLayout bannerLayout = new RelativeLayout(this);
RelativeLayout.LayoutParams adParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
adParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
adParams.addRule(RelativeLayout.CENTER_VERTICAL);
bannerLayout.setLayoutParams(adParams);
game = new MyGdxGame(GameActivity.this, revmob);
game.setRedirectionListener(this);
View gameView = initializeForView(game, cfg);
requestWindowFeature(android.view.Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
// Add the libgdx view
gameLayout.addView(gameView);
// gameLayout.addView(bannerLayout);
Log.d("RevMob", "Checking BannerAd");
if (revmob.getBannerAd() != null) {
Log.d("RevMob", "Displaying Called");
gameLayout.addView(revmob.getBannerAd());
}
// Hook it all up
setContentView(gameLayout);
this.onPause();
this.onResume();
gameLayout.refreshDrawableState();
initChartboost();
// startRevMobSession();
}
Here is the RevMobIntegration class :
public class RevMobIntegration implements RevmobAdInterface {
private static final String APPLICATION_ID = "YourAdmobAppIDHere";
// Set this to false when creating the version for the store.
private static final boolean DEBUG = true;
private RevMobAdsListener listener;
private RevMobFullscreen fullscreenAd;
private RevMobBanner bannerAd;
private Activity application;
private RevMob revmob;
public RevMobIntegration(Activity _application) {
this.application = _application;
startRevMobSession();
}
public void startRevMobSession() {
//RevMob's Start Session method:
revmob = RevMob.startWithListener(application, new RevMobAdsListener() {
#Override
public void onRevMobSessionStarted() {
loadBanner(); // Cache the banner once the session is started
Log.i("RevMob", "Session Started");
}
#Override
public void onRevMobSessionNotStarted(String message) {
//If the session Fails to start, no ads can be displayed.
Log.i("RevMob", "Session Failed to Start");
}
}, application.getString(R.string.rev_mob_app_id));
}
//RevMob
public void loadBanner() {
bannerAd = revmob.preLoadBanner(application, new RevMobAdsListener() {
#Override
public void onRevMobAdReceived() {
showBannerAd(true);
Log.i("RevMob", "Banner Ready to be Displayed"); //At this point,
the banner is ready to be displayed.
}
#Override
public void onRevMobAdNotReceived(String message) {
Log.i("RevMob", "Banner Not Failed to Load");
}
#Override
public void onRevMobAdDisplayed() {
Log.i("RevMob", "Banner Displayed");
}
});
}
#Override
public void showBannerAd(boolean show) {
if(show) {
Log.i("RevMob", "Showing");
if(bannerAd == null) {
startRevMobSession();
} else {
Log.i("RevMob", "Banner Displayed");
bannerAd.show();
}
} else {
bannerAd.hide();
}
}
public RevMobBanner getBannerAd() { return bannerAd; }
}
I have integrated the RevMob in my Activities and it is working fine. But for the Game Screen the ad is initializing but not displaying.
Any suggestions?
It seems revmob.getBannerAd() return null because bannerAd object created when loadBanner(); called. RevMob take some time to start it's session.
if (revmob.getBannerAd() != null) {
Log.d("RevMob", "Displaying Called");
gameLayout.addView(revmob.getBannerAd());
}
You can check this repo for clarification also you can take a look of this class.

Toggle play pause ImageView inside listview

I have a list view of songs with play and pause button in every row.
Obviously, I can't have two pause Icon(two playing song)at the same time in my list view So I need to first reset all of them to play Icon then set the selected view to pause Icon.
How can I achieve this?
This is what I have done so far:
In the model class ( Product ):
public boolean paused = true;
private int PlayPauseId;
public int getPlayPauseId(){
return PlayPauseId;
}
public void setPlayPauseId(int playPauseId) {
PlayPauseId = playPauseId;
}
in Adapter:
public interface PlayPauseClick {
void playPauseOnClick(int position);
}
private PlayPauseClick callback;
public void setPlayPauseClickListener(PlayPauseClick listener) {
this.callback = listener;
}
.
.
.
holder.playPauseHive.setImageResource(product.getPlayPauseId());
holder.playPauseHive.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (callback != null) {
callback.playPauseOnClick(position);
}
}
});
my Callback inside my Activity:
#Override
public void playPauseOnClick(int position) {
final Product product = movieList.get(position);
if (product.paused) {
product.setPlayPauseId(R.drawable.ic_pause);
product.paused=false;
}else {
product.setPlayPauseId(R.drawable.ic_play);
product.paused = true;
}
this.adapter.notifyDataSetChanged();
}
You have to check condition in your getView() method of adapter like this:
if (product.paused) {
holder.playPauseHive.setImageResource(R.drawable.ic_play);
}else {
holder.playPauseHive.setImageResource(R.drawable.ic_pause);
}

Updating Views through AsyncTasks

Below is working sample code of an Android Activity that has 2 buttons, of which only 1 is ever visible: a refresh button and a stop button.
This code does the following:
Refresh is clicked: start some AsyncTasks. The preExecute of the tasks will hide the refresh button and show the stop button. The postExecute of the task will check if there are no more running tasks and if so, show the refresh button and hide the stop button.
Stop is clicked: all tasks are cancelled, the refresh button is shown and the stop button is hidden.
This code works fine, but for one exception: when I recreate the activity while a task is running by changing the screen orientation. The buttons will now return to the state as defined in the xml (refresh=visibile, stop=gone).
Using a static variable to keep track of the current state of the visibility only makes it worse, because the running Task that has to toggle it back, can only modify views in the calling activity, which has been stopped or destroyed at that point!
public class MainActivity extends Activity
{
private static List<MyAsyncTask> activeTasks = new LinkedList<MyAsyncTask>();
private View refresh;
private View stop;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_main);
this.refresh = findViewById(R.id.refresh);
this.refresh.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{ // Start a couple tasks
new MyAsyncTask(MainActivity.this).execute();
new MyAsyncTask(MainActivity.this).execute();
}
});
this.stop = findViewById(R.id.stop);
this.stop.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{ // Cancel all tasks and toggle refresh button
cancelAll();
MainActivity.this.enableRefresh(true);
}
});
}
public void enableRefresh(boolean enable)
{
if (this.refresh != null && this.stop != null)
{
this.refresh.setVisibility(enable ? View.VISIBLE : View.GONE);
this.stop.setVisibility(!enable ? View.VISIBLE : View.GONE);
}
}
public static void cancelAll()
{
for (MyAsyncTask task : MainActivity.activeTasks)
task.cancel(true);
MainActivity.activeTasks = new LinkedList<MyAsyncTask>();
}
private class MyAsyncTask extends AsyncTask<Void,Void,Void>
{
private MainActivity activity;
public MyAsyncTask(MainActivity activity)
{
this.activity = activity;
}
#Override
protected void onPreExecute()
{
MainActivity.activeTasks.add(this);
this.activity.enableRefresh(false);
}
#Override
protected Void doInBackground(Void... v)
{
try
{ // Simulate a task
Thread.sleep(3000);
}
catch (InterruptedException e)
{
}
return null;
}
#Override
protected void onPostExecute(Void v)
{
MainActivity.activeTasks.remove(this);
if (MainActivity.activeTasks.size() == 0)
this.activity.enableRefresh(true);
}
}
}
http://www.androiddesignpatterns.com/2013/04/retaining-objects-across-config-changes.html
See this it will help you ... on handling the states in orientation change
to handle AsyncTasks on screen orientation follow this example
MyAsyncTask myasynce;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_main);
this.refresh = findViewById(R.id.refresh);
this.refresh.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
//Register new Task
myasynce = ( MyAsyncTask ) new MyAsyncTask(MainActivity.this).execute();
}
});
this.stop = findViewById(R.id.stop);
this.stop.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{ // Cancel all tasks and toggle refresh button
cancelAll();
MainActivity.this.enableRefresh(true);
}
});
}
now onSaveInstanceState add
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//put myasynce status true if still runing false if finished
outState.putBoolean("myasynce", ( myasynce != null && query.getStatus() != AsyncTask.Status.FINISHED ) ? true : false );
if ( myasynce != null )
{
myasynce.cancel(true);
}
}
on savedInstanceState
add
if ( savedInstanceState.getBoolean("myasynce") == true )
{
//if task was running before screen orientation run it again
myasynce = ( MyAsyncTask ) new MyAsyncTask(MainActivity.this).execute();
}
hope this help
I think this link http://www.androiddesignpatterns.com/2013/04/retaining-objects-across-config-changes.html by Tony Stark is probably the best solution, because that potentially solves even more problems.
However, I think I came up with an simpler solution for the problem at hand:
Add static vars to MainActivity:
private static MainActivity current;
private static boolean enableRefresh = true;
Save input value of enableRefresh():
public static void enableRefresh(boolean enableRefresh)
{
MainActivity.enableRefresh = enableRefresh;
(...) // Same as before
}
Add to MainActivity onCreate():
MainActivity.current = this;
enableRefresh(enableRefresh);
In the AsyncTask, use
MainActivity.current as the activity to update, instead of the activity provided in the constructor.

Categories

Resources