-2

ArrayAdapterを介して配列に保持されているデータを表示するために を使用して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を機能させるには、マニフェストに登録する必要があります (application 要素と追加された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 に答える