hide admob banner ads - libgdx

I would like to show banner admob exactly at the moment the user enter into the main game screen. I hide the banner in onCreate with setAlpha(0f) method, and show it in the first render loop with setAlpha(1f). The timing is a bit off. How do I make it more precise? I also wonder if setting alpha is acceptable method to hide admob adds?
//RENDER LOOP
if(showAd==false){
actionResolver.showBanner();
showAd=true;
}
//android launcher
protected AdView adView;
protected View gameView;
private InterstitialAd interstitialAd;
private Activity context;
#Override
public void showBanner() {
try {
runOnUiThread(new Runnable() {
public void run() {
adView.setAlpha(1f);
}
});
} catch (Exception e) {
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context=this;
AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration();
// Do the stuff that initialize() would do for you
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
RelativeLayout layout = new RelativeLayout(this);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
layout.setLayoutParams(params);
AdView admobView = createAdView();
layout.addView(admobView);
View gameView = createGameView(cfg);
layout.addView(gameView);
setContentView(layout);
startAdvertising(admobView);
interstitialAd = new InterstitialAd(this);
interstitialAd.setAdUnitId(AD_UNIT_ID_INTERSTITIAL);
interstitialAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
}
#Override
public void onAdClosed() {
super.onAdClosed();
loadInterstitial();
}
});
}
private AdView createAdView() { ////// HERE I SET ALPHA
adView = new AdView(this);
adView.setAdSize(AdSize.SMART_BANNER);
adView.setAdUnitId(AD_UNIT_ID_BANNER);
adView.setId(123456); // this is an arbitrary id, allows for relative positioning in createGameView()
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
params.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
adView.setLayoutParams(params);
adView.setBackgroundColor(Color.BLACK);
adView.setAlpha(0f);
return adView;
}
private View createGameView(AndroidApplicationConfiguration cfg) {
gameView = initializeForView(new Cube(this,this), cfg);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
params.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
params.addRule(RelativeLayout.BELOW, adView.getId());
gameView.setLayoutParams(params);
return gameView;
}
private void startAdvertising(AdView adView) {
// AdRequest adRequest = new AdRequest.Builder().build();
// adView.loadAd(adRequest);
AdRequest.Builder builder = new AdRequest.Builder();
// builder.addTestDevice("3F39DA9CF3F587314F9C4C0D88639C28");
adView.loadAd(builder.build());
}
#Override
public void showInterstitial() {
try {
runOnUiThread(new Runnable() {
public void run() {
if (interstitialAd.isLoaded()) {
interstitialAd.show();
}
}
});
} catch (Exception e) {
}
}
#Override
public void loadInterstitial() {
try {
runOnUiThread(new Runnable() {
public void run() {
if(interstitialAd.isLoaded()){
}else{
AdRequest interstitialRequest = new AdRequest.Builder().build();
interstitialAd.loadAd(interstitialRequest);
}
}
});
} catch (Exception e) {
}
}
#Override
public void onResume() {
super.onResume();
if (adView != null) adView.resume();
}
#Override
public void onPause() {
if (adView != null) adView.pause();
super.onPause();
}
#Override
public void onDestroy() {
if (adView != null) adView.destroy();
super.onDestroy();
}
#TargetApi(19)
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
}
}

Related

how to add ( admob ) Interstitial ads to libgdx game and what activity to use?

