invoke virtual method on null object reference (setDisplayHomeAsUpEnabled) - java

I want my update_activity to display a back arrow button but this code gives me this error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
at this line:
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
What do you suggest?
public class UpdateActivity extends AppCompatActivity {
TextView textView;
AppBarLayout appbar;
private static Socket s;
private static PrintWriter pw;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Button button = findViewById(R.id.UpdateButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
connect();
}
});
}
when I substitute that command with
Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
it returns me this other error (which I think is the same):
Unable to start activity
ComponentInfo{io.anycopy.googleplusdemo/io.anycopy.googleplusdemo.UpdateActivity}: java.lang.NullPointerException

Most likely you are using NoActionBar themes, in which case getSupportActionBar () return null and you must either change the theme or use getActionBar ()

Related

setOnClickListener does not work in android studio

that is my code, very simple and basic
public Button btn1;
public TextView txt1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.txt1);
findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
txt1.setText("finalyyyyyyyyyyy");
}
});
and the error showing is:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
The problem is here
findViewById(R.id.txt1);
findViewById(R.id.btn1);
you are getting the views from the .xml file but you are not actually assigning the value to any object... so when you try to call a method to the btn1 it's null (empty) and throws an error
So just assign the value you are getting to the views objects like so:
txt1 = findViewById(R.id.txt1);
btn1 = findViewById(R.id.btn1);
This will fix the problem
Save the element in variable and set onClick method to that particular variable as below:
btn1 = findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
txt1.setText("finalyyyyyyyyyyy");
}
});

NullPointerException when the orientation changes

I have a Preference activity where I get this error when it changes orientation:
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.material.floatingactionbutton.FloatingActionButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
Here is where the crash occurs specifically:
public class SomeActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
.
.
.
}
public static class SettingsFragment extends PreferenceFragmentCompat {
setPreferencesFromResource(R.xml.some_preferences, rootKey);
.
.
final FloatingActionButton brightnessFloatingActionButton = getActivity().findViewById(R.id.brightnessFloatingActionButton);
brightnessFloatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveData(sharedPreferences, gson, brightness_level_preference, packageName);
getActivity().finish();
}
});
.
.
}
}
If I remove the setOnCLickListener statement the orientation crash no longer occurs. What's the problem here?
Add below line in manifest
android:configChanges="orientation|screenSize"

App crashes when attempting to swap activities [duplicate]

This question already has answers here:
findViewByID returns null
(33 answers)
Closed 3 years ago.
This is a basic activity swapping.
The app does not crash if i declare a local button inside the configureActivitySwap() method like this:
Button voiceBtn = (findViewById(R.id.goToVoice));
But I have to declare the button in the global scope instead so I can use the button in other methods, mainly activating and deactivating the button when it should/should not be pressed.
I also noticed that if I remove the finish(); method and replace it with something else the app functions normally, but I have to have the finish(); method one way or another.
public class RecogActivity extends AppCompatActivity {
private Button voiceBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
voiceBtn = findViewById(R.id.goToVoice);
setContentView(R.layout.main_layout);
// some unrelated code
configureActivitySwap();
}
public void configureActivitySwap(){
// Button voiceBtn = (findViewById(R.id.goToVoice));
voiceBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
}
My runtime error logs:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: tk.gandriks.gaaudiotransform, PID: 23125
java.lang.RuntimeException: Unable to start activity ComponentInfo{tk.gandriks.gaaudiotransform/tk.gandriks.gaaudiotransform.RecogActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2957)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6944)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at tk.gandriks.gaaudiotransform.RecogActivity.configureActivitySwap(RecogActivity.java:140)
at tk.gandriks.gaaudiotransform.RecogActivity.onCreate(RecogActivity.java:124)
at android.app.Activity.performCreate(Activity.java:7183)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1220)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2910)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3032) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1696) 
at android.os.Handler.dispatchMessage(Handler.java:105) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6944) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374) 
You need to call the setContentView() before calling voiceBtn = findViewById(R.id.goToVoice); Since you don't specify the layout the findViewById method will not get the button instance
public class RecogActivity extends AppCompatActivity {
private Button voiceBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set the layout first
setContentView(R.layout.YOUR_LAYOUT_XML_FILE_NAME)
voiceBtn = findViewById(R.id.goToVoice);
// some unrelated code
configureActivitySwap();
}
public void configureActivitySwap(){
// Button voiceBtn = (findViewById(R.id.goToVoice));
voiceBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
Try I guess) In your // some unrelated code is contains setContentView method?
public class RecogActivity extends AppCompatActivity {
private Button voiceBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
voiceBtn = findViewById(R.id.goToVoice);
setContentView(R.layout.some_layout)
// some unrelated code
configureActivitySwap();
}
public void configureActivitySwap(){
// Button voiceBtn = (findViewById(R.id.goToVoice));
voiceBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
}
You caught NPE because of findViewById is calling on inflated view. You are have been calling findViewById before setContentView in the first case and got the exception. And in the second case - in configureActivitySwap, that going after setContentView. Move setContentView after super.onCreate(savedInstanceState) and all will be working fine.
Are you setting layout before trying to find view with findViewById?
setContentView(R.layout.main_layout);
voiceBtn = (Button) findViewById(R.id.goToVoice);
replace the statement in your onCreate() method with the above. It should work.
and use
super.finish() instead of finish()

