在android应用程序中使用setAdapter时生成的NullPointerException

在android应用程序中使用setAdapter时生成的NullPointerException,android,nullpointerexception,Android,Nullpointerexception,我正试图按照一个练习在android上创建一个简单的待办事项列表应用程序,但是当我运行这个项目时,我得到了NullPointerException。我可以从LogCat中看出,是我代码中的第46行导致了这个问题,但我不明白为什么,这里是java文件: package com.example.todolist; //import android.R; import java.util.ArrayList; import android.os.Bundle; import android.sup

我正试图按照一个练习在android上创建一个简单的待办事项列表应用程序,但是当我运行这个项目时,我得到了NullPointerException。我可以从LogCat中看出,是我代码中的第46行导致了这个问题,但我不明白为什么,这里是java文件:

package com.example.todolist;

//import android.R;
import java.util.ArrayList;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

public class ToDoListActivity extends ActionBarActivity {

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

        //inflate the view
        setContentView(R.layout.activity_to_do_list);


        //get references to UI widgets
        ListView myListView = (ListView)findViewById(R.id.myListView1);
        final EditText myEditText = (EditText)findViewById(R.id.myEditText); //You are always allowed to initialize a final variable. The compiler makes sure that you can do it only once


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

        //Create the Array Adaptor 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);
        //simple_list_item_1 is a reference to an built-in XML layout document that is part of the Android OS


        //below is causing nullpointer exception
        //Bind the ArrayAdapter to the list view
        myListView.setAdapter(aa);

        /*
        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)) {
                        todoItems.add(0,myEditText.getText().toString());
                        aa.notifyDataSetChanged();
                        myEditText.setText("");
                        return true;
                    }
                return false;
            }   
            });
        */

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.to_do_list, 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);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_to_do_list,
                    container, false);
            return rootView;
        }
    }

}
下面是两个XML布局文件,首先是activity_to_do_list.XML:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.todolist.ToDoListActivity"
tools:ignore="MergeRootFrame" />
    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
  <EditText
    android:id="@+id/myEditText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="@string/addItemHint"
    />
  <ListView
    android:id="@+id/myListView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
  />
</LinearLayout>
和片段_to_do_list.xml:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.todolist.ToDoListActivity"
tools:ignore="MergeRootFrame" />
    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
  <EditText
    android:id="@+id/myEditText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="@string/addItemHint"
    />
  <ListView
    android:id="@+id/myListView1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
  />
</LinearLayout>

它是myListView.setAdapteraa行;这导致了空指针异常,但我不明白为什么,因为据我所知,aa已经被实例化了。有人能帮忙吗?

您需要将大部分逻辑从活动的onCreate方法移动到片段的onCreateView。这是因为当您试图在活动中查找ListView时,片段的视图尚未膨胀。

myListView为null,它为null,因为它在片段中,而不是活动xml中,因此FindViewByAdjust无法找到它删除您的片段。这里不需要使用片段。删除该片段的片段类和xml。并将当前位于片段xml上的ListView移到主xml文件中。非常感谢,我将代码移到了片段中,在修改了几行之后,它工作了!我需要将调用findViewById方法的类更改为片段中使用的类:rootView.findviewbydr.id.myEditText;还有ArrayAdaptor的上下文,因为它在片段中不起作用:aa=newArrayAdapterGetActivity,android.R.layout.simple_list_item_1,todoItems;