I followed google guide:
updated build.gradle dependencies
updated AndroidManifest.xml
updated the AndroidLauncher and tried banner ads first
from libgdx wiki https://libgdx.com/wiki/third-party/admob-in-libgdx
#Override public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create the layout
RelativeLayout layout = new RelativeLayout(this);
// Do the stuff that initialize() would do for you
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
// Create the libGDX View
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
View gameView = initializeForView(new mygame(), config);
// Create and setup the AdMob view
AdView adView = new AdView(this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111"); // Put in your secret key here
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
// Add the libGDX view
layout.addView(gameView);
// Add the AdMob view
RelativeLayout.LayoutParams adParams =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
adParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
adParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
layout.addView(adView, adParams);
// Hook it all up
setContentView(layout);
}}
but I cant figure out how to do the same for Interstitial ads
i tried adding adscontroller interface
public interface AdsController {
public void loadInterstitialAd();
public void showInterstitialAd();
}
and updating AndroidLauncher
public class AndroidLauncher extends AndroidApplication implements AdsController {
InterstitialAd mInterstitialAd;
private static final String TAG = "Androidlauncher";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// // Create the layout
RelativeLayout layout = new RelativeLayout(this);
// Do the stuff that initialize() would do for you
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
// Create the libGDX View
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
View gameView = initializeForView(new mygame(this), config);
layout.addView(gameView);
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {}
});
AdRequest adRequest = null;
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.d(TAG, loadAdError.toString());
mInterstitialAd = null;
}
});
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback(){
#Override
public void onAdClicked() {
// Called when a click is recorded for an ad.
Log.d(TAG, "Ad was clicked.");
}
#Override
public void onAdDismissedFullScreenContent() {
// Called when ad is dismissed.
// Set the ad reference to null so you don't show the ad a second time.
Log.d(TAG, "Ad dismissed fullscreen content.");
mInterstitialAd = null;
}
#Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
// Called when ad fails to show.
Log.e(TAG, "Ad failed to show fullscreen content.");
mInterstitialAd = null;
}
#Override
public void onAdImpression() {
// Called when an impression is recorded for an ad.
Log.d(TAG, "Ad recorded an impression.");
}
#Override
public void onAdShowedFullScreenContent() {
// Called when ad is shown.
Log.d(TAG, "Ad showed fullscreen content.");
}
});
loadInterstitialAd();
}
#Override
public void loadInterstitialAd() {
AdRequest adRequest = new AdRequest.Builder().build();
}
#Override
public void showInterstitialAd() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if(mInterstitialAd!=null) {
mInterstitialAd.show();
}
else loadInterstitialAd();
}
});
}
}
InterstitialAd.show(MyActivity.this); require activity but libgdx doesn't work like that(I think?)
every code I found is no longer useful because google updated Admob
AndroidApplication extends Activity, so for interstitials you can just pass in a reference to the application, eg InterstitialAd.show(this);
I did something very similar to get interstitials working in my project. I use Ironsource but the process should be very similar. First, I defined an AdManager interface:
public interface AdManager {
/**
* Show a rewarded video ad
*/
void showRewardedVideo();
/**
* Called on app pause
*/
void onPause();
/**
* Called on app resume
*/
void onResume();
/**
* Attempts to show an interstitial ad
*
* #param onSuccess
* #param onFailed
*/
void showInterstitial(Listener onSuccess, Listener onFailed);
/**
* Called every frame, for any extra work that might need to be done
*
* #param deltaTime
*/
void update(float deltaTime);
}
Following that, you can implement your platform's ad provider:
public class AndroidAdManager implements AdManager, RewardedVideoListener, InterstitialListener, OfferwallListener {
private OnlineRPG game;
private boolean videoAvailable;
private Listener onInterstitialSuccess;
private Listener onInterstitialFailed;
private float timeSinceAd;
public AndroidAdManager(Activity activity, Gamegame) {
this.game = game;
this.activity = activity;
IronSource.setRewardedVideoListener(this);
IronSource.setInterstitialListener(this);
IronSource.setOfferwallListener(this);
IronSource.init(activity, "whatever");
IronSource.shouldTrackNetworkState(activity, true);
IronSource.loadInterstitial();
IntegrationHelper.validateIntegration(activity);
}
#Override
public void showRewardedVideo() {
if (IronSource.isRewardedVideoPlacementCapped(REWARDED_VIDEO_PLACEMENT_NAME)) {
Log.i(TAG, "Rewarded video placement is capped");
return;
}
IronSource.showRewardedVideo(REWARDED_VIDEO_PLACEMENT_NAME);
}
#Override
public void onPause() {
IronSource.onPause(activity);
}
#Override
public void onResume() {
IronSource.onResume(activity);
}
#Override
public void showInterstitial(Listener onSuccess, Listener onFailed) {
if (timeSinceAd < INTERSTITIAL_MIN_PERIOD || true) {
onFailed.invoke();
return;
}
this.onInterstitialSuccess = onSuccess;
this.onInterstitialFailed = onFailed;
IronSource.showInterstitial(INTERSTITIAL_PLACEMENT_NAME);
}
#Override
public void update(float deltaTime) {
timeSinceAd += deltaTime;
}
#Override
public void onRewardedVideoAdOpened() {
}
#Override
public void onRewardedVideoAdClosed() {
}
#Override
public void onRewardedVideoAvailabilityChanged(boolean b) {
Log.i(TAG, "onRewardedVideoAvailabilityChanged: " + b);
videoAvailable = b;
}
#Override
public void onRewardedVideoAdStarted() {
}
#Override
public void onRewardedVideoAdEnded() {
}
#Override
public void onRewardedVideoAdRewarded(Placement placement) {
}
#Override
public void onRewardedVideoAdShowFailed(IronSourceError ironSourceError) {
}
#Override
public void onRewardedVideoAdClicked(Placement placement) {
}
#Override
public void onInterstitialAdReady() {
}
#Override
public void onInterstitialAdLoadFailed(IronSourceError ironSourceError) {
if (onInterstitialFailed != null) {
Gdx.app.postRunnable(new Runnable() {
#Override
public void run() {
onInterstitialFailed.invoke();
onInterstitialFailed = null;
}
});
}
}
#Override
public void onInterstitialAdOpened() {
Log.i(TAG, "Interstitial Ad Opened");
}
#Override
public void onInterstitialAdClosed() {
Log.i(TAG, "Interstitial Ad Closed");
if (onInterstitialSuccess != null) {
Gdx.app.postRunnable(new Runnable() {
#Override
public void run() {
timeSinceAd = 0;
onInterstitialSuccess.invoke();
onInterstitialSuccess = null;
}
});
}
IronSource.loadInterstitial();
}
#Override
public void onInterstitialAdShowSucceeded() {
}
#Override
public void onInterstitialAdShowFailed(IronSourceError ironSourceError) {
Log.e(TAG, ironSourceError.getErrorMessage());
if (onInterstitialFailed != null) {
Gdx.app.postRunnable(new Runnable() {
#Override
public void run() {
onInterstitialFailed.invoke();
onInterstitialFailed = null;
}
});
}
}
#Override
public void onInterstitialAdClicked() {
}
#Override
public void onOfferwallAvailable(boolean b) {
}
#Override
public void onOfferwallOpened() {
}
#Override
public void onOfferwallShowFailed(IronSourceError ironSourceError) {
}
#Override
public boolean onOfferwallAdCredited(int i, int i1, boolean b) {
return false;
}
#Override
public void onGetOfferwallCreditsFailed(IronSourceError ironSourceError) {
}
#Override
public void onOfferwallClosed() {
}
}
Lastly, in your AndroidLauncher you can create your AndroidAdManager, giving it a reference to your game/activity.
public class AndroidLauncher extends AndroidApplication {
private Game game;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
game = new Game();
game.setAdManager(new AndroidAdManager(this, game));
game.setPermissionManager(new AndroidPermissionManager(this, game));
initialize(game, config);
}
#Override
protected void onPause() {
super.onPause();
game.getAds().onPause();
}
#Override
protected void onResume() {
super.onResume();
game.getAds().onResume();
}
}
I hope this helps in your project!

