I have a table in the database called PrimaryData Which includes fields are PrimaryDataId and PrimaryDataCode .My problem is,When the cursor returns data from database ,Spinner does not set the values of the cursor.
xml spinner file
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="14sp"
android:textColor= "#000000"
android:spinnerMode="dialog" />
PrimaryData class in which to put PrimaryDataId and PrimaryDataCode. This class is the equivalent of a database table.
package com.example.proposaldashborad;
public class PrimeryData {
private int primeryDataId;
private String primeryDataCode;
@Override
public String toString() {
return this.primeryDataCode; // What to display in the Spinner list.
}
public int getPrimaryDataId() {
return primeryDataId;
}
public void setPrimaryDataId(int value) {
this.primeryDataId = value;
}
public int getPrimaryDataCode() {
return primeryDataId;
}
public void setPrimaryDataCode(String value) {
this.primeryDataCode = value;
}
}
this code fill Spinner
private void GetPrimaryDataForSpinner(String primaryDataName, Cursor cr) {
cr.moveToFirst();
//array_spinner = new String[cr.getCount()];
ArrayList<PrimeryData> pds = new ArrayList<PrimeryData>() ;
do {
//array_spinner[i] = cr.getString(cr.getColumnIndex("PrimeryDataCode"));
PrimeryData pd = new PrimeryData() ;
pd.setPrimaryDataId(cr.getInt(cr.getColumnIndex("PrimeryDataId")));
pd.setPrimaryDataCode(cr.getString(cr.getColumnIndex("PrimeryDataCode")));
pds.add(pd) ;
} while (cr.moveToNext());
cr.close();
if (primaryDataName == "Admin") {
adapterAdmin = new ArrayAdapter<PrimeryData>(this,R.layout.spinner, pds);
sAdmin = (Spinner) findViewById(R.id.spinnerAdmin);
sAdmin.setAdapter(adapterAdmin);
}
}
And this is my code when data is returned from the database.
private Spinner sAdmin;
private ArrayAdapter<PrimeryData> adapterAdmin;
db = new DBAdapter(getApplicationContext());
db.open();
cr = db.getViewMT26(entityID);
cr.moveToFirst();
if(cr.getCount()>0) {
PrimeryData pd = new PrimeryData();
pd.setPrimaryDataId(cr.getInt(cr.getColumnIndex("AdminId")));
pd.setPrimaryDataCode(cr.getString(cr.getColumnIndex("Admin")));
sAdmin.setSelection(adapterAdmin.getPosition(pd));
}
cr.close();
db.close();
My main question is why
adapterAdmin.getPosition (pd));
Returns -1?
You have to initialize your adapterAdmin, and set this to your spinner by setAdapter method. Furthermore, if you only using a list of PrimeryData, then the text which is displayed on each spinner item will be PrimeryData (instance) toString().