-2

I've created BaseActivityto display navigation drawer on all activities. The activities that need navigation extends from BaseActivity.

I tried to change the value of the textviews in the navigation drawer to display username and user email. But I am getting NullPointerExceptionas below.

  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
  at com.mysite.myapp.MainActivity.onCreate(BaseActivity.java:100)
  at com.mysite.myapp.ActivityMain.onCreate(ActivityMain.java:22)

nav_header.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="@dimen/nav_header_height"
    android:background="@drawable/side_nav_bar"
    android:gravity="bottom"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:theme="@style/ThemeOverlay.AppCompat.Dark">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/nav_header_vertical_spacing"
        android:src="@android:drawable/sym_def_app_icon" />

    <TextView
        android:id="@+id/userView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/nav_header_vertical_spacing"
      android:textAppearance="@style/TextAppearance.AppCompat.Body1" />

    <TextView
        android:id="@+id/EmailView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>

BaseActivity.java

public abstract class BaseActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {
    private SQLiteHandler db;
    private SessionManager session;
    private Toolbar mActionBarToolbar;
    private DrawerLayout mDrawerLayout;
    protected NavigationView mNavigationView;
    private ActionBarDrawerToggle mToggle;
    private TextView txtName;
    private TextView txtEmail;


    protected boolean useToolbar() {
        return true;
    }


    protected boolean useDrawerToggle() {
        return true;
    }


    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);

        getActionBarToolbar();

        setupNavDrawer();
    }//end setContentView


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        txtEmail = (TextView) findViewById(R.id.EmailView);
        txtName = (TextView) findViewById(R.id.userView);
        db = new SQLiteHandler(getApplicationContext());

        // session manager
        session = new SessionManager(getApplicationContext());

        if (!session.isLoggedIn()) {
            session.setLogin(false);

            db.deleteUsers();

            // Launching the login activity
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
            // finish();
        }

        // Fetching user details from sqlite
        HashMap<String, String> user = db.getUserDetails();

        String name = user.get("name");
        String email = user.get("email");
        //Toast Message to show the usernmae
        Toast.makeText(getApplicationContext(), name, Toast.LENGTH_LONG).show();

         txtName.setText(name);
         txtEmail.setText(email);

    }}

More Details As a base activity, I am using it to create user session once the user login. I am fetching the username and user email from the SQLite database. I also tried testing whether the username is being fetched correctly through a toast message as indicated in the code. The username is being fetched correctly.

Please let me know if any details to be added. Any help would be appreciated.

Rohit5k2
  • 17,948
  • 8
  • 45
  • 57
George Forster
  • 1,201
  • 2
  • 9
  • 5

2 Answers2

1

You never set the layout to the activity.

Use setContentView(R.layout.activity_layout) in onCreate after calling super.

Your onCreate method should look like this

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_layout); // use your layout

    txtEmail = (TextView) findViewById(R.id.EmailView);
    ...
    ...
}

Note: When you don't set your layout using setContentView, then you don't have any layout associated with the activity and if you try to use findViewById to get any view then it will be null.

Update:

Keeping in mind you are using it as a base class to other activities, you should have a layout which will hold these two TextView's and a container. Use that layout in the base class. When child classes call super.setContentView() then just load the layout passed from child class to that container. This way you will have these view available in all the activities.

Rohit5k2
  • 17,948
  • 8
  • 45
  • 57
  • But this is a baseactivity and it is being extended in other activities where I call setContentView() with appropriate layouts. Correct me if I am wrong. – George Forster Feb 18 '16 at 09:47
  • Error is in `com.mysite.myapp.MainActivity.onCreate` – Rohit5k2 Feb 18 '16 at 09:50
  • I have the navigation drawer layout in three separate xml files. Where header, menu and the drawerlayout itself. – George Forster Feb 18 '16 at 09:54
  • In that case you should have a container which will hold these two TextView's and use that layout here. This way you will have these view available in all the activities. You should not reference a view which is being set by child class. Also, don't forget to call `super.setContentView` in child classes. – Rohit5k2 Feb 18 '16 at 09:57
  • Thanks for your answer. Can you please demonstrate the same in your answer ? – George Forster Feb 18 '16 at 17:08
1

You have to call setContentView in your onCreate method.

Ludwig S
  • 551
  • 3
  • 8