My application crash after using Volley lib to retrieve ads Id - android

I modified my project code to retrieve admob id from a server to show admob banner/interstitial using particular value of id by volley lib. Consequently, my application crashes each time the interstitial starts
The logcat points that "The ad unit ID must be set on InterstitialAd before loadAd is called."
This warning is caused by
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
if (!isRedirected || INCREMENT_WITH_REDIRECTS) {
super.onPageStarted(view, url, favicon);
webViewCount = webViewCount + 1;
if (webViewCount >= ServerClass.SHOW_AD_AFTER_X) {
if (ServerClass.SHOW_FULL_SCREEN_AD && !HIDE_ADS_FOR_PURCHASE) {
if (ServerClass.USE_FACEBOOK_ADS) {
if (facebookInterstitialAd != null) {
facebookInterstitialAd.loadAd();
}
} else {
if (mInterstitialAd != null) {
final AdRequest fullscAdRequest = new AdRequest.Builder().build();
mInterstitialAd.loadAd(fullscAdRequest);
}
}
}
}
}
}
So when I change it to
if (mInterstitialAd != null) {
final AdRequest fullscreenAdRequest = new AdRequest.Builder().build();
mInterstitialAd.setAdUnitId(ServerClass.interstitial_full);
mInterstitialAd.loadAd(fullscreenAdRequest);
}
I got another warning "The ad unit ID can only be set once on InterstitialAd."
since setAdUnitId is already used in an if statement in onCreate method:
if (!HIDE_PURCHASE) {
if (ServerClass.FACEBOOK_ADS) {
//CODE
} else {
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId(ServerClass.interstitial_full);
mInterstitialAd.setAdListener(new AdListener() {
public void onAdLoaded() {
showInterstitial();
}
});
}
How could I prevent my app from crashing, and why is retrieving data from server would cause that though the data is already present based on Log msg

Related

Unity, Facebook SDK, in Android build the app crashes

I am integrating Unity Facebook SDK to a project, right now I am making a log-in system. I have written a script, attached it to an object on a scene, created a button, added the FbLogin method as a listener of OnClick UnityEvent of my button and built an app for Android. Also I have pasted all the needed keys and tokens.
using System.Collections.Generic;
using UnityEngine;
using Facebook.Unity;
class FacebookLoginSystem
{
private void Awake()
{
FB.Init(SetInit, OnHideUnity);
}
void SetInit()
{
if (FB.IsLoggedIn)
{
Debug.Log("Logged in Successfuly!");
}
else
{
Debug.Log("FB is not loggid in");
}
}
void OnHideUnity(bool isGameShown)
{
if (isGameShown)
{
Time.timeScale = 1;
}
else
{
Time.timeScale = 0;
}
}
public void FbLogin()
{
List<string> permessions = new List<string>();
permessions.Add("public_profile");
FB.LogInWithReadPermissions(permessions, AuthCallResult);
}
private void AuthCallResult(ILoginResult result)
{
if (result.Error != null)
{
Debug.Log(result.Error);
}
else
{
if (FB.IsLoggedIn)
{
Debug.Log("FB logged in");
Debug.Log(result.RawResult);
FB.API("/me?fields=first_name", HttpMethod.GET, callbackData);
}
else
{
Debug.Log("Login Failed!");
}
}
}
}
But when I press the button in my build, I get this. ("Something went wrong, we are working on it...")
Tell me, please, why does it happen?
This happens when I press the button
UPD:
I have replaced the methods FbLogin and AuthCallback with these versions. Also I added a serialized field TextForLogging to see my logs in Build, and it tells me that "User cancelled login".
public void FbLogin()
{
var perms = new List<string>() { "public_profile", "email" };
FB.LogInWithReadPermissions(perms, AuthCallback);
}
private void AuthCallback(ILoginResult result)
{
if (FB.IsLoggedIn)
{
// AccessToken class will have session details
var aToken = Facebook.Unity.AccessToken.CurrentAccessToken;
// Print current access token's User ID
Debug.Log(aToken.UserId);
TextForLogging.text += $"\n{aToken.UserId}";
// Print current access token's granted permissions
foreach (string perm in aToken.Permissions)
{
Debug.Log(perm);
TextForLogging.text += $"\n{perm}";
}
FB.API("/me?fields=first_name", HttpMethod.GET, callbackData);
}
else
{
Debug.Log("User cancelled login");
TextForLogging.text += "\nUser cancelled login";
}
}

Game crashes after showing intersitial and rewarded ads

I am using admob for ads. Ads working very well on the Editor but on the phone it doesn't. I have a button in the game that show rewarded ads then load next level. And I am showing interstitial ads at end of the level then load next level. But after loading next level game crashes. I am trying to fix it for days but it keeps happening. I am adding my ad manager script. (unit ids not empty of course)
using System.Collections;
using UnityEngine;
using GoogleMobileAds.Api;
using System;
public class AdManager : MonoBehaviour
{
public static AdManager instance;
private BannerView bannerView;
private RewardedAd rewardedAd;
private InterstitialAd interstitialAd;
#if UNITY_ANDROID
string bannerAdUnitId = " ";
string rewardedAdUnitId = " ";
string interstitialAdUnitId = " ";
#else
string bannerAdUnitId = "unexpected_platform";
string rewardedAdUnitId = "unexpected_platform";
string interstitialAdUnitId = "unexpected_platform";
#endif
void Awake()
{
if(instance != null && instance != this){
Destroy(this.gameObject);
}
else{
instance = this;
DontDestroyOnLoad(this.gameObject);
}
}
private void Start() {
MobileAds.Initialize(initStatus => { });
RequestInterstitialAd();
RequestBannerAd();
RequestRewardedAd();
}
//BANNER
public void RequestBannerAd(){
if (bannerView != null)
bannerView.Destroy();
else{
bannerView = new BannerView(bannerAdUnitId, AdSize.Banner, AdPosition.Bottom);
AdRequest request = new AdRequest.Builder().Build();
bannerView.LoadAd(request);
}
}
//REWARDED
public void RequestRewardedAd(){
if(rewardedAd != null)
rewardedAd.Destroy();
rewardedAd = new RewardedAd(rewardedAdUnitId);
// Called when an ad request failed to show.
rewardedAd.OnAdFailedToShow += HandleRewardedAdFailedToShow;
// Called when the ad is closed.
rewardedAd.OnAdClosed += HandleRewardedAdClosed;
AdRequest request = new AdRequest.Builder().Build();
rewardedAd.LoadAd(request);
}
public void ShowRewardedAd(){
if (rewardedAd.IsLoaded()) {
rewardedAd.Show();
}
else{
StartCoroutine(RewardedNotLoadedFunctionCall());
}
}
IEnumerator RewardedNotLoadedFunctionCall(){
FindObjectOfType<GameManagement>().RewardedAdNotLoaded();
yield return null;
}
public void HandleRewardedAdClosed(object sender, EventArgs args)
{
RequestRewardedAd();
StartCoroutine(AdClosedFunctionCall());
}
IEnumerator AdClosedFunctionCall(){
FindObjectOfType<GameManagement>().AdClosed();
yield return null;
}
public void HandleRewardedAdFailedToShow(object sender, AdErrorEventArgs args)
{
StartCoroutine(RewardedNotLoadedFunctionCall());
}
//interstitial
private void RequestInterstitialAd(){
if(interstitialAd != null)
interstitialAd.Destroy();
interstitialAd = new InterstitialAd(interstitialAdUnitId);
interstitialAd.OnAdClosed += HandleOnAdClosed;
AdRequest request = new AdRequest.Builder().Build();
interstitialAd.LoadAd(request);
}
public void ShowInterstitialAd(){
if (interstitialAd.IsLoaded()) {
interstitialAd.Show();
}
else{
StartCoroutine(AdClosedFunctionCall());
}
}
public void HandleOnAdClosed(object sender, EventArgs args)
{
RequestInterstitialAd();
StartCoroutine(AdClosedFunctionCall());
}
}
logcat
Admob Ad does not run on the same thread as Unity's main thread.
rewardedAd.OnAdClosed += HandleRewardedAdClosed;
Calling Unity's function from Admob's thread will lead to unexpected error.
First, add UnityMainThreadDispatcher to your project. All functions called by Admob's callback need be queued by UnityMainThreadDispatcher to main thread:
public void HandleRewardedAdClosed(object sender, EventArgs args)
{
UnityMainThreadDispatcher.Instance().Enqueue(()=>{
RequestRewardedAd();
StartCoroutine(AdClosedFunctionCall());
});
}
Secondly, you should not use FindObjectOfType(). This is an expensive operation and you might run into NullReferenceException if it fails to find the GameManagement object. And since this exception did not happen on Unity's main thread, the logcat message was cryptic.
You should use Singleton or Observer pattern instead.
Thirdly, you're giving reward to user even if they skip the reward ad. Use rewardedAd.OnUserEarnedReward to make sure user have earned the reward ad.

Should object that creates ads (e.g. Banner, Interstitial) be a singleton?

Following on through the Google AdMob read on implementation for the varying ads:
https://developers.google.com/admob/unity/banner
https://developers.google.com/admob/unity/interstitial
Right now I have a C# Script which implements these ads and I go on to create a game object inside my inspector which has this script.
I believe that this is enough information for me to get a straight forward answer hopefully without any code required and a very general one.
I would like to know whether this object should be initialized only once, ideally in the Main Menu scene and be recycled through the other scenes to manage the reference to these ads.
OR
Delete the existing game object which manages those ads to then have the following scene instantiate a new one, potentially showing a different advert to the one previous.
EDIT:
AdManager Script:
using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine;
using GoogleMobileAds.Api;
public class AdManager : MonoBehaviour
{
public static AdManager instance;
//Test id: ca-app-pub-3940256099942544~3347511713
private string APP_ID = "An id";
private BannerView bannerAD;
private InterstitialAd interstitialAD;
private void Awake()
{
if (instance != null)
{
Destroy(gameObject);
}
else
{
instance = this;
DontDestroyOnLoad(gameObject);
}
}
// Start is called before the first frame update
void Start()
{
//FOR PUBLISHING ONLY
//MobileAds.Initialize(APP_ID);
RequestBannerAD();
RequestInterstitialAD();
}
private void RequestBannerAD()
{
string banner_ID = "ca-app-pub-3940256099942544/6300978111";
bannerAD = new BannerView(banner_ID, AdSize.Banner, AdPosition.Bottom);
// Called when an ad request has successfully loaded.
bannerAD.OnAdLoaded += HandleOnAdLoaded;
// Called when an ad request failed to load.
bannerAD.OnAdFailedToLoad += HandleOnAdFailedToLoad;
// Called when an ad is clicked.
bannerAD.OnAdOpening += HandleOnAdOpened;
// Called when the user returned from the app after an ad click.
bannerAD.OnAdClosed += HandleOnAdClosed;
// Called when the ad click caused the user to leave the application.
bannerAD.OnAdLeavingApplication += HandleOnAdLeavingApplication;
//FOR PRODUCTION
//AdRequest adRequest = new AdRequest.Builder().Build();
//FOR TESTING
AdRequest adRequest = new AdRequest.Builder().AddTestDevice("2077ef9a63d2b398840261c8221a0c9b").Build();
bannerAD.LoadAd(adRequest);
void HandleOnAdLoaded(object sender, EventArgs args)
{
Display_Banner();
}
void HandleOnAdFailedToLoad(object sender, AdFailedToLoadEventArgs args)
{
RequestBannerAD();
}
void HandleOnAdOpened(object sender, EventArgs args)
{
MonoBehaviour.print("HandleAdOpened event received");
}
void HandleOnAdClosed(object sender, EventArgs args)
{
MonoBehaviour.print("HandleAdClosed event received");
}
void HandleOnAdLeavingApplication(object sender, EventArgs args)
{
MonoBehaviour.print("HandleAdLeavingApplication event received");
}
}
public void Display_Banner()
{
bannerAD.Show();
}
public void DestroyBanner()
{
bannerAD.Destroy();
}
private void RequestInterstitialAD()
{
string interstitial_ID = "ca-app-pub-3940256099942544/1033173712";
interstitialAD = new InterstitialAd(interstitial_ID);
// Called when an ad request has successfully loaded.
interstitialAD.OnAdLoaded += HandleOnAdLoaded;
// Called when an ad request failed to load.
interstitialAD.OnAdFailedToLoad += HandleOnAdFailedToLoad;
// Called when an ad is clicked.
interstitialAD.OnAdOpening += HandleOnAdOpened;
// Called when the user returned from the app after an ad click.
interstitialAD.OnAdClosed += HandleOnAdClosed;
// Called when the ad click caused the user to leave the application.
interstitialAD.OnAdLeavingApplication += HandleOnAdLeavingApplication;
//FOR PRODUCTION
//AdRequest adRequest = new AdRequest.Builder().Build();
//FOR TESTING
AdRequest adRequest = new AdRequest.Builder().AddTestDevice("2077ef9a63d2b398840261c8221a0c9b").Build();
interstitialAD.LoadAd(adRequest);
void HandleOnAdLoaded(object sender, EventArgs args)
{
}
void HandleOnAdFailedToLoad(object sender, AdFailedToLoadEventArgs args)
{
}
void HandleOnAdOpened(object sender, EventArgs args)
{
MonoBehaviour.print("HandleAdOpened event received");
}
void HandleOnAdClosed(object sender, EventArgs args)
{
MonoBehaviour.print("HandleAdClosed event received");
}
void HandleOnAdLeavingApplication(object sender, EventArgs args)
{
MonoBehaviour.print("HandleAdLeavingApplication event received");
}
}
public void Display_Interstitial()
{
if (interstitialAD.IsLoaded())
{
interstitialAD.Show();
}
}
public void DestroyInterstitial()
{
interstitialAD.Destroy();
}
}
MenuLoader Script (fragment to interstitial call attached to a UI Button):
public void LoadGameOver()
{
StartCoroutine(WaitAndLoad_GameOver());
}
private IEnumerator WaitAndLoad_GameOver()
{
yield return new WaitForSeconds(gameOver_loadDelay);
FindObjectOfType<AdManager>().Display_Interstitial();
SceneManager.LoadScene("Game Over");
}
EDIT 2 (In response to Eliasar):
06-20 22:07:13.988 6492 6518 E Unity : NullReferenceException: Object reference not set to an instance of an object
06-20 22:07:13.988 6492 6518 E Unity : at AdManager.Display_Banner () [0x00000] in <0b5b8f6032c04370a5fa0fecd73ecd6b>:0
06-20 22:07:13.988 6492 6518 E Unity : at MenuLoader+<WaitAndLoad_Game>d__6.MoveNext () [0x00084] in <0b5b8f6032c04370a5fa0fecd73ecd6b>:0
06-20 22:07:13.988 6492 6518 E Unity : at UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) [0x00027] in <1f017b19aaf9475abf1041405dbaf390>:0
06-20 22:07:13.988 6492 6518 E Unity :
AdManager:
using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine;
using GoogleMobileAds.Api;
public static class AdManager
{
//public static AdManager instance;
//Test id: ca-app-pub-3940256099942544~3347511713
private static string APP_ID = "An id";
private static BannerView bannerAD;
private static InterstitialAd interstitialAD;
//private void Awake()
//{
// if (instance != null)
// {
// Destroy(gameObject);
// }
// else
// {
// instance = this;
// DontDestroyOnLoad(gameObject);
// }
//}
// Start is called before the first frame update
//void Start()
//{
// //FOR PUBLISHING ONLY
// //MobileAds.Initialize(APP_ID);
// RequestBannerAD();
// RequestInterstitialAD();
//}
private static void RequestBannerAD()
{
string banner_ID = "ca-app-pub-3940256099942544/6300978111";
bannerAD = new BannerView(banner_ID, AdSize.Banner, AdPosition.Bottom);
// Called when an ad request has successfully loaded.
bannerAD.OnAdLoaded += HandleOnAdLoaded;
// Called when an ad request failed to load.
bannerAD.OnAdFailedToLoad += HandleOnAdFailedToLoad;
// Called when an ad is clicked.
bannerAD.OnAdOpening += HandleOnAdOpened;
// Called when the user returned from the app after an ad click.
bannerAD.OnAdClosed += HandleOnAdClosed;
// Called when the ad click caused the user to leave the application.
bannerAD.OnAdLeavingApplication += HandleOnAdLeavingApplication;
//FOR PRODUCTION
//AdRequest adRequest = new AdRequest.Builder().Build();
//FOR TESTING
AdRequest adRequest = new AdRequest.Builder().AddTestDevice("2077ef9a63d2b398840261c8221a0c9b").Build();
bannerAD.LoadAd(adRequest);
void HandleOnAdLoaded(object sender, EventArgs args)
{
Display_Banner();
}
void HandleOnAdFailedToLoad(object sender, AdFailedToLoadEventArgs args)
{
RequestBannerAD();
}
void HandleOnAdOpened(object sender, EventArgs args)
{
MonoBehaviour.print("HandleAdOpened event received");
}
void HandleOnAdClosed(object sender, EventArgs args)
{
MonoBehaviour.print("HandleAdClosed event received");
}
void HandleOnAdLeavingApplication(object sender, EventArgs args)
{
MonoBehaviour.print("HandleAdLeavingApplication event received");
}
}
public static void Display_Banner()
{
bannerAD.Show();
}
public static void DestroyBanner()
{
bannerAD.Destroy();
}
private static void RequestInterstitialAD()
{
string interstitial_ID = "ca-app-pub-3940256099942544/1033173712";
interstitialAD = new InterstitialAd(interstitial_ID);
// Called when an ad request has successfully loaded.
interstitialAD.OnAdLoaded += HandleOnAdLoaded;
// Called when an ad request failed to load.
interstitialAD.OnAdFailedToLoad += HandleOnAdFailedToLoad;
// Called when an ad is clicked.
interstitialAD.OnAdOpening += HandleOnAdOpened;
// Called when the user returned from the app after an ad click.
interstitialAD.OnAdClosed += HandleOnAdClosed;
// Called when the ad click caused the user to leave the application.
interstitialAD.OnAdLeavingApplication += HandleOnAdLeavingApplication;
//FOR PRODUCTION
//AdRequest adRequest = new AdRequest.Builder().Build();
//FOR TESTING
AdRequest adRequest = new AdRequest.Builder().AddTestDevice("2077ef9a63d2b398840261c8221a0c9b").Build();
interstitialAD.LoadAd(adRequest);
void HandleOnAdLoaded(object sender, EventArgs args)
{
}
void HandleOnAdFailedToLoad(object sender, AdFailedToLoadEventArgs args)
{
}
void HandleOnAdOpened(object sender, EventArgs args)
{
MonoBehaviour.print("HandleAdOpened event received");
}
void HandleOnAdClosed(object sender, EventArgs args)
{
MonoBehaviour.print("HandleAdClosed event received");
}
void HandleOnAdLeavingApplication(object sender, EventArgs args)
{
MonoBehaviour.print("HandleAdLeavingApplication event received");
}
}
public static void Display_Interstitial()
{
if (interstitialAD.IsLoaded())
{
interstitialAD.Show();
}
}
public static void DestroyInterstitial()
{
interstitialAD.Destroy();
}
}
MenuLoader (fragment edit):
public void LoadGameOver()
{
StartCoroutine(WaitAndLoad_GameOver());
}
private IEnumerator WaitAndLoad_GameOver()
{
yield return new WaitForSeconds(gameOver_loadDelay);
AdManager.Display_Interstitial();
//FindObjectOfType<AdManager>().Display_Interstitial();
SceneManager.LoadScene("Game Over");
AdManager.Display_Banner();
}

