简体   繁体   中英

NullPointerException - attempt to invoke virtual method `notifyDataSetChanged()` - can't see list created

I'm working my way through this tutorial and am stuck adding names to a list, and having the list populate.

Here's what I'm trying to get, a list of names that I type in in the input box: http://www.raywenderlich.com/78576/android-tutorial-for-beginners-part-2

(The underlined "Darryl" is the input box, and it shows that name (after hitting the button) on top, then adds it to the list).

I'm getting this error though:

08-24 18:17:50.903  21935-21935/com.example.batman.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.batman.myapplication, PID: 21935
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ArrayAdapter.notifyDataSetChanged()' on a null object reference
            at com.example.batman.myapplication.MainActivity.onClick(MainActivity.java:65)
            at android.view.View.performClick(View.java:5217)
            at android.view.View$PerformClick.run(View.java:20983)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:145)
            at android.app.ActivityThread.main(ActivityThread.java:6141)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)

Here's my MainActivity.java :

package com.example.batman.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    TextView mainTextView;
    EditText mainEditText;
    ListView mainListView;
    ArrayAdapter mArrayAdapter;
//  ArrayList<String> mNameList = new ArrayList<String>();
    ArrayList mNameList = new ArrayList();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 1. Access the TextView defined in layout XML
        // and then set its text
        mainTextView = (TextView) findViewById(R.id.main_textview);
        mainTextView.setText("Set in Java!");

        Button mainButton;
        mainButton = (Button) findViewById(R.id.main_button);
        mainButton.setOnClickListener(this);

        // 3.  Access the EditText defined in layout XML
        mainEditText = (EditText) findViewById(R.id.main_edittext);

        // 4. Access the ListView
        mainListView = (ListView) findViewById(R.id.main_listview);
        // Create an ArrayAdapter for the ListView
        mArrayAdapter = new ArrayAdapter(this,  // removed ArrayAdapter before mArrayAdapter
                android.R.layout.simple_list_item_1,
                mNameList);
        // Set the ListView to use the ArrayAdapter
        mainListView.setAdapter(mArrayAdapter);
    }

    @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 void onClick(View v) {
        // Take what was typed into the EditText
        // and use in TextView
        mainTextView.setText(mainEditText.getText().toString() + ".");

        // Also add that value to the list shown in the ListView
        mNameList.add(mainEditText.getText().toString());
        mArrayAdapter.notifyDataSetChanged();
    }
} // end class

Here's ActivityMain.XML :

<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:orientation="vertical"
              tools:context=".MainActivity">

    <TextView
        android:id="@+id/main_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="20dp"
        android:text="textView"/>
    <!-- Displays keyboard when touched -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <!-- List whose dataset is defined in code with an adapter -->
        <ListView
            android:id="@+id/main_listview"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:layout_marginTop="20dp"/>

        <!-- Set OnClickListener to trigger results when pressed -->

        <Button
            android:id="@+id/main_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:layout_marginLeft="20dp"
            android:text="button" />
        <!-- Shows an image from your drawable resources -->
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:layout_marginLeft="20dp"
            android:src="@drawable/ic_launcher" />
        <!-- Closing tag for the horizontal nested layout -->
    </LinearLayout>

    <EditText
        android:id="@+id/main_edittext"
        android:inputType="textCapSentences"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:layout_marginLeft="20dp"
        android:hint="hint"/>

    <!-- Closing tag for the horizontal nested layout -->
</LinearLayout>

I also get some highlighting (Android Studio) on the new ArrayAdapter(this, android.R.layout.simple_list_item_1, mNameList); line, saying there's an "Unchecked call" to it.

As you can see by my one comment, do I need to make the mNameList a string by something like ArrayList<String> mNameList = new ArrayList<String>(); ?

(If you need the manifest or my MainActivity.xml , let me know).

Thanks for any ideas!

Edit: Thanks to the comments, I removed ArrayAdapter from the onClick part. The final part of issue is to get the list to display. It now displays the input, but doesn't show up on a list below. I've attached the XML too.

You did not initialized the global variable mArrayAdapter

change :

ArrayAdapter mArrayAdapter = new ArrayAdapter(this,
            android.R.layout.simple_list_item_1,
            mNameList);

to :

mArrayAdapter = new ArrayAdapter(this,
            android.R.layout.simple_list_item_1,
            mNameList);

in the onCreate Method of your activity

Your mArrayAdapter is always null since you're creating a local mArrayAdapter with this:

ArrayAdapter mArrayAdapter = new ArrayAdapter(this,
                android.R.layout.simple_list_item_1,
                mNameList);

So... just remove ArrayAdapter so you will initialize the global version of the adapter and you should be fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM