0

I want to load a spinner using data from SQLite database.But i couln't do it and i got error as follows.

12-11 13:05:39.206 2445-2445/com.ksfr.updatetest E/AndroidRuntime: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Spinner.setAdapter(android.widget.SpinnerAdapter)' on a null object reference
12-11 13:05:39.206 2445-2445/com.ksfr.updatetest E/AndroidRuntime:     at com.ksfr.updatetest.update_fragment02.loadToSpinner(update_fragment02.java:58)
12-11 13:05:39.206 2445-2445/com.ksfr.updatetest E/AndroidRuntime:     at com.ksfr.updatetest.update_fragment02.onCreateView(update_fragment02.java:47)

I put add a row at onCreate method in my database since i got a NullPointerException. Even though i couldn't solve my issue.

Here is my MyDBHandler.java class

package com.ksfr.updatetest;

/**
 * Created by User on 12/10/2015.
 */
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.content.Context;


public class MyDBHandler extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "schoolDB.db";
private static final String TABLE_SCHOOLS = "schools";

public static final String COLUMN_ID = "_id";
public static final String COLUMN_SCHOOLNAME = "schoolname";
public static final String COLUMN_SCHOOLADDRESS = "schooladdress";
public static final String COLUMN_SCHOOLTYPE = "schooltype";
public static final String COLUMN_LAT = "_lat";
public static final String COLUMN_LNG = "_lng";


public MyDBHandler(Context context, String name,
                   SQLiteDatabase.CursorFactory factory, int version) {
    super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}



@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_SCHOOLS_TABLE = "CREATE TABLE " +
            TABLE_SCHOOLS + "("+ COLUMN_ID + " INTEGER PRIMARY KEY," + COLUMN_SCHOOLNAME+" TEXT,"+COLUMN_SCHOOLADDRESS+
            " TEXT,"+COLUMN_SCHOOLTYPE+" TEXT,"+COLUMN_LAT+" DOUBLE,"+COLUMN_LNG+" DOUBLE"+")";
    db.execSQL(CREATE_SCHOOLS_TABLE);
//Here one item added to avoid to table getting empty.
    String add1= "INSERT INTO schools ('schoolname','schooladdress','schooltype','_lat','_lng') " +
            "VALUES ('Diyatalawa Central Collage','Diyatalawa','Primary school','2.564','5.6456')";
    db.execSQL(add1);
}


@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
                      int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_SCHOOLS);
    onCreate(db);
}

 * Getting all schools
 * returns list of schools
 * */
public List<String> getAllSchools(){

    List<String> school_list = new ArrayList<String>();
    // Select All Query
    String Query = "SELECT "+  COLUMN_SCHOOLNAME +" FROM " + TABLE_SCHOOLS;

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(Query, null);

    //School school = new School();
    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            school_list.add(cursor.getString(0));
        } while (cursor.moveToNext());
    }
    cursor.close();
    db.close();
    return school_list;
 }
}

In my fragment class as follows

public class update_fragment02 extends Fragment implements AdapterView.OnItemSelectedListener {


TextView schoolID,schoolName,address,latitude,longitude;
Spinner spinner_school;
Button button_e_edit,button_e_cancel;
String schoolSelect;
public static update_fragment02 newInstance() {
    update_fragment02 fragment = new update_fragment02();
    return fragment;
}

public update_fragment02(){
}

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

    schoolID =(TextView)rootView.findViewById(R.id.txtID02E);
    schoolName=(TextView)rootView.findViewById(R.id.txtName02E);
    address=(TextView)rootView.findViewById(R.id.txtAddress02E);
    latitude=(TextView)rootView.findViewById(R.id.txtLat02E);
    longitude=(TextView)rootView.findViewById(R.id.txtLng02E);

    spinner_school= (Spinner)rootView.findViewById(R.id.spinner);
    loadToSpinner();

    return rootView;
}

private void loadToSpinner(){
    MyDBHandler dbHandler =new MyDBHandler(getActivity(),null,null,1);
    List<String> schoolList = dbHandler.getAllSchools();
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<>(this.getActivity(),
            android.R.layout.simple_spinner_item, schoolList);
       dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner_school.setAdapter(dataAdapter);
    spinner_school.setOnItemSelectedListener(this);

}


@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
       schoolSelect= String.valueOf(parent.getItemAtPosition(position));
}

@Override
public void onNothingSelected(AdapterView<?> parent) {

 }
}
Kasun
  • 11
  • 2
  • just use `SimpleCursorAdapter` when your data model is sqlite db – pskink Dec 11 '15 at 08:18
  • Make sure you have a Spinner with ID `spinner` in your `update_tab_fab02`. NullPointer suggests that `spinner_school` is pointing to a null location – Kushal Sharma Dec 11 '15 at 08:24
  • does your update_tab_fab02.xml has Spinner with id spinner ? – Linh Nguyen Dec 11 '15 at 08:36
  • As I fairly scanned your code, You should have remove your if statement, put while instead and `moveToFirst()` with `moveToNext()` like `while (cursor.moveToNext()) { school_list.add(cursor.getString(0)); } cursor.close(); db.close(); return school_list; }` – Shree Krishna Dec 11 '15 at 08:42
  • @ShreeKrishna and instead of playing with Cursors, moveTo* methods etc, why not just to use a `SimpleCursorAdapter` ? – pskink Dec 11 '15 at 08:47
  • @pskink That will be better choice !!I – Shree Krishna Dec 11 '15 at 08:52
  • @ Kushal Sharma,@Linh Nguyen Yes,spinner is the id of spinner_school. – Kasun Dec 11 '15 at 19:17
  • @pskink Can you tell me how i can use SimpleCursorAdapter in my code. – Kasun Dec 11 '15 at 19:27
  • @Linh Nguyen yes I have an ID spinner for my Spinner. – Kasun Dec 11 '15 at 19:29
  • create a `SimpleCursorAdapter` instance and call `spinner_school.setAdapter(sca)` – pskink Dec 11 '15 at 19:33
  • @pskink My data getting from database through a List Array and that array called from a another list array at updata_fragment02. Can I use a String array in both places. – Kasun Dec 11 '15 at 19:55
  • @pskink What should i need to pass for two parameters for from and to in the SimpleCursorAdapter. like mCurAdapter = new SimpleCursorAdapter(view.getContext(),android.R.layout.simple_list_item_1,mNotesCursor,from,to,0); – Kasun Dec 11 '15 at 20:03
  • read the documentation of SimpleCursorAdapter or use google for a sample code – pskink Dec 11 '15 at 20:09

0 Answers0