How to solve Admob Error failed to load ad 0

I have implemented Admob in my app and working well with test ads.
I am loading ads in feed list, and getting error " Failed to load Ad: 0". According to Stack Overflow answers, this error mostly related to newly created ad units, but it had been more than 15 days but getting the same error. While rewarded video ad unit is working fine. Admob account is also with approved status. Asked the same question in Google Admob Community, but no answer.
Don't mark it duplicate of this question as the accepted answer says to wait, but in my case, I am waiting for last 15 days.
Here is code snippet.
private void showNativeGoogleAd(UnifiedNativeAdViewHolder holder)
{
AdLoader adLoader = new AdLoader.Builder(mContext, mContext.getString(R.string.admob_social_wall_ad_unit_id))
//AdLoader adLoader = new AdLoader.Builder(mContext, "ca-app-pub-3940256099942544/1044960115")
.forUnifiedNativeAd(new UnifiedNativeAd.OnUnifiedNativeAdLoadedListener() {
#Override
public void onUnifiedNativeAdLoaded(UnifiedNativeAd unifiedNativeAd) {
// Show the ad.
populateNativeAdView(unifiedNativeAd, holder.adView);
//holder.fl_adplaceholder.removeAllViews();
//holder.fl_adplaceholder.addView(holder.adView);
}
})
.withAdListener(new AdListener() {
#Override
public void onAdFailedToLoad(int errorCode) {
// Handle the failure by logging, altering the UI, and so on.
Log.d("TAG", "onAdFailedToLoad: Google => "+errorCode);
}
})
.withNativeAdOptions(new NativeAdOptions.Builder()
// Methods in the NativeAdOptions.Builder class can be
// used here to specify individual options settings.
.build())
.build();
adLoader.loadAd(new AdRequest.Builder().build());
}
private void populateNativeAdView(UnifiedNativeAd nativeAd,
UnifiedNativeAdView adView) {
// Some assets are guaranteed to be in every UnifiedNativeAd.
((TextView) adView.getHeadlineView()).setText(nativeAd.getHeadline());
((TextView) adView.getBodyView()).setText(nativeAd.getBody());
((Button) adView.getCallToActionView()).setText(nativeAd.getCallToAction());
// These assets aren't guaranteed to be in every UnifiedNativeAd, so it's important to
// check before trying to display them.
com.google.android.gms.ads.formats.NativeAd.Image icon = nativeAd.getIcon();
if (icon == null) {
adView.getIconView().setVisibility(View.INVISIBLE);
} else {
((ImageView) adView.getIconView()).setImageDrawable(icon.getDrawable());
adView.getIconView().setVisibility(View.VISIBLE);
}
if (nativeAd.getPrice() == null) {
adView.getPriceView().setVisibility(View.INVISIBLE);
} else {
adView.getPriceView().setVisibility(View.VISIBLE);
((TextView) adView.getPriceView()).setText(nativeAd.getPrice());
}
if (nativeAd.getStore() == null) {
adView.getStoreView().setVisibility(View.INVISIBLE);
} else {
adView.getStoreView().setVisibility(View.VISIBLE);
((TextView) adView.getStoreView()).setText(nativeAd.getStore());
}
if (nativeAd.getStarRating() == null) {
adView.getStarRatingView().setVisibility(View.INVISIBLE);
} else {
((RatingBar) adView.getStarRatingView())
.setRating(nativeAd.getStarRating().floatValue());
adView.getStarRatingView().setVisibility(View.VISIBLE);
}
if (nativeAd.getAdvertiser() == null) {
adView.getAdvertiserView().setVisibility(View.INVISIBLE);
} else {
((TextView) adView.getAdvertiserView()).setText(nativeAd.getAdvertiser());
adView.getAdvertiserView().setVisibility(View.VISIBLE);
}
// Assign native ad object to the native view.
adView.setNativeAd(nativeAd);
}

