Android Null指针异常 - 碎片(PA4AD)

use*_*591 1 java android nullpointerexception android-fragments

我一直在通过专业Android 4 App开发工作,并且已经停留在其中一个教程中.我的应用程序编译正常,但是当我运行它时,它崩溃并出现错误NullPointerException:尝试在空对象引用上调用虚方法'boolean java.util.ArrayList.add(java.lang.Object'.当我输入一些文本时会发生这种情况进入edittext并点击返回.

该程序似乎在onNewItemAdded方法(todoItems.add行)中崩溃.据我所知,我的arraylist已正确初始化.

我相对来说是Java和Android开发的新手,我对于出了什么问题感到困惑.

对于那些不熟悉本书的人,该应用程序包含一个编辑文本片段和一个列表片段.

谢谢你的帮助.

ToDoListActivity.java

import android.app.Activity;
import android.app.FragmentManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import java.util.ArrayList;


public class ToDoListActivity extends Activity
    implements NewItemFragment.OnNewItemAddedListener {

    private ArrayAdapter<String> aa;
    private ArrayList<String> todoItems;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Inflate your View
        setContentView(R.layout.main);

        // Get references to UI widgets
        FragmentManager fm = getFragmentManager();
        ToDoListFragment toDoListFragment =
                (ToDoListFragment)fm.findFragmentById(R.id.ToDoListFragment);

        // Create the Array List of to do items
        final ArrayList<String> todoItems = new ArrayList<String>();

        // Create the Array Adapter to bind the array to the List View
        final ArrayAdapter<String> aa;

        aa = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1,
                todoItems);

        // Bind the Array Adapter to the List View
        toDoListFragment.setListAdapter(aa);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.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();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    public void onNewItemAdded(String newItem) {
        System.out.println(newItem);
        todoItems.add(newItem);
        aa.notifyDataSetChanged();
    }
}
Run Code Online (Sandbox Code Playgroud)

NewItemFramgment.java

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link NewItemFragment.OnNewItemAddedListener} interface
 * to handle interaction events.
 *
 */
public class NewItemFragment extends Fragment {

    private OnNewItemAddedListener onNewItemAddedListener;

    public interface OnNewItemAddedListener {
        public void onNewItemAdded(String newItem);
    }

    public NewItemFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.new_item_fragment, container, false);

        final EditText myEditText = (EditText)view.findViewById(R.id.myEditText);

        myEditText.setOnKeyListener(new View.OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN)
                if ((keyCode == KeyEvent.KEYCODE_DPAD_CENTER) ||
                        (keyCode == KeyEvent.KEYCODE_ENTER)) {
                    String newItem = myEditText.getText().toString();
                    onNewItemAddedListener.onNewItemAdded(newItem);
                    myEditText.setText("");
                    return true;
                }
            return false;
        }
    });

    return view;
}

/*    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }*/

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            onNewItemAddedListener = (OnNewItemAddedListener)activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnItemAddedListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        onNewItemAddedListener = null;
    }
}
Run Code Online (Sandbox Code Playgroud)

nem*_*035 5

要了解您的问题,您需要了解变量作用域在Java中的工作方式

简而言之,您有类变量(也称为字段)和局部变量:

class MyClass {
    int myVar;        // Class Variable - this variable is visible to the whole class

    void someMethod() {
        int myVar;    // Local Variable - this variable is visible only within someMethod()
    }
}
Run Code Online (Sandbox Code Playgroud)

通过对类和局部变量使用相同的名称,里面的变量someMethod()是"隐藏"全局类变量.

因此,您的问题是,在您的内部onCreate,您通过说:重新声明一个ArrayList名为todoItems:

// Create the Array List of to do items
final ArrayList<String> todoItems = new ArrayList<String>();
Run Code Online (Sandbox Code Playgroud)

这意味着todoItems引用此本地版本(仅在onCreate方法内可见),而不是您在类顶部定义的全局版本(对整个类可见).

但是,在你的onNewItemAdded方法中,todoItems指的ArrayList是从未初始化(因此null)的类全局,这就是为什么你得到一个NullPointerException.

您应该将上面的陈述更改为:

todoItems = new ArrayList<String>();
Run Code Online (Sandbox Code Playgroud)

所以它指的是全球类 ArrayList

注意:你的问题也有同样的问题ArrayAdapter<String> aa