-1

I am trying to create a Navigation drawer and have thoroughly followed an online tutorial and am getting the error "Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference"

Full error message: 06-21 13:59:08.134 8883-8883/com.example.saarikakumar.factsappfull E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.saarikakumar.factsappfull, PID: 8883

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.saarikakumar.factsappfull/com.example.saarikakumar.factsappfull.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) at android.app.ActivityThread.-wrap11(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference at com.example.saarikakumar.factsappfull.MainActivity.addDrawerItems(MainActivity.java:97) at com.example.saarikakumar.factsappfull.MainActivity.onCreate(MainActivity.java:43) at android.app.Activity.performCreate(Activity.java:6237) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)  at android.app.ActivityThread.-wrap11(ActivityThread.java)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:148)  at android.app.ActivityThread.main(ActivityThread.java:5417)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

The error is specifically in this line: mDrawerList.setAdapter(mAdapter); and addDrawerItems();

My MainActivity code is:

    import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;

public class MainActivity extends AppCompatActivity {


    private TextView info;
    private LoginButton loginButton;
    private CallbackManager callbackManager;
    private ListView mDrawerList;
    private DrawerLayout mDrawerLayout;
    private ArrayAdapter<String> mAdapter;
    private ActionBarDrawerToggle mDrawerToggle;
    private String mActivityTitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mDrawerList = (ListView) findViewById(R.id.navList);mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mActivityTitle = getTitle().toString();

        addDrawerItems();
        setupDrawer();

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);


        FacebookSdk.sdkInitialize(getApplicationContext());
        callbackManager = CallbackManager.Factory.create();
        setContentView(R.layout.activity_main);
        info = (TextView) findViewById(R.id.info);
        loginButton = (LoginButton) findViewById(R.id.login_button);

        loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                info.setText("Login successful");
                info.setText(
                        "User ID: "
                                + loginResult.getAccessToken().getUserId()
                                + "\n" +
                                "Auth Token: "
                                + loginResult.getAccessToken().getToken()

                );
            }

            @Override
            public void onCancel() {
                info.setText("Login attempt cancelled");

            }

            @Override
            public void onError(FacebookException error) {
                info.setText("Login attempt failed");

            }
        });

        Button switchButton = (Button) findViewById(R.id.login_button);
        switchButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, MainActivity5.class);
                startActivity(intent);

            }
        });
    }

    private void addDrawerItems() {
        String[] osArray = {"Android", "iOS", "Windows", "OS X", "Linux"};
        mAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, osArray);
        mDrawerList.setAdapter(mAdapter);

        mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(MainActivity.this, "Time for an upgrade!", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void setupDrawer() {
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {

            /** Called when a drawer has settled in a completely open state. */
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                getSupportActionBar().setTitle("Navigation!");
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }

            /** Called when a drawer has settled in a completely closed state. */
            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
                getSupportActionBar().setTitle(mActivityTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }
        };

        mDrawerToggle.setDrawerIndicatorEnabled(true);
        mDrawerLayout.setDrawerListener(mDrawerToggle);
    }


    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        // Activate the navigation drawer toggle
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }
}

Layout file is:

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="16dp"
    android:gravity="center"
    android:background="#f44336"
    android:orientation="vertical"
    android:id="@+id/fragment_placeholder"
    android:paddingBottom="16dp" tools:context=".MainActivity"
    android:weightSum="1"
    android:padding="41dp">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/info"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:textSize="18sp"
        />


    <com.facebook.login.widget.LoginButton
        android:id="@+id/login_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"/>

</LinearLayout>

    <ListView
        android:id="@+id/navList"
        android:layout_width="200dp"
        android:layout_height="match_parent"
        android:layout_gravity="left|start"
        android:background="#ffeeeeee"/>

</android.support.v4.widget.DrawerLayout>
SAK
  • 51
  • 1
  • 8
  • Please always add the error message in your question! – Sebastian Schneider Jun 21 '16 at 20:36
  • @SeseSchneider I did I put it in the first line of my question – SAK Jun 21 '16 at 20:39
  • @SAK This isn't enought, please provide the **full** error message, this can help us a lot – Sebastian Schneider Jun 21 '16 at 20:41
  • @SeseSchneider Just added in the full message – SAK Jun 21 '16 at 20:45
  • @SeseSchneider I get the error "error inflating class com.facebook.login.widget.LoginButton" When I put the code starting with mDrawerList = (ListView) findViewById(R.id.navList);mDrawerLayout = (DrawerLayout) Before the facebook login button code. When I put the facebook code first, I get the error "void android.support.v7.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference" at the line "getSupportActionBar().setDisplayHomeAsUpEnabled(true);" So not really sure what the error is – SAK Jun 23 '16 at 00:30

2 Answers2

1

You have to call setContentView first.

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

    /* add this */
    setContentView(R.layout.your_layout);

    mDrawerList = (ListView) findViewById(R.id.navList);mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mActivityTitle = getTitle().toString();

