So I am trying to get ads to work for my first Android ap, I am following the Google developers tutorial found here: https://developers.google.com/mobile-ads-sdk/docs/admob/fundamentals
Thus my code looks like what it looks like in the example:
package com.google.example.gms.ads.banner;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
/**
* A simple {#link Activity} that embeds an AdView.
*/
public class BannerSample extends Activity {
/** The view to show the ad. */
private AdView adView;
/* Your ad unit id. Replace with your actual ad unit id. */
private static final String AD_UNIT_ID = "TO_BE_DISCOVERED_SHORTLY";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create an ad.
adView = new AdView(this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId(AD_UNIT_ID);
// Add the AdView to the view hierarchy. The view will have no size
// until the ad is loaded.
LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout);
layout.addView(adView);
// Create an ad request. Check logcat output for the hashed device ID to
// get test ads on a physical device.
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice("INSERT_YOUR_HASHED_DEVICE_ID_HERE")
.build();
// Start loading the ad in the background.
adView.loadAd(adRequest);
}
#Override
public void onResume() {
super.onResume();
if (adView != null) {
adView.resume();
}
}
#Override
public void onPause() {
if (adView != null) {
adView.pause();
}
super.onPause();
}
/** Called before the activity is destroyed. */
#Override
public void onDestroy() {
// Destroy the AdView.
if (adView != null) {
adView.destroy();
}
super.onDestroy();
}
}
However, when I compile this I get the following errors:
BannerSample.java:25: error: package R does not exist
setContentView(R.layout.activity_main);
^
BannerSample.java:34: error: package R does not exist
LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout);
^
2 errors
I suspect the solution to my answers may be incredibly simple, but I'm not sure where these Rs are suppose to come from and the tutorial doesn't say anything about it. Help?
I am compiling using this javac command:
javac -cp ".;android.jar;google-play-services.jar" BannerSample.java
Every time you compile your Android project (if you are working on eclipse at least) the R package gets deleted and then gets rebuild. This error is pretty common and it means that you have an error in your code that stopped the building process and so also the creation of the R package.
If it worked before then try identifying at which time did it stop working and analyze the code that caused it not to compile so to find the error. Normally the error is in the XML layout file that prevented the application from being built
It may be that your problem is caused by a different reason, but in every case that that I've seen that this problem is present, the cause is always a compilation error.
Happy hunting :)
edit:
Check out this answer, it may contain just the info you need
Related
I was running project OnmiNotes on Github when I ran, and looking at Logcat, the result was an error: "Tried to access UI constants from a non-visual Context", I found out that this is a new error on android 11, and there are quite a few suggestions to correct this error on gg, I look at them, those cases are not suitable for my case. And the person who wrote this app wrote on android 8, so they probably didn't know this error. Below are the code lines I find relevant.
There is an error in Logcat:
Tried to access UI constants from a non-visual
Context:it.feio.android.omninotes.OmniNotes#e9ea0eUI constants, such as
display metrics or window metrics, must be accessed from Activity or
other visual Context. Use an Activity or a Context created with
Context#createWindowContext(int, Bundle), which are adjusted to the
configuration and visual bounds of an area on screen
and:
Tried to access visual service WindowManager from a non-visual Context:it.feio.android.omninotes.OmniNotes#e9ea0e Visual services, such as WindowManager, WallpaperService or LayoutInflater should be accessed from Activity or other visual Context. Use an Activity or a Context created with Context#createWindowContext(int, Bundle), which are adjusted to the configuration and visual bounds of an area on screen.
And there are two command lines I see mentioned in logcat error
1.In BaseActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
// Forces menu overflow icon
try {
ViewConfiguration config = ViewConfiguration.get(this.getApplicationContext()); //ERROR IN LOGCAT IN THIS LINE
#SuppressLint("SoonBlockedPrivateApi") Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
if (menuKeyField != null) {
menuKeyField.setAccessible(true);
menuKeyField.setBoolean(config, false);
}
} catch (Exception e) {
LogDelegate.w("Just a little issue in physical menu button management", e);
}
super.onCreate(savedInstanceState);
}
MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);//ERROR IN LOGCAT IN THIS LINE
setTheme(R.style.OmniNotesTheme_ApiSpec);
binding = ActivityMainBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
EventBus.getDefault().register(this);
Prefs.getPreferences().registerOnSharedPreferenceChangeListener(this);
initUI();
if (IntroActivity.mustRun()) {
startActivity(new Intent(getApplicationContext(), IntroActivity.class));
}
}
Does anyone know how to deal with it? Any help will be appreciated.
Replace this.getApplicationContext() and getApplicationContext() with this. this appears to be an Activity in both places.
I am trying to make carousel with clickable images, made as a list. I want to make so using SetOnItemCLickListener, but when I try to rebuild the project an error pops up and tells me:
error: cannot find symbol method setOnItemClickListener(<anonymous OnItemClickListener>)
I searched the internet for a solution but I am still stuck.
I have tried so far:
Clean the project (obvious);
Searched for name illegal elements, there are none;
When I tried only with SetOnCLickListener it did not work; it is in red-colored letters and there is no method like this.
public class FinalSadMovies extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_final_sad_movies);
List<CarouselPicker.PickerItem> imageItems = new ArrayList<>();
imageItems.add(new CarouselPicker.DrawableItem(R.drawable.joker));
imageItems.add(new CarouselPicker.DrawableItem(R.drawable.starwars_resized));
imageItems.add(new CarouselPicker.DrawableItem(R.drawable.test));
CarouselPicker.CarouselViewAdapter imageAdapter = new CarouselPicker.CarouselViewAdapter(this, imageItems, 0);
carouselPicker.setAdapter(imageAdapter);
carouselPicker.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("MainActivity", "ListView item clicked.");
}
});
If you're using carouselPicker from GoodieBag then setOnItemClickListener is not supported.
The only thing you can rely on is the addOnPageChangeListener but this requires you to change your app UI and flow (because you need to use a button to confirm the selection).
Another option is to create a custom CarouselViewAdapter class where you can handle the click event on the instantiateItem method.
I'm fairly new to Android, and Javascript. But, I'm actively learning by watching tutorials, and asking questions. Now, I'm trying to code an app that changes certain system values. I know this can only be done by granting my app the WRITE_SECURE_SETTINGS permission. Through my research I've realized I cannot declare the permission in the manifest file itself. Obviously, the only respectable answer is to check if the permission has been granted by the user through ADB. I can't find anything related to this topic and I'm hoping you guys can help me come to a conclusion on how to properly do this. So far this is the code that I have.
package com.datastream.settingschanger;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String requiredPermission = "android.permission.WRITE_SECURE_SETTINGS";
int checkVal = getContext().checkCallingOrSelfPermission(requiredPermission);
if (checkVal == PackageManager.PERMISSION_GRANTED) {
}
Toast.makeText(getActivity(), "WRITE_SECURE_SETTINGS has been granted to the application. You may now continue!",
Toast.LENGTH_LONG).show();
if (checkVal == PackageManager.PERMISSION_DENIED) {
}
Toast.makeText(getActivity(), "WRITE_SECURE_SETTINGS has not been granted to the application. Please grant access to continue.",
Toast.LENGTH_LONG).show();
}
}
But, when ever I run this in Android Studio I get the following errors:
error: cannot find symbol method getContext()
error: cannot find symbol method getActivity()
error: cannot find symbol method getActivity()
Can anyone help me resolves these errors? I have no clue how to fix this. Thank you!
The getContext() and getActivity() method is used in Fragment to get Context
Remove getContext() and getActivity() And use this and MainActivity.this to get Context in your activity
Use this
int checkVal = checkCallingOrSelfPermission(requiredPermission);
instead of this
int checkVal = getContext().checkCallingOrSelfPermission(requiredPermission);
SAMPLE CODE
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String requiredPermission = "android.permission.WRITE_SECURE_SETTINGS";
int checkVal = checkCallingOrSelfPermission(requiredPermission);
if (checkVal == PackageManager.PERMISSION_GRANTED) {
}
Toast.makeText(this, "WRITE_SECURE_SETTINGS has been granted to the application. You may now continue!",
Toast.LENGTH_LONG).show();
if (checkVal == PackageManager.PERMISSION_DENIED) {
}
Toast.makeText(this, "WRITE_SECURE_SETTINGS has not been granted to the application. Please grant access to continue.",
Toast.LENGTH_LONG).show();
}
}
I make a game with Java and LibGdx
It's a game of skill with a time limit, and the problem is the player can push home button to pause app, and go to task manager, and can see preview of app to seek what he has to find without counting time
So, I would like to hide the preview of the app when the player push home button to pause
What I tried to do
I override pause and resume handler
#Override
public void pause() {
Gdx.app.log("LibGDX", "pause");
state = State.PAUSE;
Gdx.graphics.setContinuousRendering(false);
Gdx.graphics.requestRendering();
}
#Override
public void resume() {
Gdx.app.log("LibGDX", "resume");
state = State.RUN;
Gdx.graphics.setContinuousRendering(true);
}
and main part of my public void render(float) function
switch (state)
{
case RUN:
// game
break;
case PAUSE:
// a black rectangle on screen
shapeRenderer.setProjectionMatrix(camera.combined);
shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);
shapeRenderer.setColor(Color.BLACK);
shapeRenderer.rect(0, 0, GameScreen.WIDTH, GameScreen.HEIGHT);
shapeRenderer.end();
break;
default:
break;
}
log tell me that pause and resume are indeed invoked
but in task manager, I still see the game and not the black rectangle
Update 1
to Ridcully answer :
I tried what you suggested
package com.mygdx.game;
import android.os.Bundle;
import android.view.WindowManager;
import com.badlogic.gdx.backends.android.AndroidApplication;
import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration;
public class AndroidLauncher extends AndroidApplication {
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
// --
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
// --
initialize(new MyGame(), config);
}
}
But same thing, I still see the screenshot
I'm with Android Studio 2.1
My smartphone: Oneplus One
and Android 6.0.1
Do you have an idea ? thanks
There is a flag for that. You can use this little method, e.g. in onCreate() to prevent Android from creating a 'screenshot' for the 'recent activities' list. You can activate/deactivate as you want, e.g. only activate it when the actual game board is visible etc.
/**
* Sets/clears FLAG_SECURE which prevents system from creating screenshots for 'recent activities' list.
* Flag should be set while user is in vault.
*
* #param set
*/
protected void setWindowFlagSecure(boolean set) {
if (set) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE);
}
EDIT
I just found this SO answer, regarding Libgdx applications: Seems you have to set the flag AFTER invoking the initialize() method.
You can do that using
public class SampleActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE,
WindowManager.LayoutParams.FLAG_SECURE);
setContentView(R.layout.main);
}
}
Make sure you do that before you call setContentView.
I've been following this tutorial (http://www.kilobolt.com/day-7-creating-an-android-game-from-start-to-finish.html) for creating an Android game. Now I would like to add AdMob ads to the game in GameScreen Class inside private void drawGameOverUI() {...}.
I got the context from SampleGame Class using
private static Context context;
public Screen getInitScreen() {
SampleGame.context = getApplicationContext();
...
}
public static Context getAppContext() {
return SampleGame.context;
}
In GameScreen Class inside private void drawGameOverUI() I have this
contextGameScreen = SampleGame.getAppContext();
LinearLayout layout = new LinearLayout(contextGameScreen);
adView = new AdView(contextGameScreen, AdSize.BANNER, "...");
layout.addView(adView);
adView.loadAd(new AdRequest());
but I got this error "Cannot resolve constructor 'AdView(android.content.Context, com.google.ads.AdSize, java.lang.String)'" for (contextGameScreen, AdSize.BANNER, "...");.
On Google Developers (https://developers.google.com/mobile-ads-sdk/docs/admob/fundamentals#android) they use 'this', but when I use (this, AdSize.BANNER, "..."); I got the error "Cannot resolve constructor 'AdView(com.name.GameScreen, com.google.ads.AdSize, java.lang.String)'".
Can you please help me with this, how to solve this error, and to get this to work? This means alot to me. And also what exactly is 'this'?
Your problem is that contextGameScreen in
new AdView(contextGameScreen, AdSize.BANNER, "...")
is not an instance of android.content.Context. Eg an Activity or an Application.
It is very hard to work out exactly what you are doing as you have only provided disconnected scraps of code, but what you need to do is to provide the AdView constructor the Activity in which in will be embedded.