Getting data in recyclerView

i am getting messages from the database into a recycler view but i want to refresh the recycler view every second for to adding different for to getting new messages in recycler view
But i haver an error of getting data please see it https://www.filemail.com/d/izhittgyibvcjxx
my code is
boolean refresh;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message_user);
refresh = true;
content();
}
public void content()
{
getdata();
if (refresh)
{
refresh(100);
}
}
private void refresh(int milliseconds)
{
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
#Override
public void run() {
content();
}
};
handler.postDelayed(runnable,milliseconds);
}
private void getdata()
{
String Choice = "Get Messages";
Call<List<responsemodel>> call = SplashScreen.apiInterface.getfullprofiledata(Choice,Message_To,Message_From);
call.enqueue(new Callback<List<responsemodel>>() {
#Override
public void onResponse(Call<List<responsemodel>> call, Response<List<responsemodel>> response) {
List<responsemodel> data = response.body();
Message_user_Adapter adapter = new Message_user_Adapter(data,Message_To);
messages_Message_user_RecyclerView.setAdapter(adapter);
messages_Message_user_RecyclerView.smoothScrollToPosition(messages_Message_user_RecyclerView.getAdapter().getItemCount());
}
#Override
public void onFailure(Call<List<responsemodel>> call, Throwable t) {
}
});
}

