setAdapter返回null

时间:2016-06-21 20:34:09

标签: java android navigation-drawer

我正在尝试创建一个导航抽屉并完全遵循在线教程并在空对象上收到错误“尝试调用虚拟方法'void android.widget.ListView.setAdapter(android.widget.ListAdapter)'参考“

完整的错误消息:06-21 13:59:08.134 8883-8883 / com.example.saarikakumar.factsappfull E / AndroidRuntime:FATAL EXCEPTION:main                                                                                      处理:com.example.saarikakumar.factsappfull,PID:8883

  

java.lang.RuntimeException:无法启动活动ComponentInfo {com.example.saarikakumar.factsappfull / com.example.saarikakumar.factsappfull.MainActivity}:java.lang.NullPointerException:尝试调用虚方法'void android.widget .ListView.setAdapter(android.widget.ListAdapter)'在空对象引用上   在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)   在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)   在android.app.ActivityThread.-wrap11(ActivityThread.java)   在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1344)   在android.os.Handler.dispatchMessage(Handler.java:102)   在android.os.Looper.loop(Looper.java:148)   在android.app.ActivityThread.main(ActivityThread.java:5417)   at java.lang.reflect.Method.invoke(Native Method)   在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:726)   在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)   引起:java.lang.NullPointerException:尝试在空对象引用上调用虚方法'void android.widget.ListView.setAdapter(android.widget.ListAdapter)'   在com.example.saarikakumar.factsappfull.MainActivity.addDrawerItems(MainActivity.java:97)   at com.example.saarikakumar.factsappfull.MainActivity.onCreate(MainActivity.java:43)   在android.app.Activity.performCreate(Activity.java:6237)   在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)   在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)   在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)   在android.app.ActivityThread.-wrap11(ActivityThread.java)   在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1344)   在android.os.Handler.dispatchMessage(Handler.java:102)   在android.os.Looper.loop(Looper.java:148)   在android.app.ActivityThread.main(ActivityThread.java:5417)   at java.lang.reflect.Method.invoke(Native Method)   在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:726)   在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

错误具体在这一行: mDrawerList.setAdapter(mAdapter);        和 addDrawerItems();

我的MainActivity代码是:

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

布局文件是:

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

2 个答案:

答案 0 :(得分:1)

你必须先调用setContentView。

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

这告诉操作系统您要在哪些布局中进行充气,以及在哪里找到您想要在您的活动中操纵的视图。

答案 1 :(得分:1)

你的问题是,mDrawerList是null,这是因为你已经初始化它但没有调用setContentView来加载布局文件。

如果没有布局引用,findViewById将返回null,

添加:

setContentView(R.layout.name_of_this_activity_layout);
在你的mDrawerList初始化之前