-2

我正在使用 aArrayAdapter来显示通过 a 保存在数组中的数据ListView,我的代码编译得很好,但是当我调用下面的类时,会导致进程以Sorry application has stopped异常结束。

   public class Timetable extends Activity {

    private ListView timeTableView;
    private ArrayList <Module> Modules;
    private ArrayAdapter <Module> adaptModule;

     @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.view);

            timeTableView = (ListView) findViewById(R.id.timeTableView);

            adaptModule = new ArrayAdapter<Module>(this, android.R.layout.simple_list_item_1, Modules);
            timeTableView.setAdapter(adaptModule);
     }
    }

这是我的Add课程,它处理创建数组并将项目添加到数组中:

public class Add extends Activity implements OnClickListener{

private EditText ModuleText;
private EditText RoomText;
private Spinner Day;
private Spinner Start;
private Spinner Duration;
private Spinner Session;
private ArrayList<Module> Modules;

/*
 * OnCreate method for add class
 * @see android.app.Activity#onCreate(android.os.Bundle)
 */

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.add);

    // spinner for days
    Spinner day = (Spinner) findViewById(R.id.spinnerDay);
    ArrayAdapter<CharSequence> adapterDay = ArrayAdapter.createFromResource(
            this, R.array.days_array, android.R.layout.simple_spinner_item);
    adapterDay.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    day.setAdapter(adapterDay);


    // spinner for start time
    Spinner startTime = (Spinner) findViewById(R.id.spinnerStart);
    ArrayAdapter<CharSequence> adapterstart = ArrayAdapter.createFromResource(
            this, R.array.start_array, android.R.layout.simple_spinner_item);
    adapterstart.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    startTime.setAdapter(adapterstart);

    // spinner for duration
    Spinner duration = (Spinner) findViewById(R.id.spinnerDuration);
    ArrayAdapter<CharSequence> adapterduration = ArrayAdapter.createFromResource(
            this, R.array.duration_array, android.R.layout.simple_spinner_item);
    adapterduration.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    duration.setAdapter(adapterduration);

    // spinner for class type
    Spinner session = (Spinner) findViewById(R.id.spinnerSession);
    ArrayAdapter<CharSequence> adapterSession = ArrayAdapter.createFromResource(
            this, R.array.session_array, android.R.layout.simple_spinner_item);
    adapterSession.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    session.setAdapter(adapterSession);

    //create array
    Modules = new ArrayList<Module>();

    // ref to UI Widgets
    ModuleText = (EditText) findViewById(R.id.ModuleText);
    RoomText = (EditText) findViewById(R.id.RoomText);
    Day = (Spinner) findViewById(R.id.spinnerDay);
    Start = (Spinner) findViewById(R.id.spinnerStart);
    Duration = (Spinner) findViewById(R.id.spinnerDuration);
    Session = (Spinner) findViewById(R.id.spinnerSession);


    // buttons for this activity also includes listeners
    View addEntryButton = findViewById(R.id.addEntry_button);
    addEntryButton.setOnClickListener(this);
    View cancelEntryButton = findViewById(R.id.cancelEntry_button);
    cancelEntryButton.setOnClickListener(this);


}

/*
 * on click listeners for buttons
 * @see android.view.View.OnClickListener#onClick(android.view.View)
 */
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.cancelEntry_button:
        Intent i = new Intent(this, Home.class);
        startActivity(i);
        break;

    }
     switch (v.getId()) {
        case R.id.addEntry_button:
            Intent i = new Intent(this, Home.class);
            addModule();
            startActivity(i);
            break;
    }

    }

    /* 
     * Method for adding an entry into the table
     */
public void addModule() 
   {
    if(ModuleText !=null || RoomText !=null)
    {
    Modules.add(new Module(ModuleText.getText().toString(), RoomText.getText().toString(), Day.getSelectedItem().toString(), Start.getSelectedItem().toString(), Duration.getSelectedItem().toString(), Session.getSelectedItem().toString()));
    Toast.makeText(getApplicationContext(), "Timetable entry has been added succesfully", Toast.LENGTH_SHORT).show();
    }
    else
    {
        Toast.makeText(getApplicationContext(), "Error adding timetable entry, please check details and try again", Toast.LENGTH_SHORT).show();
    }

   }


} 

这是我logcat的例外:

