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

时间:2014-07-05 20:30:59

标签: android nullpointerexception

我试图按照练习在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;
        }
    }

}

以下是2个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" />

和fragment_to_do_list.xml:

    <?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.setAdapter(aa)行;这导致空指针异常,但我无法理解为什么因为aa已被实例化,据我所见。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

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