如何将微调器的选定项保存(以及稍后检索)到SQLite

时间:2013-08-27 16:06:44

标签: android sqlite spinner

好吧......我受够了。

我非常沮丧。

所以我宁愿寻求帮助而不是新的显示器。

......这些都非常贵。

长话短说......我有一个数据库。还有一张桌子。

private String DEFINE_PROP_TYPES = "CREATE TABLE " + TABLE_PROP_TYPES + "("
        + TABLE_ID + " INTEGER PRIMARY KEY, "
        + TABLE_PROP_TYPE_NAME + " TEXT NOT NULL"
        + ")";

引入“适配器”类以便管理它。

public abstract class DBAdapter 
{
    static public final String C_COLUMN_ID = "_id";

    protected Context context;
    protected DBHelper dbHelper;
    protected SQLiteDatabase db;
    protected String managedTable;
    protected String[] columns;

    public String getTableManaged() 
    {
        return managedTable;
    }

    public void setTableManaged(String managedTable) 
    {
        this.managedTable = managedTable;
    }

    public void setColumns(String[] columns)
    {
        this.columns = columns;
    }

    public DBAdapter(Context context)
    {
        this.context = context;
    }

    public void close()
    {
        dbHelper.close();
    }

    public DBAdapter open() throws SQLException
    {
        dbHelper = new DBHelper(context);
        db = dbHelper.getWritableDatabase();
        return this;
    }

    public Cursor getList()
    {
        Cursor c = db.query(true, managedTable, columns, null, null, null, null, null, null);

        return c;       
    }

    public long insert(ContentValues reg)
    {
        return 0;
    }
}
public class PropTypesDBAdapter extends DBAdapter
{
    static public final String C_TABLE_PROP_TYPES = "PROP_TYPES";

    static public final String C_COLUMN_ID = "_id",
        C_COLUMN_PROP_TYPES_NAME = "re_prop_type";

    public PropTypesDBAdapter(Context context)
    {
        super(context);
        this.setTableManaged(C_TABLE_PROP_TYPES);
        this.setColumns(new String[] { C_COLUMN_ID,
            C_COLUMN_PROP_TYPES_NAME });
    }

    public long insert(ContentValues reg)
    {
        if (db == null)
        {
            open();
        }

        return db.insert(C_TABLE_PROP_TYPES, null, reg);
    }
}

除了这堆可爱的我还有活动课。

使用微调器。

public class PropDetailActivity extends Activity implements LocationListener
{
    // insert here some blah-blah constants not needed by spinners

    private PropDBAdapter mHouses;
    private RatingsDBAdapter mRatings;
    private PropTypesDBAdapter mPropTypes;
    private Cursor mCursorHouses, 
        mCursorRatings,
        mCursorPropTypes;

    long mPropType;

    private long mPropId;

