Null object reference error on findViewById() even when invoked after setContentView() - java

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 ;)

Related

NullPointerException: Attempt to invoke virtual method 'void android.widget.CheckBox.setOnClickListener on a null object reference, ONLY on tablets [duplicate]

This question already has answers here:
Null pointer Exception - findViewById()
(12 answers)
Closed 6 years ago.
I saw many similar questions online, and tried several solutions. But none fixed my issue. One important thing I want to mention is that, my code works well on android Phones, it only crashes on android Tablets. I have no idea what's going on.
This is the stack:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.xxxx.xxxx.android/com.xxxx.xxxx.android.LoginScreenActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.CheckBox.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2808)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2873)
at android.app.ActivityThread.access$900(ActivityThread.java:181)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1482)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6145)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.CheckBox.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.xxxx.xxxx.android.LoginScreenActivity.onCreate(LoginScreenActivity.java:89)
at android.app.Activity.performCreate(Activity.java:6374)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2752)
... 10 more
This is the LoginScreenActivity:
public class LoginScreenActivity extends Activity implements OnClickListener
{
private Context context;
private CheckBox showPassword;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.login_screen);
context = getApplicationContext();
showPassword = (CheckBox)findViewById(R.id.checkbox_show_password);
//below is line 89 of LoginScreenActivity, exception happened here.
showPassword.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View view)
{
//.................
}
});
}
}
Here's the xml file:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<CheckBox
android:id="#+id/checkbox_show_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Show Password"/>
</RelativeLayout>
</ScrollView>
There are two problems that are apparent.
The obvious: NullPointerException
The solution: All instances of login_screen.xml will need a Checkbox with android:id="#+id/checkbox_show_password" in order for findViewById(R.id.checkbox_show_password) to not return null.
This is worth mentioning because in the comments it was stated that there are multiple res/layout-* folders and the error only happens on tablets, so that is important.
Second problem:
While any View can use an OnClickListener, you have a CheckBox, not a Button, so you'll probably want to know when the checkbox was checked, not just clicked.
In that case, use an OnCheckedChangeListener
showPassword.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked){
// do something
}else {
//do something else
}
}
});
Well with a checkbox you cannot have an onClickListener. Please remove the Interface (implements) also. You may want to try this:
showPassword.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (showPassword.isChecked()){
//do something
}else {
//do something else
}
}
});
Hope it helps!!!

Android Wear append to textView crashes app

So i have a strange issue when trying to retrieve a list of sensors on my application.
Printing to the log works just fine.
When I try to append to a textView, it crashes.
Here is where I am doing the attempted appending:
protected void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.activity_main);
sensorTextView = (TextView) findViewById(R.id.sensorList);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
initialiseAccelerometer();
sensorManager=(SensorManager) getSystemService(SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
for (Sensor sensor : sensors) {
Log.d("Sensors", "" + sensor.getName());
sensorTextView.append(sensor.getName());
}
sensorManager.registerListener(
this,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
mGestureDetector = new GestureDetectorCompat(this, new LongPressListener());
}
And subsequent error:
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.XXXXXX.XXXXXXXXXXX.MainActivity}:
java.lang.NullPointerException:
Attempt to invoke virtual method
'void android.widget.TextView.append(java.lang.CharSequence)' on a null object reference
And the XML file with correct id:
android:id="#+id/sensorList"
Can anyone point me in the right direction or advise me as to what I'm doing wrong?
activity_main.xml:
<android.support.wearable.view.WatchViewStub
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/watch_view_stub"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:rectLayout="#layout/rect_activity_main"
app:roundLayout="#layout/round_activity_main"
tools:context=".MainActivity"
tools:deviceIds="wear"></android.support.wearable.view.WatchViewStub>
Thanks,
Emmett
This section of the documentation notes some quirks of WatchViewStub. In particular, note the following:
The layouts that you specify for square or round screens are not inflated until WatchViewStub detects the shape of the screen, so your app cannot access their views immediately. To access these views, set a listener in your activity to be notified when the shape-specific layout has been inflated
You are probably trying to set the TextView reference too early, which is why it's null at the point you attempt to append text. If you instead use an OnLayoutInflatedListener as in the sample code below (also from the documentation) to wait until the appropriate round/square layout is inflated, you should find that the reference is initialized properly for both screen types:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wear);
WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
#Override public void onLayoutInflated(WatchViewStub stub) {
// Now you can access your views
TextView tv = (TextView) stub.findViewById(R.id.text);
...
}
});
}
[Note that a colleague of mine has indicated that there is currently a bug that requires you to define the square layout xml attribute and the round layout xml attribute in a specific order for this to work - I don't remember offhand which needs to be first, just a heads-up if you run into problems].

if() in a Settings Activity

I'm a Android-Beginner and want to make a if-question in my settings/preferences-Activity.
Here is my Preferences.java:
package net.dominik.genpush;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class Preferences extends PreferenceActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs);
}
}
...and my Prefs.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:key="pushCheckBox"
android:title="#string/pushnachr_headline"
android:summary="#string/pushnachr_explain"
android:defaultValue="true">
</CheckBoxPreference>
</PreferenceScreen>
Now I wanted to make something like
public void onCheckboxPush(View b)
{
if (pushCheckBox.isChecked())
{
//CODE
}
else...
but don't know how I can start the methode when the checkbox changes.
In a other way I could use
android:onClick="MethodeNameHere" in my activity.xml-File. This don't work in my PreferenceActivity class so no message.
Is there a (easy) way to do something like the "onClick" in a similar manner?
You can set listener for checkbox.
CheckBoxPreference checkBox = (CheckBoxPreference) findPreference("pushCheckBox");
checkBox.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object value) {
//your code here
return true;
}
});
According to documentation return true will update the state of the Preference with the new value.
And simply check inside of listener if checkBox is checked.
If you are simply trying to make one attribute depend on another, you can use the android:dependency attribute. Will that do what you want? E.g.,
<CheckBoxPreference
android:key="pushCheckBox"
android:title="#string/pushnachr_headline"
android:summary="#string/pushnachr_explain"
android:defaultValue="true">
<!-- This setting will be disabled if pref_one is not checked -->
<CheckBoxPreference
android:defaultValue="false"
android:key="preference_two"
android:dependency="pushCheckBox"
android:title="Pref Two" />
But, if you really just want to get the click event to do something else, put something like this in the onResume method.
Preference pushCheckBox = findPreference("pushCheckBox");
pushCheckBox.setOnPreferenceClickListener(new OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
// do something here
return false;
}
});

Setting up buttons for Android

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.

Admob - no ad to show

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

Categories