0
votes

My activity holding the spinner is crashing when I open it, any ideas on how i could fix this?

The code used from the DB helper looks like this:

public List<String> getAllNames() {
    List<String> retData = new ArrayList<String>();
    String selectQuery = "SELECT name FROM sqlite_master WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%' and name <> 'ViewWorkout' ORDER BY 1";
    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    if (cursor.moveToFirst()) {
        do {
            retData.add(cursor.getString(0));
        } while (cursor.moveToNext());
    }
    return retData;
}

The code used to call the returned list into the spinner looks like this:

public class SelectWorkoutActivity extends AppCompatActivity {

    DBHelper DB;
    Spinner Workout_list;

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

        DB = new DBHelper(this);
        List<String> Workouts = DB.getAllNames();

        //Set Adapter on the spinner
        Workout_list.setAdapter(new ArrayAdapter<>(SelectWorkoutActivity.this
                , android.R.layout.simple_spinner_dropdown_item,Workouts));
    }
}

Any help would be greatly appreciated

1

1 Answers

0
votes

You need to instantiate the spinner otherwise it will be null resulting in a Null Pointer Exception (NPE) and a crash.

So

public class SelectWorkoutActivity extends AppCompatActivity {

    DBHelper DB;
    Spinner Workout_list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_workout);
        Workout_list = this.findViewById(R.id.???????); //<<<<<<<<<< ADDED (see note)

        DB = new DBHelper(this);
        List<String> Workouts = DB.getAllNames();

        //Set Adapter on the spinner
        Workout_list.setAdapter(new ArrayAdapter<>(SelectWorkoutActivity.this
                , android.R.layout.simple_spinner_dropdown_item,Workouts));
    }
}
  • Note replace ??????? with the id assigned in the layout activity_select_workout/xml

Here's a working demonstrating the Spinner working:-

The layout used for the activity (with just the spinner) :-

<?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">

    <Spinner
        android:id="@+id/workout_list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </Spinner>

</LinearLayout>
  • note the id assigned to the spinner as per android:id="@+id/workout_list"

And the activity :-

public class MainActivity extends AppCompatActivity {

    //DBHelper DB; //commented out for demo
    Spinner Workout_list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_workout);
        Workout_list = this.findViewById(R.id.workout_list); //<<<<< ADDED

        //DB = new DBHelper(this); //commented out for demo
        /* List built from hardcoded items for demo */
        List<String> Workouts = Arrays.asList(new String[]{"Item1", "Item2", "Item3"});

        //Set Adapter on the spinner
        Workout_list.setAdapter(new ArrayAdapter<>(this /*<<<<< changed for demo */
                , android.R.layout.simple_spinner_dropdown_item, Workouts));

    }
}

Result :-

enter image description here

Without instantiation of the Spinner the you get the NPE (null pointer exception) :-

2021-12-10 05:49:39.460 5361-5361/? D/AndroidRuntime: Shutting down VM
2021-12-10 05:49:39.462 5361-5361/? E/AndroidRuntime: FATAL EXCEPTION: main
    Process: a.a.so70292623javaspinner, PID: 5361
    java.lang.RuntimeException: Unable to start activity ComponentInfo{a.a.so70292623javaspinner/a.a.so70292623javaspinner.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Spinner.setAdapter(android.widget.SpinnerAdapter)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Spinner.setAdapter(android.widget.SpinnerAdapter)' on a null object reference
        at a.a.so70292623javaspinner.MainActivity.onCreate(MainActivity.java:28)
        at android.app.Activity.performCreate(Activity.java:7136)
        at android.app.Activity.performCreate(Activity.java:7127)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:193) 
        at android.app.ActivityThread.main(ActivityThread.java:6669) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 
2021-12-10 05:49:39.466 1943-4597/system_process W/ActivityManager:   Force finishing activity a.a.so70292623javaspinner/.MainActivity

If you look at the log in Android Studio you will see that it has a link to the respective code e.g.

enter image description here

If you click on the link and add a break point on offending the line and then use the debug option (green bug icon) e.g.

enter image description here

The code will stop at the line and the debugger window will appear, showing that Workout_list is null:-

enter image description here

See more about debugging at https://developer.android.com/studio/debug/