0

I am including toolbar on my followup activity after adding I want to add an icon on right side but it give error.Please help me how can I resolve it.

public class Add_Followup extends AppCompatActivity {

androidx.appcompat.widget.Toolbar tool_bar

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add__followup);

    tool_bar=(Toolbar) findViewById(R.id.custom_toolbar);
    setSupportActionBar(tool_bar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    tool_bar.setNavigationIcon(R.drawable.back);
  }

I include like this.

<include
    layout="@layout/custom_tool_bar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

This is customlayout

<androidx.appcompat.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:fontFamily="serif"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#FF9B9B"
android:elevation="4dp"
app:title="Welcome"
app:titleTextColor="#ffff"
app:subtitleTextColor="#ffff"
android:id="@+id/custom_toolbar">

I am facing this exception

  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
    at com.example.loginproject.Add_Followup.onCreate(Add_Followup.java:54)
    at android.app.Activity.performCreate(Activity.java:7802)
    at android.app.Activity.performCreate(Activity.java:7791)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
  • That would mean that `findViewById(R.id.custom_toolbar)` is returning null. Are you certain that `custom_toolbar` is in the `activity_add__followup` layout? How exactly are you including it? Do you mean you've used an `` element for it? – Mike M. Aug 23 '19 at 12:04
  • 1
    Possible duplicate of [Null pointer Exception - findViewById()](https://stackoverflow.com/questions/19078461/null-pointer-exception-findviewbyid) – Vivek Mishra Aug 23 '19 at 12:06
  • Yes I am including it via . –  Aug 23 '19 at 12:41
  • can you please also post your XML file? – Chandan Sharma Aug 23 '19 at 12:53
  • I am using this custom tool bar on another activity using same way but there is only warning shows but no exception –  Aug 25 '19 at 13:14

1 Answers1

0

Just call id like this.

<include layout="@layout/custom_tool_bar"
    android:id="@+id/custom_toolbar"/>
Tarun Sharma
  • 914
  • 9
  • 15