I want to refresh/recreate my activity programatically when getting response from server

I want when server sends some response in form of WebView then immediately my activity gets refreshed and so WebView in form of banner ad.
I write code for display banner ad but ad is showing only when my activity recreated i.e. when I rotate my screen then banner is showing but when it is in same static mode then banner is not showing.
So, please let me know what I will do so that when server gave some response immediately it will be shown on my activity.
void startDemo() {
//Set Http Client Options
final OptimusHTTP client = new OptimusHTTP();
client.enableDebugging();
client.setMethod(OptimusHTTP.METHOD_POST);
client.setMode(OptimusHTTP.MODE_SEQ);
FreqDetector_Goertzel.getInstance().startRecording(new FreqDetector_Goertzel.RecordTaskListener() {
private String urlRedirect = "";
private String imgSmallBanner = "";
#Override
public void onSuccess(int val)
{
String pSet = pVal.getPatternSet(val, 5);
if (pSet != null) {
FreqDetector_Goertzel.getInstance().stopRecording();
EasyDeviceInfo deviceInfo = new EasyDeviceInfo(MainActivity.this);
final HashMap<String, String> device_params = new HashMap<>();
device_params.put("aid", deviceInfo.getAndroidID());
device_params.put("pattern", pSet);
if (isNetworkAvailable(MainActivity.this)) {
try {
client.makeRequest(MainActivity.this, new HttpReq(), Defaults.MATCHINGSERVER, device_params, new OptimusHTTP.ResponseListener() {
#Override
public void onSuccess(String s) {
try {
if (s != null && !s.contains("No Match Found"))
{
JSONObject jsonObject = null;
jsonObject = new JSONObject(s);
imgSmallBanner = Uri.decode(jsonObject.optString("smallImgUrl", "NA"));
urlRedirect = Uri.decode(jsonObject.optString("redirectUrl", "NA"));
loadAdvertisement(urlRedirect, imgSmallBanner);
} else {
//Did not match
startDemo();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(String s) {
}
});
} catch (Exception e) {
e.printStackTrace();
}
} else {
//Internet not available. Do not do anything.
}
}
}
#Override
public void onFailure(String s) {
}
});
}
void loadAdvertisement(String clickUrl, String imgSmallName) {
String click_url;
String img_small_url;
stopDemo();
click_url = Uri.decode(Uri.encode(clickUrl));
img_small_url = imgSmallName;
StringBuilder htmlData2 = new StringBuilder();
htmlData2.append("<html><body style='margin:0;padding:0;background-color:black;'><a href='").append(click_url).append("' ><img src='").append(img_small_url).append("' height=50 style='margin:0 auto;display:block;' /></a></body></html>");
webView_img_small.loadDataWithBaseURL("file:///android_asset/", htmlData2.toString(), "text/html", "utf-8", null);
webView_img_small.setVisibility(View.VISIBLE);
/* What I will do here so when server sends response it will immediately being refreshed and shown on activity without recreating it.*/ }
here you can find some response: http://developer.android.com/guide/topics/ui/how-android-draws.html
for me a call to invalidate() only refresh the view and a call to requestLayout() refresh the view and compute the size of the view in the screen.
You can try to use Activity.recreate(). This method will destroy your current Activity and create a new Activity same way when you rotate device.
Hope this helps.

Categories

Resources