04-22 11:52:46.290: E/AndroidRuntime(426): FATAL EXCEPTION: main
04-22 11:52:46.290: E/AndroidRuntime(426): java.lang.RuntimeException: Unable to start    activity ComponentInfo{org.assignment.timetable/org.assignment.timetable.Timetable}:   java.lang.NullPointerException
04-22 11:52:46.290: E/AndroidRuntime(426):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
04-22 11:52:46.290: E/AndroidRuntime(426):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
04-22 11:52:46.290: E/AndroidRuntime(426):  at android.app.ActivityThread.access$2300(ActivityThread.java:125)
04-22 11:52:46.290: E/AndroidRuntime(426):  at     android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
04-22 11:52:46.290: E/AndroidRuntime(426):  at android.os.Handler.dispatchMessage(Handler.java:99)
04-22 11:52:46.290: E/AndroidRuntime(426):  at android.os.Looper.loop(Looper.java:123)
04-22 11:52:46.290: E/AndroidRuntime(426):  at android.app.ActivityThread.main(ActivityThread.java:4627)
04-22 11:52:46.290: E/AndroidRuntime(426):  at java.lang.reflect.Method.invokeNative(Native Method)
04-22 11:52:46.290: E/AndroidRuntime(426):  at java.lang.reflect.Method.invoke(Method.java:521)
04-22 11:52:46.290: E/AndroidRuntime(426):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
04-22 11:52:46.290: E/AndroidRuntime(426):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
04-22 11:52:46.290: E/AndroidRuntime(426):  at dalvik.system.NativeStart.main(Native Method)
04-22 11:52:46.290: E/AndroidRuntime(426): Caused by: java.lang.NullPointerException
04-22 11:52:46.290: E/AndroidRuntime(426):  at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:291)
04-22 11:52:46.290: E/AndroidRuntime(426):  at android.widget.ListView.setAdapter(ListView.java:436)
04-22 11:52:46.290: E/AndroidRuntime(426):  at org.assignment.timetable.Timetable.onCreate(Timetable.java:25)
04-22 11:52:46.290: E/AndroidRuntime(426):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-22 11:52:46.290: E/AndroidRuntime(426):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
4

2 回答 2

1

你永远不会在你的类中初始化这个Modules字段,当你在适配器中使用它时,它会抛出你看到的那个。如果您在另一个活动中构建列表,然后尝试在活动中显示它,那么您必须从该活动(可能是活动)传递列表并在适配器中使用该列表。TimetableadaptModuleNullPointerExceptionModulesTimetableModulesAdd

有多种方法可以将其ArrayList从一个活动传递到另一个活动,您可以在 Stackoverflow 上查看更多示例,例如:

Android:如何将 ArrayList<object> 从一个活动传递到另一个活动

添加了小例子:

扩展的类Application

/**
 * The class that extends Application, and where we will store our ArrayList
 */
public class MyApplication extends Application {

    /**
     * This will hold your Modules list so we can access it from evry activity
     */
    private ArrayList<Module> mModules;

    /**
     * We will call this method when we want to store the list of modules(for
     * example when we finish adding elements to it(in the Add activity) and we
     * are switching to the Timetable activity)
     */
    public void setModulesList(ArrayList<Module> data) {
        this.mModules = data;
    }

    /**
     * Retrieve the list of modules and work with it(for example to display it
     * in the Timetable activity)
     */
    public ArrayList<Module> getModulesList() {
        return mModules;
    }
}

我们将元素添加到列表的活动Modules

public class AddActivity extends Activity {

    // local list of modules on which, in this activity, we will add elements
    private ArrayList<Module> items = new ArrayList<Module>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // simple layout with one Button that will get us to the Timetable
        // activity
        Button b = new Button(this);
        b.setText("I've put something in the Modules arrayList so go to the new activity");
        b.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // we are switching to the other activity so store the list of
                // modules in MyApplication
                ((MyApplication) getApplicationContext()).setModulesList(items);
                Intent i = new Intent(AddActivity.this, Timetable.class);
                startActivity(i);
            }
        });
        setContentView(b);
        // some dummy work, adding elements to the list of Modules.
        for (int i = 0; i < 12; i++) {
            items.add(new Module("Module " + i));
        }

    }
}

我们将在其中显示Modules先前创建的列表的活动AddActivity

public class Timetable extends ListActivity {

    // private field, that will hold a copy of the list from MyApplication
    private ArrayList<Module> mModules;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // retrieve the list of Modules from MyApplication
        mModules = ((MyApplication) getApplicationContext()).getModulesList();
        // it is possible to not have elements in the list at this time so just
        // create an
        // empty list so we don't throw exceptions
        if (mModules == null) {
            mModules = new ArrayList<Module>();
        }
        // set the adapter
        setListAdapter(new ArrayAdapter<Module>(this,
                android.R.layout.simple_list_item_1, mModules));
    }
}

为了让我们MyApplication工作,我们必须在清单中注册它(请参阅应用程序元素和添加的android:name标签):

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.luksprog.passit"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <application
        android:name=".MyApplication"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".AddActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Timetable"
            android:label="@string/app_name" >
        </activity>
    </application>

</manifest>

最后是Module课程:

/**
 * A small Module class. 
 *
 */
public class Module {

    String name;

    public Module(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        //This will show a nice string in the `ListView` 
        return "This is:" + name;
    }

}
于 2012-04-22T12:41:29.520 回答
0

在您的代码模块中没有初始化任何地方。私有 ArrayList 模块;

初始化它...

于 2012-04-22T11:53:39.823 回答