This tells the OS what layout you're inflating and where to locate the views you intent on manipulating in your Activity.

Francesc
  • 25,014
  • 10
  • 66
  • 84
  • You should explain why. – cyroxis Jun 21 '16 at 20:38
  • @Fracesc When you say your_layout do you mean drawer_layout? – SAK Jun 21 '16 at 20:41
  • @cyroxis Explain what? – SAK Jun 21 '16 at 20:41
  • The layout where the drawerlayout and the listview are defined. – Francesc Jun 21 '16 at 20:43
  • @cyroxis I just checked and I actually have that line of code further down – SAK Jun 21 '16 at 20:43
  • Then just move that line to above any findViewById call. – Francesc Jun 21 '16 at 20:43
  • @Francesc I just did and it still gave me the same error message. I just updated my question with the full error – SAK Jun 21 '16 at 20:46
  • Either the setConventView is not before all the findViewById, your listview is not called navList, or you're inflating the wrong layout. There is no other option. – Francesc Jun 21 '16 at 20:48
  • @Francesc I am creating a navigation drawer in my main activity so I put the listview in the layout file, I will add it to my question – SAK Jun 21 '16 at 20:56
  • @Francesc I get the error "error inflating class com.facebook.login.widget.LoginButton" When I put the code starting with mDrawerList = (ListView) findViewById(R.id.navList);mDrawerLayout = (DrawerLayout) Before the facebook login button code. When I put the facebook code first, I get the error "void android.support.v7.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference" at the line "getSupportActionBar().setDisplayHomeAsUpEnabled(true);" So not really sure what the error is – SAK Jun 23 '16 at 00:30
1

Your problem is, mDrawerList is null, this is because you have initialized it but haven't call setContentView in order to load the layout file.

Without the layout reference, your findViewById returns null,

add this:

setContentView(R.layout.name_of_this_activity_layout);

before your mDrawerList initialization.

Erik Minarini
  • 4,795
  • 15
  • 19
  • I just did and got the same error – SAK Jun 21 '16 at 20:55
  • I see you had updated your question, but I don't see you have call setContent, if you had called it, are you sure you had used the correct layout name? – Erik Minarini Jun 21 '16 at 20:59
  • I just added it in to the question – SAK Jun 21 '16 at 21:03
  • Now am getting another error in regards to my facebook login button that was previously working : java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.saarikakumar.factsappfull/com.example.saarikakumar.factsappfull.MainActivity}: android.view.InflateException: Binary XML file line #31: Binary XML file line #31: Error inflating class com.facebook.login.widget.LoginButton – SAK Jun 21 '16 at 21:05
  • So, the error on the mDrawerList is solved? Have you initialized facebook button before or after mDrawerList? – Erik Minarini Jun 21 '16 at 21:08
  • post your XML if you edited it – Erik Minarini Jun 21 '16 at 21:15
  • I posted it in the question I updated it – SAK Jun 21 '16 at 22:27
  • What facebook sdk version are you using? I think Facebook sdk require FacebookSdk.sdkInitialize(getApplicationContext()); before calling setContentView. So put this line as first after super.onCreate(savedInstanceState); Try and let me know – Erik Minarini Jun 21 '16 at 22:42
  • Erik Minarini I am now getting this error inflateException: Binary XML file line #31: Binary XML file line #31: Error inflating class com.facebook.login.widget.LoginButton at this line: setContentView(R.layout.activity_main); – SAK Jun 22 '16 at 15:31
  • Have you initialized Facebook sdk before this line as I've suggested in the comment above? – Erik Minarini Jun 22 '16 at 19:55
  • yes I initialized it before – SAK Jun 22 '16 at 22:26
  • you miss this: xmlns:facebook="http://schemas.android.com/apk/res-auto" try to add this in the xml parent – Erik Minarini Jun 22 '16 at 22:42
  • I put that in and it says "namespace declaration is never used" and now I am getting another error "Attempt to invoke virtual method 'void android.support.v7.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference" at this line: "getSupportActionBar().setDisplayHomeAsUpEnabled(true);" – SAK Jun 22 '16 at 22:55
  • ok, drop this namespaces, bad idea! – Erik Minarini Jun 22 '16 at 23:04
  • look this answer: http://stackoverflow.com/a/32682310/6093353 this guys resolve your same problem with multidex – Erik Minarini Jun 22 '16 at 23:14
  • I get the error "error inflating class com.facebook.login.widget.LoginButton" When I put the code starting with mDrawerList = (ListView) findViewById(R.id.navList);mDrawerLayout = (DrawerLayout) Before the facebook login button code. When I put the facebook code first, I get the error "void android.support.v7.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference" at the line "getSupportActionBar().setDisplayHomeAsUpEnabled(true);" So not really sure what the error is – SAK Jun 23 '16 at 00:29