    private Spinner spinnerRating, spinnerType;
    AdapterView.OnItemSelectedListener spnLstPropType, spnLstRating;

    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_house_detail);

        Intent intent = getIntent();
        Bundle extra = intent.getExtras();

        if (extra == null)
        {
            return;
        }

        // Figure all view widgets being retrieved here, including...

        spinnerRating = (Spinner) findViewById(R.id.spinnerRating);
        spinnerType = (Spinner) findViewById(R.id.spinnerType);

        // Create adapter and cursor-y things here

        mHouses = new PropDBAdapter(this);
        mHouses.open();

        // And now, for the juicy, deliciously irritating stuff:

        String[] from = new String[] { PropTypesDBAdapter.C_COLUMN_PROP_TYPES_NAME };

        int[] to = new int[] { android.R.id.text1 };

        mPropTypes = new PropTypesDBAdapter(this);
        mPropTypes.open();

        mCursorPropTypes = mPropTypes.getList();

        @SuppressWarnings("deprecation")
        SimpleCursorAdapter adapterPropTypes = new SimpleCursorAdapter(this, 
                android.R.layout.simple_spinner_item, 
                mCursorPropTypes, 
                from,       /*new String[] { RatingsDBAdapter.C_COLUMN_RATING_NAME }, */
                to);        /*new int[] { android.R.id.text1 } */

        adapterPropTypes.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        spinnerType.setAdapter(adapterPropTypes);

        spinnerRating.setSelection(pos);

        spnLstPropType = new AdapterView.OnItemSelectedListener()
        {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                    int pos, long id) 
            {
                mPropType = id;
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) { }
        };
        spinnerType.setOnItemSelectedListener(spnLstPropType);

    private int getItemPositionById(Cursor c, long id, DBAdapter adapter)
    {
        for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext())
        {
            if (c.getLong(c.getColumnIndex(DBAdapter.C_COLUMN_ID)) == id)
            {
                return c.getPosition();
            }
        }

        return 0;
    } 

    private void query(long id) 
    {
        mCursorHouses = mHouses.getRecord(id);

        // Figure values being retrieved and set on their widgets instead of this comment... and now...

        mPropType = mCursorHouses.getInt(mCursorHouses.getColumnIndex(PropDBAdapter.C_PROP_TYPE_ID));

        spinnerType.setSelection(
            getItemPositionById(
                    mCursorRatings, 
                    mCursorHouses.getColumnIndex(PropDBAdapter.C_PROP_TYPE_ID),
                    mPropTypes
                )
            );

    private void save() 
    {
        ContentValues reg = new ContentValues();

        // Read: values being put into 'reg'... eventually it should reach this:

        reg.put(PropDBAdapter.C_PROP_TYPE_ID, mPropType);

        try
        {
            if (mFormMode == PropListActivity.C_CREATE)
            {
                mHouses.insert(reg);
                Toast.makeText(PropDetailActivity.this, R.string.house_create_notice, Toast.LENGTH_LONG).show();
            }
            else if (mFormMode == PropListActivity.C_EDIT)
            {
                Toast.makeText(PropDetailActivity.this, R.string.house_edit_notice, Toast.LENGTH_LONG).show();

                reg.put(PropDBAdapter.C_COLUMN_ID, mPropId);

                long resultCode = mHouses.update(reg);
                Log.i(this.getClass().toString(), "Database operation result code: " + resultCode);         
            }
        }
        catch(SQLException e)
        {
            Log.i(this.getClass().toString(), e.getMessage());
        }

        setResult(RESULT_OK);
        finish();
    }
}   

Spinners是坏男孩。 懒惰坏男孩。

他们确实加载了数据 - 房地产属性类型列表 - 它们是要显示的。

经过一些打屁股,就是这样。

但是,希望他们将您选择的值保存到SQLite?并且当从数据库中取回东西时显示 THAT EXACT VALUE

哦,不,不,不怎么样。

他们固执地坚持在活动启动时始终显示相同的值。

所以......请...我必须利用你的集体智慧来为项目保存我的抱歉借口...

Pleasepleaseplease? :)

IF 你想深入研究整个未切割的代码,这里有一个GIT存储库:https://github.com/CruxMDQ/Quoterv3

2 个答案:

答案 0 :(得分:2)

检查您的代码,我认为我发现了问题,请在query中的PopDetailActivity.java方法中更改以下行。
spinnerRating执行:

spinnerRating.setSelection(
    getItemPositionById(
        mCursorRatings, 
        mCursorHouses.getInt(mCursorHouses.getColumnIndex(PropDBAdapter.C_PROP_RATING_ID)),
        mRatings
    )
);

spinnerType执行:

spinnerType.setSelection(
    getItemPositionById(
        mCursorPropTypes, 
        mCursorHouses.getInt(mCursorHouses.getColumnIndex(PropDBAdapter.C_PROP_TYPE_ID)),
        mPropTypes
    )
);

编辑:

在您的查询方法中,您通过调用mPropTypeId初始化getItemPositionById(),但在该调用中,第一个参数应为mCursorPropTypes而不是mCursorHouses

答案 1 :(得分:0)

一些事情:

(1)我实际上并没有看到您实际创建SQLite数据库的位置或使用SQLiteOpenHelper类来访问该数据。看看this tutorial。它使用一个简单的单表设置来存储数据。创建数据库后,应该可以轻松地从中读取和写入数据库。确认您确实已创建数据库。

(2)您的SQL查询在哪里返回您要查找的数据?即使添加了数据,您也需要确保在完成后使用Cursor获取正确的数据。如果你每次都得到相同的值,你可能每次只是添加新数据并用光标检索相同的值 - 即你没有告诉光标获取新添加的数据,因为你继续抓取相同的指数?

如果您需要替换那里的数据,您应该使用更新查询而不是插入。