Why my pager adapter cant show the data that I load from openweather(as json format) cant show properly

Why my pager adapter cant show the data that I load from openweather(as json format) cant show properly. I got five page in the slide view and the data in the first page will not show unless I load to the third page and the data in second page will show only when I load to the fourth page.
This is the coding of my slider java class
public class SliderAdapter extends PagerAdapter {
Context context;
LayoutInflater layoutInflater;
private static final String TAG = "SliderAdapter";
public SliderAdapter(Context context)
{
this.context=context;
}
public double[] slide_headings= new double[50];
public String[] slide_desc=new String[50];
public String[] slide_images= new String[50];
public static final String URL_DATA = "http://api.openweathermap.org/data/2.5/forecast?id=1732698&appid=4bdfb7127d4a85742cfbb201078ba566";
#Override
public int getCount() {
return 5;
}
#Override
public boolean isViewFromObject(View view,Object o) {
return view== o;
}
#Override
public Object instantiateItem(ViewGroup container,int position)
{
getData();
layoutInflater= (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View view=layoutInflater.inflate(R.layout.slide_layout,container,false);
ImageView slideImageView=view.findViewById(R.id.imageView);
TextView slideHeading=view.findViewById(R.id.textView);
TextView slideDescription=view.findViewById(R.id.textView2);
Glide.with(context).load(slide_images[position]).into(slideImageView);
slideHeading.setText(Double.toString(slide_headings[position]));
slideDescription.setText(slide_desc[position]);
container.addView(view);
return view;
}
private void getData() {
final ProgressDialog progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Loading data.....");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST,
URL_DATA,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(s);
for (int i = 0; i < jsonObject.length(); i++) {
JSONArray JA = (JSONArray) jsonObject.get("list");
for (int j = 0; j < JA.length(); j++) {
JSONObject JO = JA.getJSONObject(j);
JSONObject jo = (JSONObject) JO.get("main");
slide_headings[j] = jo.getDouble("temp");
JSONArray ja = JO.getJSONArray("weather");
for (int k = 0; k < ja.length(); k++) {
JSONObject o = ja.getJSONObject(k);
slide_desc[j] = o.getString("main");
slide_images[j] = "http://openweathermap.org/img/w/" + o.getString("icon") + ".png";
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
//this method will run when there is error sending the request
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
progressDialog.dismiss();
Toast.makeText(context, volleyError.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(context);
requestQueue.add(stringRequest);
}
#Override
public void destroyItem(ViewGroup container, int position,Object object) {
container.removeView((RelativeLayout)object);
}
}
This is my example of my main java class
public class MainActivity extends AppCompatActivity {
private ViewPager mSLideViewPager;
private LinearLayout mDotLayout;
private SliderAdapter sliderAdapter;
private TextView[] mDots;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSLideViewPager=findViewById(R.id.slideViewPager);
mDotLayout=findViewById(R.id.dotsLayout);
sliderAdapter=new SliderAdapter(this);
mSLideViewPager.setAdapter(sliderAdapter);
addDotsIndicator(0);
mSLideViewPager.addOnPageChangeListener(viewListener);
}
public void addDotsIndicator(int position){
mDotLayout.removeAllViews();
mDots=new TextView[5];
for(int i=0;i<mDots.length ;i++)
{
mDots[i] = new TextView(this);
mDots[i].setText(Html.fromHtml("&#8226"));
mDots[i].setTextSize(35);
mDots[i].setTextColor(getResources().getColor(R.color.colorTransparentWhite));
mDotLayout.addView(mDots[i]);
}
if(mDots.length >0){
mDots[position].setTextColor(getResources().getColor(R.color.colorWhite));
}
}
ViewPager.OnPageChangeListener viewListener= new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i1) {
}
#Override
public void onPageSelected(int i) {
addDotsIndicator(i);
}
#Override
public void onPageScrollStateChanged(int i) {
}
};
}
I have used array list instead of array and this solve my problems

How to send a JSON object to a server with Volley library in android?

I want to send a json object to the server using the post method.
I have used volley library to pass the string params, and it's working fine, but when I run my app I am getting this:
BasicNetwork.performRequest: Unexpected response code 400
my code:-
public class MainActivity extends AppCompatActivity {
ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
makeJsonObjReq();
}
private void makeJsonObjReq() {
JSONObject request=new JSONObject();
try {
request.put("ProductCode", "KK03672-038");
} catch (JSONException e) {
e.printStackTrace();
}
pd = ProgressDialog.show(MainActivity.this, "Alert", "Please Wait...");
JsonObjectRequest jsonObjReq = new JsonObjectRequest(
"URL",request,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
pd.dismiss();
System.out.println("Response is====>" + response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pd.dismiss();
System.out.println("Error is====>" + error.getMessage());
}
}) {
/**
* Passing some request headers
* */
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
#Override
public String getBodyContentType() {
return "application/json";
}
};
// Adding request to request queue:-
AppController.getInstance().addToRequestQueue(jsonObjReq);
}
}
AppContoller:-
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public ImageLoader getImageLoader() {
getRequestQueue();
if (mImageLoader == null) {
mImageLoader = new ImageLoader(this.mRequestQueue,
new LruBitmapCache());
}
return this.mImageLoader;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
// set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
Try adding volley initialization code in Application class and reference this to your manifest application tag.

How to get rid of edges in JFXPanel?

I'm developing a Java Swing map application, it gets a url and loads maps from Google maps at different zoom levels.
But the address bar in the maps are annoying, I want to get rid of it or reduce it's space.
In my code below, I first tried: Use_iFrame_B=false;
This will get a map with large address bar like this, and zooming isn't working :
Then I tried: Use_iFrame_B=true;
This will show maps with zooming, but has large edges:
So, my questions are :
When Use_iFrame_B=false, how to hide the address bar in the first case and still show an indicator [ red balloon ] on the address ?
How to make zoom work in the above case [ Use_iFrame_B=false ].
If 1 and 2 above are not doable, then I'd prefer to use iFrame which will show a smaller more meaningful address and zooming also works. But it leaves large edges, how to get rid of those edges when Use_iFrame_B=true?
Here are my programs:
import java.awt.*;
import java.io.File;
import java.net.URL;
import javafx.embed.swing.JFXPanel;
import javafx.application.Platform;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.layout.*;
import javafx.scene.web.*;
import javax.swing.*;
import javax.swing.border.*;
/**
Note using the browser might require setting the properties
- http.proxyHost
- http.proxyPort
e.g. -Dhttp.proxyHost=webcache.mydomain.com -Dhttp.proxyPort=8080
*/
public class JavaFX_Browser_Panel extends JPanel
{
static int Edge_W=0,Edge_H=0;
private int PANEL_WIDTH_INT=1200,PANEL_HEIGHT_INT=900;
private JFXPanel browserFxPanel;
private Pane browser;
WebView view;
WebEngine eng;
// static String Url,Urls[]=new String[]{"http://www.Yahoo.com","www.Google.com","dell.com","C:/Dir_Fit/Yahoo_Maps_Frame.html","C:/Dir_Broadband_TV/TV.html"};
// static String Url,Urls[]=new String[]{"C:/Dir_Broadband_TV/TV.html"};
// static String Url,Urls[]=new String[]{"http://screen.yahoo.com/cecily-strong-snl-skits/hermes-000000630.html"};
static String Url,Urls[]=new String[]{"https://www.google.com/maps/#33.8470183,-84.3677322,11z"};
public JavaFX_Browser_Panel() { init(); }
public JavaFX_Browser_Panel(int W,int H)
{
PANEL_WIDTH_INT=W+Edge_W;
PANEL_HEIGHT_INT=H+Edge_H;
init();
}
public JavaFX_Browser_Panel(String Url)
{
this.Url=Url;
init();
setURL(Url);
}
void init()
{
FlowLayout FL=new FlowLayout();
FL.setHgap(0);
FL.setVgap(0);
setLayout(FL);
browserFxPanel=new JFXPanel();
// browserFxPanel.setBorder(new EmptyBorder(0,0,0,0));
add(browserFxPanel);
setPreferredSize(new Dimension(PANEL_WIDTH_INT,PANEL_HEIGHT_INT));
Platform.runLater(new Runnable() { public void run() { createScene(); } });
}
public static void Set_Edge(int W,int H)
{
Edge_W=W;
Edge_H=H;
}
public String getURL() { return eng.getLocation(); }
public String goBack()
{
final WebHistory history=eng.getHistory();
ObservableList<WebHistory.Entry> entryList=history.getEntries();
int currentIndex=history.getCurrentIndex();
// Out("currentIndex = "+currentIndex);
// Out(entryList.toString().replace("],","]\n"));
Platform.runLater(new Runnable() { public void run() { history.go(-1); } });
return entryList.get(currentIndex>0?currentIndex-1:currentIndex).getUrl();
}
public String goForward()
{
final WebHistory history=eng.getHistory();
ObservableList<WebHistory.Entry> entryList=history.getEntries();
int currentIndex=history.getCurrentIndex();
// Out("currentIndex = "+currentIndex);
// Out(entryList.toString().replace("],","]\n"));
Platform.runLater(new Runnable() { public void run() { history.go(1); } });
return entryList.get(currentIndex<entryList.size()-1?currentIndex+1:currentIndex).getUrl();
}
public void refresh() { Platform.runLater(new Runnable() { public void run() { eng.reload(); } }); }
public void stop() { Platform.runLater(new Runnable() { public void run() { eng.getLoadWorker().cancel(); } }); }
public void Load_iFrame(final String Url,final int W,final int H)
{
Platform.runLater(new Runnable()
{
public void run()
{
if (new File(Url).exists()) setURL(new File(Url));
else eng.loadContent("<iframe width="+W+" height="+H+" src="+Url+" style=border:0; marginheight=0 marginwidth=0 allowfullscreen></iframe>");
// else eng.loadContent("<iframe width="+W+" height="+H+" src="+Url+" frameborder=0 marginheight=0 marginwidth=0 allowfullscreen></iframe>");
// else eng.loadContent("<iframe width='990' height='915' src="+Url+" frameborder='0' allowfullscreen></iframe>");
}
});
}
public void setURL(final String Url)
{
Platform.runLater(new Runnable()
{
public void run()
{
if (new File(Url).exists()) setURL(new File(Url));
else eng.load((Url.startsWith("http://") || Url.startsWith("https://"))?Url:"http://"+Url);
}
});
}
public void setURL(final URL Url)
{
Platform.runLater(new Runnable()
{
public void run()
{
try { eng.load(Url.toString()); }
catch (Exception e) { e.printStackTrace(); }
}
});
}
public void setURL(final File file)
{
Platform.runLater(new Runnable()
{
public void run()
{
try { eng.load(file.toURI().toURL().toString()); }
catch (Exception e) { e.printStackTrace(); }
}
});
}
private void createScene()
{
browser=createBrowser();
browserFxPanel.setScene(new Scene(browser));
}
private Pane createBrowser()
{
Double widthDouble=new Integer(PANEL_WIDTH_INT).doubleValue();
Double heightDouble=new Integer(PANEL_HEIGHT_INT).doubleValue();
view=new WebView();
view.setMinSize(widthDouble,heightDouble);
view.setPrefSize(widthDouble,heightDouble);
eng=view.getEngine();
GridPane grid=new GridPane();
grid.getChildren().addAll(view);
return grid;
}
public static void out(String message) { System.out.print(message); }
public static void Out(String message) { System.out.println(message); }
public static void main(String[] args)
{
final JavaFX_Browser_Panel demo=new JavaFX_Browser_Panel(Urls[0]);
int i=0;
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
// try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); }
// catch (Exception e) { e.printStackTrace(); }
JFrame frame=new JFrame("JavaFX 2.2 in Swing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(demo);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
while (i<Urls.length-1)
{
try
{
demo.setURL(Urls[++i]);
Thread.sleep(2000);
}
catch (Exception e) { e.printStackTrace(); }
}
// demo.goBack();
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class Map_Maker_2 extends JPanel implements Runnable
{
public static final long serialVersionUID=26362862L;
int W=1600,H=1200,JavaFX_Browser_Edge_W=200,JavaFX_Browser_Edge_H=200,Upper_Left_Button_Panel_W=90;
static Dimension Screen_Size=Toolkit.getDefaultToolkit().getScreenSize();
String Google_Url="http://maps.google.com/maps?q=Address&t=m&z=Zoom",Address="760 West Genesee Street Syracuse NY 13204",Url;
Insets An_Inset=new Insets(0,0,0,0);
JTextArea Upper_Left_TextArea=new JTextArea(Address);
JavaFX_Browser_Panel Left_JavaFX_Browser_Panel,Upper_Right_JavaFX_Browser_Panel,Lower_Right_JavaFX_Browser_Panel;
// boolean Use_iFrame_B=true;
boolean Use_iFrame_B=false;
Thread Empty_JPanel_Thread;
public Map_Maker_2()
{
JavaFX_Browser_Panel.Set_Edge(JavaFX_Browser_Edge_W,JavaFX_Browser_Edge_H);
FlowLayout Fl=new FlowLayout(0,0,0);
setLayout(Fl);
JPanel Left_Panel=new JPanel(Fl);
Left_Panel.setBorder(new EtchedBorder());
Left_Panel.setPreferredSize(new Dimension(W/2,H));
add(Left_Panel);
JPanel Upper_Left_Panel=new JPanel(Fl);
Upper_Left_Panel.setBorder(new EtchedBorder());
Upper_Left_Panel.setPreferredSize(new Dimension(W/2-2,H/4-2));
Left_Panel.add(Upper_Left_Panel);
Upper_Left_TextArea.setFont(new Font("Times New Roman",0,16));
Upper_Left_TextArea.setBorder(new EtchedBorder());
Upper_Left_TextArea.setPreferredSize(new Dimension(W/2-2-Upper_Left_Button_Panel_W-4,H/4-6));
Upper_Left_Panel.add(Upper_Left_TextArea);
FlowLayout Button_Panel_Fl=new FlowLayout(0,0,66);
JPanel Upper_Left_Button_Panel=new JPanel(Button_Panel_Fl);
Upper_Left_Button_Panel.setBorder(new EtchedBorder());
Upper_Left_Button_Panel.setPreferredSize(new Dimension(Upper_Left_Button_Panel_W,H/4-6));
Upper_Left_Panel.add(Upper_Left_Button_Panel);
JButton Get_Maps_Button=new JButton("Get Maps");
Get_Maps_Button.setForeground(new Color(0,0,230));
Get_Maps_Button.setFont(new Font("Times New Roman",0,16));
Get_Maps_Button.setMargin(An_Inset);
Get_Maps_Button.setPreferredSize(new Dimension(Upper_Left_Button_Panel_W-5,26));
Get_Maps_Button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { Get_Maps(); } });
Upper_Left_Button_Panel.add(Get_Maps_Button);
JButton Print_Button=new JButton("Print");
Print_Button.setForeground(new Color(0,0,230));
Print_Button.setFont(new Font("Times New Roman",0,16));
Print_Button.setMargin(An_Inset);
Print_Button.setPreferredSize(new Dimension(Upper_Left_Button_Panel_W-5,26));
Upper_Left_Button_Panel.add(Print_Button);
JPanel Lower_Left_Panel=new JPanel(Fl);
Lower_Left_Panel.setPreferredSize(new Dimension(W/2-2,H*3/4));
Left_Panel.add(Lower_Left_Panel);
Left_JavaFX_Browser_Panel=new JavaFX_Browser_Panel(W/2-4,H*3/4);
Lower_Left_Panel.add(Left_JavaFX_Browser_Panel);
JPanel Right_Panel=new JPanel(new FlowLayout(0,0,1));
Right_Panel.setBorder(new EtchedBorder());
Right_Panel.setPreferredSize(new Dimension(W/2,H-2));
add(Right_Panel);
JPanel Upper_Right_Outer_Panel=new JPanel(Fl);
Upper_Right_Outer_Panel.setBorder(new EtchedBorder());
Upper_Right_Outer_Panel.setPreferredSize(new Dimension(W/2-4,H/2-4));
Right_Panel.add(Upper_Right_Outer_Panel);
JPanel Upper_Right_Panel=new JPanel(Fl);
Upper_Right_Panel.setPreferredSize(new Dimension(W/2-8,H/2-8));
Upper_Right_Outer_Panel.add(Upper_Right_Panel);
Upper_Right_JavaFX_Browser_Panel=new JavaFX_Browser_Panel(W/2-8,H/2-8);
Upper_Right_Panel.add(Upper_Right_JavaFX_Browser_Panel);
JPanel Lower_Right_Outer_Panel=new JPanel(Fl);
Lower_Right_Outer_Panel.setBorder(new EtchedBorder());
Lower_Right_Outer_Panel.setPreferredSize(new Dimension(W/2-4,H/2-4));
Right_Panel.add(Lower_Right_Outer_Panel);
JPanel Lower_Right_Panel=new JPanel(Fl);
Lower_Right_Panel.setPreferredSize(new Dimension(W/2-8,H/2-8));
Lower_Right_Outer_Panel.add(Lower_Right_Panel);
Lower_Right_JavaFX_Browser_Panel=new JavaFX_Browser_Panel(W/2-8,H/2-8);
Lower_Right_Panel.add(Lower_Right_JavaFX_Browser_Panel);
setPreferredSize(new Dimension(W,H));
Get_Maps();
}
void Get_Maps()
{
Address=Upper_Left_TextArea.getText();
Out(Address);
Url=Google_Url.replace("Address",Address.replace(" ","+"));
Out(Url);
if (Use_iFrame_B)
{
Left_JavaFX_Browser_Panel.Load_iFrame(Url.replace("Zoom","12&output=embed"),785,890);
Upper_Right_JavaFX_Browser_Panel.Load_iFrame(Url.replace("Zoom","16&output=embed"),778,578);
Lower_Right_JavaFX_Browser_Panel.Load_iFrame(Url.replace("Zoom","19&output=embed"),775,575);
}
else
{
Left_JavaFX_Browser_Panel.setURL(Url.replace("Zoom","12")); // This works fine without output=embed in url, but it will show address bar, I want to hide that
Upper_Right_JavaFX_Browser_Panel.setURL(Url.replace("Zoom","16"));
Lower_Right_JavaFX_Browser_Panel.setURL(Url.replace("Zoom","19"));
}
}
public void run()
{
}
public void start()
{
if (Empty_JPanel_Thread==null)
{
Empty_JPanel_Thread=new Thread(this);
Empty_JPanel_Thread.setPriority(Thread.NORM_PRIORITY);
Empty_JPanel_Thread.start();
}
}
public void stop() { if (Empty_JPanel_Thread!=null) Empty_JPanel_Thread=null; }
private static void out(String message) { System.out.print(message); }
private static void Out(String message) { System.out.println(message); }
// Create the GUI and show it. For thread safety, this method should be invoked from the event-dispatching thread.
static void Create_And_Show_GUI()
{
final Map_Maker_2 demo=new Map_Maker_2();
JFrame frame=new JFrame("Map Maker 2");
frame.add(demo);
frame.addWindowListener( new WindowAdapter()
{
public void windowActivated(WindowEvent e) { }
public void windowClosed(WindowEvent e) { }
public void windowClosing(WindowEvent e) { System.exit(0); }
public void windowDeactivated(WindowEvent e) { }
public void windowDeiconified(WindowEvent e) { demo.repaint(); }
public void windowGainedFocus(WindowEvent e) { demo.repaint(); }
public void windowIconified(WindowEvent e) { }
public void windowLostFocus(WindowEvent e) { }
public void windowOpening(WindowEvent e) { demo.repaint(); }
public void windowOpened(WindowEvent e) { }
public void windowResized(WindowEvent e) { demo.repaint(); }
public void windowStateChanged(WindowEvent e) { demo.repaint(); }
});
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args)
{
// Schedule a job for the event-dispatching thread : creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() { public void run() { Create_And_Show_GUI(); } });
}
}
Alright, I found the answer :
Replace the code in JavaFX_Browser_Panel :
if (new File(Url).exists()) setURL(new File(Url));
else eng.loadContent("<iframe width="+W+" height="+H+" src="+Url+" style=border:0; marginheight=0 marginwidth=0 allowfullscreen></iframe>");
With the following :
String Content="<Html>\n"+
"<style>\n"+
" html,body,div,iframe\n"+
" {\n"+
" height: 100%;\n"+
" overflow: hidden;\n"+
" overflow-x: hidden;\n"+
" overflow-y: hidden;\n"+
" margin: 0; padding: 0;\n"+
" }\n"+
"</style>\n"+
"<iframe width="+W+" height="+H+" src="+Url+" style=border:0></iframe>\n"+
"</Html>";
if (new File(Url).exists()) setURL(new File(Url));
else eng.loadContent(Content);