Android toolbar save state when visible/gone

I'm making a calculator (those bits are not shown in the code below) and I have a toolbar at the bottom of the application, and I can toggle its visibility from a menu. This is my current MainActivity class:
public class MainActivity extends Activity implements OnClickListener {
public Toolbar toolbar_btm;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar_btm = findViewById(R.id.toolbar_bottom);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//Toolbar toolbar_btm = findViewById(R.id.toolbar_bottom);
outState.putInt("TOOLBAR_VISIBLE", toolbar_btm.getVisibility());
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
//Toolbar toolbar_btm = findViewById(R.id.toolbar_bottom);
toolbar_btm.setVisibility(savedInstanceState.getInt("TOOLBAR_VISIBLE"));
}
//Toggles the toolbar to show/hide
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.toolbar_toggle:
Toolbar toolbar_btmtog = findViewById(R.id.toolbar_bottom);
if (toolbar_btmtog.getVisibility() == View.GONE)
toolbar_btmtog.setVisibility(View.VISIBLE);
else if (toolbar_btmtog.getVisibility() == View.VISIBLE)
toolbar_btmtog.setVisibility(View.GONE);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
However, I cannot seem to keep this visible/gone state in memory. I've tried using onSaveInstanceState and onRestoreInstanceState, but when I run my code, it throws the following exception:
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.calculator/com.example.calculator.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.Toolbar.setVisibility(int)' on a null object reference
I simply cannot figure out what the issue is. I'm using putInt and getInt and I'm declaring the toolbar with the right name. So, why am I getting a null object reference?
You have two varaibles named toolbar_btm. One is global and unassigned, and another is in onOptionsItemSelected(MenuItem item). That local variable "overwrites" local variable (in function)
You should declare Toolbar as global, and then assign its value in OnCreate() or, if that doesn't work, in overridden function OnResume(). You assign value by not using Toolbar keyword for a second time, so like this.
toolbar_btm = findViewById(R.id.toolbar_bottom);
UPDATE:
You could also drop Toolbar altogether and use ActionBar instead. This snippet will toggle action bar visibility in Activity (not Fragment):
ActionBar actionBar = getActionBar();
if(actionBar.isShowing())
actionBar.hide();
else
actionBar.show();
this.invalidateOptionsMenu();
You are not assigning your Toolbar variable. After menu option was selected you are using local one. Put this code in onCreate() :
toolbar_btm = findViewById(R.id.toolbar_bottom);

Null PointerExeption ALL the time?

Why is mainB_news allways null? (in the method onBackPressed())
In onCreate I set a value to the button!!! :(
PS: with findViewById() I get the same error...
public class MainActivity extends Activity {
private Button mainB_news;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mainB_news = (Button) findViewById(R.id.mainB_news);
mainB_news.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
setContentView(R.layout.news);
}
});
}
#Override
public void onBackPressed() {
// check if page 2 is open
if (mainB_news != null && mainB_news.isShown()){
setContentView(R.layout.main); // open main view again
return;
}else
super.onBackPressed(); // allows standard use of backbutton for page 1
}
}
THANKS a lot!
Because you change contentView on button click. mainB_news doesn't exist after contentView changing. You shouldn't use setContentView() in this manner. Consider using another activity for showing news.
Because it is not defined in res/layout/main.xml ?

Categories