Hello
I try to make some example program showing ads on Android phone, and I try to test it on Emulator of v2.2
Everything in code seems to be fine, but AdListener in debugger says that:
Response message is zero or null;
onFailedToReceiveAd( No ad to show).
Is there any way for it to be my fault? Did anyone encounter same problem?
Heres the code
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.AdTest"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".AdTest"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- AdMobActivity definition -->
<activity android:name="com.google.ads.AdActivity"
android:configChanges="orientation|keyboard|keyboardHidden" />
</application>
<uses-sdk android:minSdkVersion="7"></uses-sdk>
<!-- AdMob SDK requires Internet permission -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Layout xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/main"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
/>
</LinearLayout>
and Activity code
package com.AdTest;
import com.google.ads.*;
import com.google.ads.AdRequest.ErrorCode;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;
public class AdTest extends Activity implements AdListener{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout layout = (LinearLayout)findViewById(R.id.main);
AdView adView = new AdView(this, AdSize.BANNER, "anonymouse");
// Unit ID is correct, I changed it on purpose while pasting here
adView.setAdListener(this);
layout.addView(adView);
AdRequest request= new AdRequest();
adView.loadAd(request);
}
public void onFailedToReceiveAd(AdView adView)
{
Log.d("AdListener", "onFailedToReceiveAd");
}
public void onFailedToReceiveRefreshedAd(AdView adView)
{
Log.d("AdListener", "onFailedToReceiveRefreshedAd");
}
public void onReceiveAd(AdView adView)
{
Log.d("AdListener", "onReceiveAd");
}
public void onReceiveRefreshedAd(AdView adView)
{
Log.d("AdListener", "onReceiveRefreshedAd");
}
#Override
public void onDismissScreen(Ad arg0) {
// TODO Auto-generated method stub
}
#Override
public void onFailedToReceiveAd(Ad arg0, ErrorCode arg1) {
Log.d("AdListener", "onFailedToReceiveAD");
}
#Override
public void onLeaveApplication(Ad arg0) {
// TODO Auto-generated method stub
}
#Override
public void onPresentScreen(Ad arg0) {
// TODO Auto-generated method stub
}
#Override
public void onReceiveAd(Ad arg0) {
Log.d("AdListener", "Received succesfully");
}
}
I have confront the same problem with
onFailedToReceiveAd( No ad to show).
It seems AdMob not sent ad content for our app for some reasons. Even when I in testing mode there's still no ad.
I create my house ad on AdMob to verify my application. It's an easier way in development than testing mode.
I implemented AdListener on my Activity and set it as the AdView listener, then added the following
public void onFailedToReceiveAd(Ad arg0, ErrorCode arg1)
{
Log.d("AdMob", "Failed to receive an Ad. Requesting a new one..." + arg1);
arg0.stopLoading();
arg0.loadAd(new AdRequest());
}
I had the same problem too. So I changed the code to set the test mode true, then the Admob test ad started to show on the emulator. Try this in your OnCreate() method:
LinearLayout layout = (LinearLayout)findViewById(R.id.main);
AdView adView = new AdView(this, AdSize.BANNER, "anonymouse");
// Unit ID is correct, I changed it on purpose while pasting here
adView.setAdListener(this);
AdRequest request = new AdRequest();
request.setTesting(true);
adView.loadAd(request);
If you run this on a real device and still no ad to show, then I guess it might have something to do with Admob fill rate.
Change the test mode to true. Note that ads will not be displayed until at least 3 access attempts are made for the day.
It appears that the latest admob SDK 4.0.4 doesn't display ads on 1.5 devices.
In the emulator it works fine for 1.6+, but not 1.5.
I think its from the new cross-over advertising with AdSense. As far as I can tell the SDK now wraps a webview as the visual component of the view so it can publish the different kinds of ads. A close look at the log shows WebView.multitouch enabled - as 1.5 doesn't support multitouch (for us developers in Java) due to Apple throwing its toys out of the pram and having a dummyspit (I understand they believe only they are allowed to use two fingers at once..) and perhaps enabling multitouch on the webview causes an internal exception and the view never gets created, and thus cannot receive the HTML reply from the admob http server.
Also see this link
1/ get the latest SDK version
2/ try admob demo with your publisher id
3/ try it in test mode (this should work always)
4/ try to add some sample house ads (shown when there is no other ad available)
5/ try to change your keywords
In general, admob prints detailed error to log (ID missing, activity missing in manifest etc).
I had done the admob integration and that is run on device as well as on emulator.
so, please try below code:
I think you have to remove textview from main.xml
and also try this:
1) Create new app on in your admob a/c
2) then simply replace the id of previous app by new one
try it bro.
I also get this problem. You can try to customized the request, before loading. Like this:
AdRequest re = new AdRequest();
//re.setTesting(true);
re.setGender(AdRequest.Gender.FEMALE);
adview.loadAd(re);
I put my example, apk file and source code here, you can try:
Add Google Admob in Android Application
Related
Ad serving on your account is currently being limited due to invalid traffic concerns. We’ll automatically review and update this limit as we continue to monitor your traffic.
It's been 8 months now the limit is still there and of course, there is no way to contact the AdMob team. It all started when I ran a google ads install campaign for one of my apps and I got a very high volume of installs and thus high impression and earnings from the app, then boom I got a limit on my account. I have paused the campaign and deleted all the ad unit id for all my apps and after 7 days the warning goes away but when I create a new ad unit and I get as little as 10 requests and 2 impressions the limit comes back. I have done that several times but it's Limit still comes and goes. I don't know what to do anymore please I need your help. Below is how I show Admob ads via firebase in my app.
private InterstitialAd mInterstitialAd;
//innitiatizing the ads
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("ca-app-pub-1137773547201239/7187777199");
mInterstitialAd.loadAd(new AdRequest.Builder().build());//loading the ads
if (mInterstitialAd.isLoaded()) {
final ProgressDialog dialog=new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading...");
dialog.setCancelable(false);
dialog.setInverseBackgroundForced(false);
dialog.show();
Handler handler = new Handler();
Runnable r = new Runnable() {
public void run() {
dialog.dismiss();
mInterstitialAd.show();
}
};
handler.postDelayed(r, 2000);
}
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
// Code to be executed when an ad finishes loading.
}
#Override
public void onAdFailedToLoad(LoadAdError adError) {
// Code to be executed when an ad request fails.
}
#Override
public void onAdOpened() {
// Code to be executed when the ad is displayed.
}
#Override
public void onAdClicked() {
// Code to be executed when the user clicks on an ad.
}
#Override
public void onAdLeftApplication() {
// Code to be executed when the user has left the app.
}
#Override
public void onAdClosed() {
// Code to be executed when the interstitial ad is closed.
mInterstitialAd.loadAd(new AdRequest.Builder().build());//Reloading the ads
}
});
}
This is the code and permissions in my manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="com.android.vending.BILLING"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="ca-app-pub-1132553547777239~2704777871"/>
I am trying to get an instance of a SeekBar using the findViewById() and attaching a listener to it.
The code looks like this:
SeekBar seek_bar = findViewById(R.id.audio_volume);
seek_bar.setOnSeekBarChangeListener(listener);
And the listener:
private SeekBar.OnSeekBarChangeListener listener = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
log.d("YO HERE");
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
};
Followed this SO post, and invoked the findViewById inside the onCreate method after these two lines:
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
But the problem persists. I am still getting:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.SeekBar.setOnSeekBarChangeListener(android.widget.SeekBar$OnSeekBarChangeListener)' on a null object reference
And the app fails to open. How can I solve this issue? Also it would be very helpful if the process of debugging a null object reference error is shared.
Layout xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<ListPreference
android:key="PREF_MIN_REC"
android:title="#string/min_rec"
android:summary="#string/min_rec_desc"
android:entries="#array/min_rec_options"
android:entryValues="#array/min_rec_values"
android:dialogTitle="#string/min_rec"
android:defaultValue="15"
/>
<ListPreference
android:key="PREF_AUDIO_SOURCE"
android:title="#string/audio_source"
android:summary="#string/audio_source_desc"
android:entries="#array/audio_source_options"
android:entryValues="#array/audio_source_values"
android:dialogTitle="#string/audio_source"
android:defaultValue="4"
/>
<ListPreference
android:key="PREF_AUDIO_FORMAT"
android:title="#string/audio_format"
android:summary="#string/audio_format_desc"
android:entries="#array/audio_format_options"
android:entryValues="#array/audio_format_values"
android:dialogTitle="#string/audio_format"
android:defaultValue="1"
/>
<org.anasthase.androidseekbarpreference.SeekBarPreference
android:id="#+id/volume"
android:key="PREF_MIC_VOLUME"
android:title="#string/mic_volume"
android:summary="#string/mic_volume_desc"
app:maxValue="100"
app:minValue="1"
app:stepValue="1"
android:defaultValue="20"
app:format="%.1f"
app:displayDividerValue="5"/>
<org.anasthase.androidseekbarpreference.SeekBarPreference
android:id="#+id/audio_volume"
android:key="PREF_AUDIO_VOLUME"
android:title="#string/audio_volume"
android:summary="#string/audio_volume_desc"
app:maxValue="100"
app:minValue="1"
app:stepValue="1"
android:defaultValue="20"
app:format="%.1f"
app:displayDividerValue="5"/>
<EditTextPreference
android:key="PREF_URL_SUBDOMAIN"
android:title="#string/server_subdomain"
android:summary="#string/server_subdomain_desc"
android:dialogTitle="#string/server_subdomain"
android:defaultValue=".telforce.biz"
/>
<ListPreference
android:key="PREF_UPLOAD_NETWORK"
android:title="#string/upload_network"
android:summary="#string/upload_network_desc"
android:entries="#array/upload_network_options"
android:entryValues="#array/upload_network_values"
android:dialogTitle="#string/upload_network"
android:defaultValue="1"
/>
<CheckBoxPreference
android:key="save_term_enable_key"
android:title="#string/save_term_check_title"
android:summary="#string/save_term_check_summary"/>
<EditTextPreference
android:key="save_term_key"
android:title="#string/save_term_title"
android:summary="#string/save_term_summary"
android:dependency="save_term_enable_key"
android:defaultValue="#string/save_term_default_value"
android:dialogTitle="#string/save_term_dialog"/>
</PreferenceScreen>
In your XML your audio_volume view belongs to class
org.anasthase.androidseekbarpreference.SeekBarPreference
In your Java code, it is SeekBar only, so if it is not crashing, I assume Seekbar extends SeekBarPreference.
Ignore the casting comments and responses since it's not needed since last year if you're using the latest versions of java, android sdk and target api.
The null pointer exception means the seekbar was not found on the layout. Check if you have more than 1 xml with the same name (for different screen resolutions).
do this way if its preference fragment:
SeekBarPreference skp = (SeekBarPreference) findPreference("PREF_AUDIO_VOLUME");
Cheers ;)
I found few topics describing similar problems, but not found a solution for memory leaks being created by pretty simple Android app:
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cz.reloecc.testBackground"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="10"/>
<application android:label="#string/app_name"
android:icon="#drawable/ic_launcher">
<activity android:name="TestBackgroundActivity"
android:theme="#android:style/Theme.Black.NoTitleBar.Fullscreen"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/ui">
</LinearLayout>
TestBackgroundActivity.java:
public class TestBackgroundActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
While changing an orientation of my device (nvidia Tegra Note 7) logcat is noting:
cz.reloecc.testBackground I/dalvikvm-heap﹕ Grow heap (frag case) to 35.625MB for 12904976-byte allocation
with roughly 13MB addition on every turnaround (for biggest version of image)
up to my heap max (64MB):
cz.reloecc.testBackground E/dalvikvm-heap﹕ Out of memory on a 12904976-byte allocation.
cz.reloecc.testBackground I/dalvikvm﹕ at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
..
cz.reloecc.testBackground I/dalvikvm﹕ at cz.reloecc.testBackground.TestBackgroundActivity.onCreate(TestBackgroundActivity.java:13)
BUT!
problem does not persist when I delete ui.png (which is set as background) from drawable-land-[x|m|l]dpi OR drawable-[x|m|l]dpi folder in res folder..
so if I have only one version of background image, I can turn device for a long week..
And here is my question: How to handle multiple versions of drawables (set as background) to avoid memory leaks?
//EDIT: I managed few tries of disposing, recycling, destroying, nulling resources or their holders, the last one is based on Aeshang's suggestion:
=== version 2.0 ===
Resources.java:
public class Resources {
public Resources(Context context){
this.context = context;
}
public Drawable getImage(int id){
if(images.indexOfKey(id) < 0){
Drawable drawable = context.getResources().getDrawable(id);
images.put(id, drawable);
}
return images.get(id);
}
public void disposeImages(){
int key;
for(int i = 0; i < images.size(); i++) {
key = images.keyAt(i);
Drawable drawable = images.get(key);
if(drawable instanceof BitmapDrawable){
if(drawable instanceof BitmapDrawable){
Log.i(TestBackgroundActivity.LOG_TAG, "Recycling image " + key);
((BitmapDrawable)drawable).getBitmap().recycle();
}
}
}
}
public void disposeAll(){
disposeImages();
images.clear();
}
private SparseArray<Drawable> images = new SparseArray<Drawable>();
private Context context;
}
TestBackgroundActivity.java:
public class TestBackgroundActivity extends Activity {
public static String LOG_TAG = "[TestBG]";
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
resources = new Resources(getApplicationContext());
LinearLayout mainLayout = (LinearLayout)findViewById(R.id.mainLayout);
mainLayout.setBackgroundDrawable(resources.getImage(R.drawable.ui));
}
#Override
protected void onDestroy(){
resources.disposeAll();
super.onDestroy();
}
private Resources resources;
}
Use third party libraries to load the drawables
like Picasso or Universal Image Loader
They will automatically handle large bitmaps
And coming to drawables
User 1920X1080 resolution images and put them drawable-xxhdpi folder every thing works fine
Ok,
this should definitely work. Tested in on two other devices, and altrough app is complaining about high memory heap grow. It is gc'ing right after.
My tegra note 7 is THE pain. I will have to find out the right source of this hell.
//edit:
fine, calling
System.gc();
in onDestroy() of MainActivity
and app lasts forever.. who knows why?
I'm kind of a noob android developer, and I hit a few bumps while trying to create a button that opens a new layout. While I was doing that, I got a few errors that would not go away no matter what I tried. In response, I copied most of the xml files and java files that I had changed from the original structure, and I added them to a new project, thinking all my errors would go away. I really need some help, I can't tell you how long I have been stuck on this small error. I have attached the main FullScreenActivity.java, activity_main.xml, the Android Manifest, and the error messages. Thank you in advance for the help guys, I really do appreciate it! c:
FullScreenActivity.java ~
package sehej.android.doge;
import sehej.android.doge.util.SystemUiHider;
import sehej.android.doge.R;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
public class FullscreenActivity extends Activity {
/**
* Whether or not the system UI should be auto-hidden after
* {#link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
*/
private static final boolean AUTO_HIDE = true;
/**
* If {#link #AUTO_HIDE} is set, the number of milliseconds to wait after
* user interaction before hiding the system UI.
*/
private static final int AUTO_HIDE_DELAY_MILLIS = 3000;
/**
* If set, will toggle the system UI visibility upon interaction. Otherwise,
* will show the system UI visibility upon interaction.
*/
private static final boolean TOGGLE_ON_CLICK = true;
/**
* The flags to pass to {#link SystemUiHider#getInstance}.
*/
private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION;
/**
* The instance of the {#link SystemUiHider} for this activity.
*/
private SystemUiHider mSystemUiHider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
**** final View controlsView = findViewById(R.id.fullscreen_content_controls);
**** final View contentView = findViewById(R.id.fullscreen_content);
// Set up an instance of SystemUiHider to control the system UI for
// this activity.
mSystemUiHider = SystemUiHider.getInstance(this, contentView,
HIDER_FLAGS);
mSystemUiHider.setup();
mSystemUiHider
.setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() {
// Cached values.
int mControlsHeight;
int mShortAnimTime;
#Override
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
public void onVisibilityChange(boolean visible) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
// If the ViewPropertyAnimator API is available
// (Honeycomb MR2 and later), use it to animate the
// in-layout UI controls at the bottom of the
// screen.
if (mControlsHeight == 0) {
mControlsHeight = controlsView.getHeight();
}
if (mShortAnimTime == 0) {
mShortAnimTime = getResources().getInteger(
android.R.integer.config_shortAnimTime);
}
controlsView
.animate()
.translationY(visible ? 0 : mControlsHeight)
.setDuration(mShortAnimTime);
} else {
// If the ViewPropertyAnimator APIs aren't
// available, simply show or hide the in-layout UI
// controls.
controlsView.setVisibility(visible ? View.VISIBLE
: View.GONE);
}
if (visible && AUTO_HIDE) {
// Schedule a hide().
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
}
});
// Set up the user interaction to manually show or hide the system UI.
contentView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (TOGGLE_ON_CLICK) {
mSystemUiHider.toggle();
} else {
mSystemUiHider.show();
}
}
});
};
// Upon interacting with UI controls, delay any scheduled hide()
// operations to prevent the jarring behavior of controls going away
// while interacting with the UI.
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Trigger the initial hide() shortly after the activity has been
// created, to briefly hint to the user that UI controls
// are available.
delayedHide(100);
}
/**
* Touch listener to use for in-layout UI controls to delay hiding the
* system UI. This is to prevent the jarring behavior of controls going away
* while interacting with activity UI.
*/
View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (AUTO_HIDE) {
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
return false;
}
};
Handler mHideHandler = new Handler();
Runnable mHideRunnable = new Runnable() {
#Override
public void run() {
mSystemUiHider.hide();
}
};
/**
* Schedules a call to hide() in [delay] milliseconds, canceling any
* previously scheduled calls.
*/
private void delayedHide(int delayMillis) {
mHideHandler.removeCallbacks(mHideRunnable);
mHideHandler.postDelayed(mHideRunnable, delayMillis);
}
}
activity_main.xml ~
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/grass"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:padding="20sp"
app:textAlignment="center"
tools:context=".MainActivity" >
<requestFocus
app:layout_width="wrap_content"
app:layout_height="wrap_content" />
<Button
app:id="#+id/button2"
style="#style/ButtonBar"
app:layout_width="150dp"
app:layout_height="wrap_content"
app:layout_below="#+id/button1"
app:layout_centerHorizontal="true"
app:layout_marginTop="65dp"
app:text="#string/button2"
app:typeface="sans" />
<Button
app:id="#+id/button3"
style="#style/ButtonBar"
app:layout_width="150dp"
app:layout_height="wrap_content"
app:layout_alignLeft="#+id/button1"
app:layout_below="#+id/button2"
app:layout_marginTop="65dp"
app:text="#string/button3"
app:typeface="sans" />
<Button
app:id="#+id/button1"
style="#style/ButtonBar"
app:layout_width="150dp"
app:layout_height="wrap_content"
app:layout_alignLeft="#+id/button2"
app:layout_below="#+id/textView1"
app:layout_marginTop="22dp"
app:onClick="whenClicked"
app:text="#string/button1"
app:typeface="sans" />
<TextView
app:id="#+id/textView1"
app:layout_width="wrap_content"
app:layout_height="wrap_content"
app:layout_alignParentTop="true"
app:layout_centerHorizontal="true"
app:layout_marginTop="39dp"
app:paddingBottom="30sp"
app:text="#string/title"
app:textColor="#color/blue"
app:textSize="60sp"
app:textStyle="bold"
app:typeface="sans" />
Android Manifest ~
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="sehej.android.doge"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="sehej.android.doge.FullscreenActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="#string/app_name"
android:theme="#style/FullscreenTheme" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Error messages from problems view ~
fullscreen_content_controls cannot be resolved or is not a field FullscreenActivity.java /???/src/sehej/android/doge
line 54 Java Problem
fullscreen_content cannot be resolved or is not a field FullscreenActivity.java /???/src/sehej/android/doge
line 55 Java Problem
~~~~??? is the project/application name
~~~~I have marked the section that received the errors with '***'s
You have not defined
fullscreen_content_controls
fullscreen_content
The above id in your activity_main.xml Thats why you are getting
fullscreen_content_controls cannot be resolved or is not a field FullscreenActivity.java .
As looking at your code you have not declare any View with the id
fullscreen_content_controls
fullscreen_content in your activity_main.xml.
If you want to get rid of this problem you have to define two Views with the id you are mentioning in your code.
Edit
you will usually call setContentView(int) with a layout resource defining your UI, and using findViewById(int) to retrieve the widgets in that UI So whatever view you have declared in your Ui Xml you can get those.
Like in your case you have defined button so something like
Button someButton = (Button) findViewById(R.id.button2);
will work for you now you can use this widget in your application.
This is what I did to solve this problem I faced. It happens when you press ctrl+shift+O to auto import.
the solution is to
Replace import android.R with .R in your activity java file.
Here is my problem. I setup the buttons exactly the way they are setup in the Android documentation, but I am getting a warning, and the button will not do anything.
Here is my Java code:
package com.variDice;
import android.app.Activity;
import android.os.Bundle;
import android.widget.*;
public class VariDiceActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//die1Clicked();
}
private void die1Clicked() {
ImageButton die1button = (ImageButton)findViewById(R.id.die1button);
die1button.setImageResource(R.drawable.icon);
}
}
...and the XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="1" android:layout_gravity="center_horizontal">
<ImageView
android:id="#+id/varidice_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:src="#drawable/icon"></ImageView>
<ImageButton
android:id="#+id/die1button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:background="#null"></ImageButton>
</LinearLayout>
...and the warning:
The method die1Clicked from the type VariDiceActivity is never used locally.
I must say that I am completely new to Android development. I made my app for the iPhone, and I am now trying to make a version for the android. The iPhone version was sooo much easier, because of the better interface builder (so I can just make an action and connect it to the button that way), so this is almost impossibly hard for me to understand. In other words, I do not understand how you connect an action to the button. Could somebody please tell me what I am doing wrong?
Try this in your xml:
<ImageButton
android:id="#+id/die1button"
android:onClick="die1Clicked"
...></ImageButton>
And in your code, change the method signature to:
public void die1Clicked(android.view.View v) {
ImageButton die1button = (ImageButton)findViewById(R.id.die1button);
die1button.setImageResource(R.drawable.icon);
}
Here is the Android Button tutorial.
To bind some behavior to an UI button, you need to register a listener that receives notifications of a certain event type. In your case, you register a OnClickListener (for the click event); just like in the following snippet:
// create the implementation of OnClickListener
private OnClickListener mDie1Listener = new OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
}
};
protected void onCreate(Bundle savedValues) {
...
// get the button from layout
Button button = (Button)findViewById(R.id.die1button);
// register the onClick listener with the implementation above
button.setOnClickListener(mDie1Listener);
...
}
You need to add a click listener to your button. Put this in your onCreate():
ImageButton die1button = (ImageButton)findViewById(R.id.die1button);
die1button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// What to do when the button is clicked
});
Most answers on SO tend to use 'setOnClickListener' instead of using xml properties.
I personally prefer using xml for making items clickable in android.
The mistake you have made is setting your function as private. The function which gets called after clicking the item should be public.
There are 3 things you should keep in mind:
Define the 2 properties in xml.
android:clickable="true"
android:onClick="functionName"
Define that function in the Activity file. Make sure to keep the function public.
public void functionName(View v) {
// TODO Auto-generated method stub
}
Make sure to pass 'View v' as an argument for that function.