【问题标题】:Second Spinner result is based on First Spinner selection from Sqlite(Magic Code)第二个 Spinner 结果基于 Sqlite(Magic Code) 中的 First Spinner 选择
【发布时间】:2018-03-19 15:30:24
【问题描述】:

我有一张有两列(id、name)的表。 Toast 应该在从 spinner 中选择 id 时显示来自 sqlite 的“名称”详细信息。

例如:Sqlite 表 1,899,Chris 和 2,890,David。

每当我从微调器中选择值 899 时,Toast 应显示 Chris,如果我选择微调器 890,则 Toast 应显示 David。需要建议。

代码:SpinnerEx4Activity.Java

package com.bar.example.androidspinnerexample;



import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Toast;
import android.support.v7.app.AppCompatActivity;

import android.database.sqlite.SQLiteDatabase;

import android.widget.Button;
import android.widget.CheckBox;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.SimpleCursorAdapter;
import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.content.Intent;
import java.util.HashMap;
import java.util.List;
import android.view.View.OnClickListener;
import android.util.Log;
import android.widget.TextView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.EditText;
import java.util.LinkedList;
import android.view.inputmethod.InputMethodManager;
public class SpinnerEx4Activity extends Activity implements
    AdapterView.OnItemSelectedListener {
Spinner s1,s2;
Button btnAdd;
EditText inputLabel;
DatabaseHandler dbhndlr;        //<<<<< Single instance for Database handler
Cursor spinner1csr;
Cursor spinner2csr;   //<<<<< Cursor for spinner (close in onDestroy)



 @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_spinner_ex4);
        s1 = (Spinner)findViewById(R.id.spinner1);
        s2 = (Spinner)findViewById(R.id.spinner2);
        btnAdd = (Button) findViewById(R.id.btn_add);
        s1.setOnItemSelectedListener(this);
        dbhndlr = new DatabaseHandler(this);    //<<<< Instantiate Databasehandler
        //loadSpinnerData();                            //<<<< commented out


        altLoadSpinnerData();
        altLoadSpinnerData1();//<<<< Load via cursor
        btnAdd.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                String label = inputLabel.getText().toString();

                if (label.trim().length() > 0) {
                    // database handler commeneted out, use dbhndlr instance instead
                    // inserting new label into database
                    dbhndlr.insertLabel(label);

                    // making input filed text to blank
                    inputLabel.setText("");

                    // Hiding the keyboard
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(inputLabel.getWindowToken(), 0);

                    // loading spinner with newly added data
                    //loadSpinnerData();                    //<<<< commeneted out
                    altLoadSpinnerData();
                    altLoadSpinnerData1();
                } else {
                    Toast.makeText(getApplicationContext(), "Please enter label name",
                            Toast.LENGTH_SHORT).show();
                }

            }
        });


    }
    // New method to utilise Cursor adapter
    private void altLoadSpinnerData() {
        spinner1csr = dbhndlr.getAllLabelsAsCursor();
        SimpleCursorAdapter sca = new SimpleCursorAdapter(this,
                android.R.layout.simple_list_item_1, // Layout to show 2 items
                spinner1csr, // Cursor
                new String[]{DatabaseHandler.KEY_NAME},
                new int[]{android.R.id.text1},// Views into which data is shown
                0
        );
              s1.setAdapter(sca);
    }
    private void altLoadSpinnerData1 () {
        // get the cursor
        spinner2csr = dbhndlr.getAllLabelsAsCursor();
        // Instantiaie Simple Cursor Adapter
        SimpleCursorAdapter sca = new SimpleCursorAdapter(this,
                android.R.layout.simple_list_item_2, // Layout to show 2 items
                spinner2csr, // Cursor
                new String[]{DatabaseHandler.KEY_ID}, // Source data
                new int[]{android.R.id.text2}, // Views into which data is shown
                0
        );
        s2.setAdapter(sca);
        s2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(parent.getContext(),
                        "You Selected: " + id + " " +
                                spinner2csr.getString(
                                        spinner2csr.getColumnIndex(DatabaseHandler.KEY_ID)),
                        Toast.LENGTH_SHORT

                ).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // TODO Auto-generated method stub
            }
        });
}}

还有Databasehandler.java

package com.bar.example.androidspinnerexample;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHandler extends SQLiteOpenHelper {
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "spinnerExample";

    // Labels table name
    private static final String TABLE_LABELS = "labels";

    // Labels Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";

    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        // Category table create query
        String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + TABLE_LABELS + "("
                + KEY_ID + " TEXT," + KEY_NAME + " TEXT)";
        db.execSQL(CREATE_CATEGORIES_TABLE);
    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS);

        // Create tables again
        onCreate(db);
    }

    /**
     * Inserting new lable into lables table
     * */
    public void insertLabel(String label){
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_NAME, label);

        // Inserting Row
        db.insert(TABLE_LABELS, null, values);
        db.close(); // Closing database connection
    }

    /**
     * Getting all labels
     * returns list of labels
     * */
    public List<String> getAllLabels(){
        List<String> labels = new ArrayList<String>();

        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_LABELS;

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

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                labels.add(cursor.getString(0));
            } while (cursor.moveToNext());
        }

        // closing connection
        cursor.close();
        db.close();

        // returning lables
        return labels;
    }
}

而activity_spinner_ex4.xml是

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <!-- Label -->

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="8dip"
        android:text="@string/lblAcc" />

    <!-- Spinner Dropdown -->

    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dip"
        android:layout_marginRight="8dip"
        android:layout_marginTop="10dip"
         />

    <!-- Select Label -->

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="8dip"
        android:text="@string/lblSubAcc" />

    <!-- Spinner Dropdown -->
    <Spinner
        android:id="@+id/spinner2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dip"
        android:layout_marginLeft="8dip"
        android:layout_marginRight="8dip"
        />


    <EditText android:id="@+id/input_label"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dip"
        android:layout_marginRight="8dip"/>

    <!-- Add Button -->
    <Button android:id="@+id/btn_add"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Add Label"
        android:layout_marginLeft="8dip"
        android:layout_marginTop="8dip"/>
</LinearLayout>

将微调器和复选框值插入另一个表。 我能够插入所有数据。但所有复选框文本都在保存而不是选中一个。你能帮忙吗?

主要活动。

 btnAdd.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg0) {
                        //String label = inputLabel.getText().toString();
                    String SaveString="No";

                    DatabaseHandler db = new DatabaseHandler(getApplicationContext());
                    String message1= ((Cursor) s1.getSelectedItem()).getString(2);
                    String message2= ((Cursor) s2.getSelectedItem()).getString(1);
                    String message = inputLabel.getText().toString();
                   // String message1 = s1.getSelectedItem().toString();
                   // String message2 = s2.getSelectedItem().toString();
                    String message10 = s3.getSelectedItem().toString();
                    String message4 = ck1.getText().toString();
                    String message5 = ck2.getText().toString();
                    String message6 = ck3.getText().toString();
                    String message7 = ck4.getText().toString();
                    String message9 = ck6.getText().toString();
                    String message3 = ck7.getText().toString();
                    String message8 = ck8.getText().toString();
                    db.insertLabel(message1,message2,message5,message6,message7,message9,message3,message4,message8,message10);

                    if (ck1.isChecked())
                    { SaveString="Yes";
                    }
                    else
                    {  SaveString="No";
                    }

                    if (ck2.isChecked())
                    { SaveString="Yes";
                    }
                    else
                    {  SaveString="No";
                    }

                    if (message.trim().length() > 0) {
                        // database handler commeneted out, use dbhndlr instance instead
                        // inserting new label into database


                        // making input filed text to blank
                        inputLabel.setText("");

                        // Hiding the keyboard
                        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.hideSoftInputFromWindow(inputLabel.getWindowToken(), 0);

                        // loading spinner with newly added data
                        spinner1csr = dbhndlr.getAllLabelsAsCursor();
                        spinner2csr = dbhndlr.getByRowid(spinner1_selected);
                        sca.swapCursor(spinner1csr);
                        sca2.swapCursor(spinner2csr);
                    } else {
                        Toast.makeText(getApplicationContext(), "Please enter label name",
                                Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }

数据库。

     public void insertLabel(String message1, String message2,String message3,String message4,String message5,String message6,String message7,String message8,String message9,String message10){
            SQLiteDatabase db = this.getWritableDatabase();

            ContentValues values = new ContentValues();

            values.put(KEY_1, message1);
            values.put(KEY_2, message2);
            values.put(KEY_10,message10);
            values.put(KEY_3,message3);
            values.put(KEY_4,message4);
            values.put(KEY_5,message5);
            values.put(KEY_6,message6);
            values.put(KEY_7,message7);
            values.put(KEY_9,message9);

            values.put(KEY_8,message8);


            // Inserting Row
            db.insert(TABLE_LABELS2, null, values);
            db.close(); // Closing database connection
        }

【问题讨论】:

  • 使用 where 子句
  • 您好 Zoe,感谢您的建议。您能否根据您的专业知识按照以下场景分享 where 子句语句..

标签: android android-sqlite


【解决方案1】:

替代/改进的 SpinnerEx4Activity.Java

public class SpinnerEx4Activity extends Activity {
    Spinner s1,s2;
    Button btnAdd;
    EditText inputLabel;
    DatabaseHandler dbhndlr;
    Cursor spinner1csr, spinner2csr;
    SimpleCursorAdapter sca, sca2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        s1 = (Spinner)findViewById(R.id.spinner1);
        s2 = (Spinner)findViewById(R.id.spinner2);
        btnAdd = (Button) findViewById(R.id.btn_add);
        inputLabel = (EditText) findViewById(R.id.input_label);
        dbhndlr = new DatabaseHandler(this);

        // If no data in database then load data for testing purposes only
        if (DatabaseUtils.queryNumEntries(
                dbhndlr.getWritableDatabase(),
                DatabaseHandler.TABLE_LABELS) < 1)
        {
            dbhndlr.insertlabel("899","Chris");
            dbhndlr.insertlabel("890","David");
        }

        // Get Cursors for Spinners
        spinner1csr = dbhndlr.getAllLabelsAsCursor();
        spinner2csr = dbhndlr.getAllLabelsAsCursor();

        //Setup Adapter for Spinner 1
        sca = new SimpleCursorAdapter(this,
                android.R.layout.simple_list_item_1,spinner1csr,
                new String[]{DatabaseHandler.KEY_ID},
                new int[]{android.R.id.text1},
                0
        );
        //Steup Adapter for Spinner2
        sca2 = new SimpleCursorAdapter(this,
                android.R.layout.simple_list_item_1,
                spinner2csr,
                new String[]{DatabaseHandler.KEY_NAME},
                new int[]{android.R.id.text1},
                0
        );
        // Set the Adapters to the Spinners
        s1.setAdapter(sca);
        s2.setAdapter(sca2);
        // Set Spinner1 OnSelectedItemListener
        s1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(parent.getContext(),
                        "You Selected: " + id + " - " +
                                spinner1csr.getString(
                                        spinner1csr.getColumnIndex(DatabaseHandler.KEY_NAME)),
                        Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        // Set Spinner2 OnSelectedItemListener
        s2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(parent.getContext(),
                        "You Selected: " + id + " " +
                                spinner2csr.getString(
                                        spinner2csr.getColumnIndex(DatabaseHandler.KEY_ID)),
                        Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        btnAdd.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                String label = inputLabel.getText().toString();

                if (label.trim().length() > 0) {
                    // database handler commeneted out, use dbhndlr instance instead
                    // inserting new label into database
                    dbhndlr.insertLabel(label);

                    // making input filed text to blank
                    inputLabel.setText("");

                    // Hiding the keyboard
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(inputLabel.getWindowToken(), 0);

                    // loading spinner with newly added data
                    //loadSpinnerData();                    //<<<< commeneted out
                    spinner1csr = dbhndlr.getAllLabelsAsCursor();
                    spinner2csr = dbhndlr.getAllLabelsAsCursor();
                    sca.swapCursor(spinner1csr);
                    sca2.swapCursor(spinner2csr);
                    //altLoadSpinnerData();
                    //altLoadSpinner2Data();
                } else {
                    Toast.makeText(getApplicationContext(), "Please enter label name",
                            Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

注意事项

  • 不再实现 AdapterView.OnItemSelectedListener
  • 不再创建新的适配器实例重用现有的适配器
  • 由于上述原因,使用 adapter.swapCursor(new_cursor) 使微调器与输入的数据保持同步。
  • 第一个 Spinner 将显示空白行,第二个将导致 Toast 显示 id 后跟 bu null。
    • 以上都是因为在输入新标签时,没有分配 ID(不是 rowid)。由于仅使用 'dbhndlr.insertLabel(label);' 添加因此 KEY_ID 列为空。我不知道您如何将 ID 分配给标签(名称)。但是,请注意我是如何创建了一个替代的 insertlabel 方法,该方法采用 ID 和 NAME/LABEL 参数。

根据评论修改

我现在在这里谈论选择微调器 s1 值(例如:123)然后 微调器 s2 应该根据表格不同的值(Mike Trae)。

即微调器应排除另一个微调器中的选定值(微调器是相互依赖的)

  • 注意!我更改为在两个微调器中显示名称,因为 id 可能为空且令人困惑(请参阅前面的注释)

SpinnerEx4Activity

​​>
public class SpinnerEx4Activity extends Activity {
    Spinner s1,s2;
    Button btnAdd;
    EditText inputLabel;
    DatabaseHandler dbhndlr;
    Cursor spinner1csr, spinner2csr;
    SimpleCursorAdapter sca, sca2;
    long spinner1_selected = 0, spinner2_selected = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        s1 = (Spinner)findViewById(R.id.spinner1);
        s2 = (Spinner)findViewById(R.id.spinner2);
        btnAdd = (Button) findViewById(R.id.btn_add);
        inputLabel = (EditText) findViewById(R.id.input_label);
        dbhndlr = new DatabaseHandler(this);

        // If no data in database then load data for testing purposes only
        if (DatabaseUtils.queryNumEntries(
                dbhndlr.getWritableDatabase(),
                DatabaseHandler.TABLE_LABELS) < 1)
        {
            dbhndlr.insertlabel("899","Chris");
            dbhndlr.insertlabel("890","David");
        }

        // Get Cursors for Spinners
        spinner1csr = dbhndlr.getAllLabelsExceptedSelected(spinner2_selected);
        //Setup Adapter for Spinner 1
        sca = new SimpleCursorAdapter(this,
                android.R.layout.simple_list_item_1,spinner1csr,
                new String[]{DatabaseHandler.KEY_NAME},
                new int[]{android.R.id.text1},
                0
        );

        // Set the Adapters to the Spinners
        s1.setAdapter(sca);
        // Set Spinner1 OnSelectedItemListener
        s1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(parent.getContext(),
                        "You Selected: " + id + " - " +
                                spinner1csr.getString(
                                        spinner1csr.getColumnIndex(DatabaseHandler.KEY_NAME)) +
                                " - " + spinner1csr.getString(spinner1csr.getColumnIndex(DatabaseHandler.KEY_ID))
                        ,
                        Toast.LENGTH_SHORT).show();
                spinner1_selected = id;
                spinner2csr = dbhndlr.getAllLabelsExceptedSelected(spinner1_selected);
                sca2.swapCursor(spinner2csr);
            }

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

        //Steup Adapter for Spinner2
        spinner2csr = dbhndlr.getAllLabelsExceptedSelected(spinner1_selected);
        sca2 = new SimpleCursorAdapter(this,
                android.R.layout.simple_list_item_1,
                spinner2csr,
                new String[]{DatabaseHandler.KEY_NAME},
                new int[]{android.R.id.text1},
                0
        );
        s2.setAdapter(sca2);
        // Set Spinner2 OnSelectedItemListener
        s2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(parent.getContext(),
                        "You Selected: " + id + " - " +
                                spinner2csr.getString(
                                        spinner2csr.getColumnIndex(DatabaseHandler.KEY_NAME)) +
                                " - " + spinner2csr.getString(spinner2csr.getColumnIndex(DatabaseHandler.KEY_ID)),
                        Toast.LENGTH_SHORT).show();
                spinner2_selected = id;
                spinner1csr = dbhndlr.getAllLabelsExceptedSelected(spinner2_selected);
                sca.swapCursor(spinner1csr);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        btnAdd.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                String label = inputLabel.getText().toString();

                if (label.trim().length() > 0) {
                    // database handler commeneted out, use dbhndlr instance instead
                    // inserting new label into database
                    dbhndlr.insertLabel(label);

                    // making input filed text to blank
                    inputLabel.setText("");

                    // Hiding the keyboard
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(inputLabel.getWindowToken(), 0);

                    // loading spinner with newly added data
                    //loadSpinnerData();                    //<<<< commeneted out
                    spinner1csr = dbhndlr.getAllLabelsExceptedSelected(spinner2_selected);
                    spinner2csr = dbhndlr.getAllLabelsExceptedSelected(spinner1_selected);
                    sca.swapCursor(spinner1csr);
                    sca2.swapCursor(spinner2csr);
                    //altLoadSpinnerData();
                    //altLoadSpinner2Data();
                } else {
                    Toast.makeText(getApplicationContext(), "Please enter label name",
                            Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    public void onDestroy() {
        spinner1csr.close();
        spinner2csr.close();
        super.onDestroy();
    }
}

数据库处理程序

public class DatabaseHandler extends SQLiteOpenHelper {
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    public static final String DATABASE_NAME = "spinnerExample";

    // Labels table name
    public static final String TABLE_LABELS = "labels"; //<<<< Made public

    // Labels Table Columns names
    public static final String KEY_ID = "id";           //<<<< Made public
    public static final String KEY_NAME = "name";       //<<<< made public

    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        // Category table create query
        String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + TABLE_LABELS + "("
                + KEY_ID + " TEXT," + KEY_NAME + " TEXT)";
        db.execSQL(CREATE_CATEGORIES_TABLE);
    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS);

        // Create tables again
        onCreate(db);
    }

    /**
     * Inserting new lable into lables table
     * */
    public void insertLabel(String label){
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_NAME, label);

        // Inserting Row
        db.insert(TABLE_LABELS, null, values);
        db.close(); // Closing database connection
    }

    // Added for adding new data
    public void insertlabel(String id, String label) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put(KEY_ID,id);
        cv.put(KEY_NAME,label);
        db.insert(TABLE_LABELS,null,cv);
        db.close();
    }

    // Added to get Cursor for Simple CursorAdapter
    public Cursor getAllLabelsAsCursor() {
        String[] columns = new String[]{"rowid AS _id, *"}; // Need _id column for SimpleCursorAdapter
        return this.getWritableDatabase().query(TABLE_LABELS,columns,null,null,null,null,null);
    }

    public Cursor getAllLabelsExceptedSelected(long selected) {
        String[] columns = new String[]{"rowid AS _id, *"};
        String whereclause = "rowid <> ?";
        String[] whereargs = new String[]{String.valueOf(selected)};
        return this.getWritableDatabase().query(TABLE_LABELS,
                columns,
                whereclause,
                whereargs,
                null,
                null,
                null
        );
    }
}

cmets 后的修改:-

但我只希望它是单向的 Spinner1 选择第一 列(数据库)应显示在微调器 2(第二列)数据库中。

不需要从微调器 2 到微调器。

1.另请注意,我的表有 1000 个数据*(行)*。

例如:数据库: { dbhndlr.insertlabel("9001234","Chris") dbhndlr.insertlabel("9001235","Cdedd"); dbhndlr.insertlabel("9003457","Dcdtt"); dbhndlr.insertlabel("9001231","Chrdis"); dbhndlr.insertlabel("9003451","Ddavid");}

例如:如果微调器 1 选择 9001231,则微调器 2 应显示 Chrdis,如果微调器 1 选择 9001234,则微调器 2 应显示 Chris。

1) 向 Databasehandler.java 添加了新方法 getByRowid :-

public class DatabaseHandler extends SQLiteOpenHelper {
    // Database Version
    public static final int DATABASE_VERSION = 1;

    // Database Name
    public static final String DATABASE_NAME = "spinnerExample";

    // Labels table name
    public static final String TABLE_LABELS = "labels"; //<<<< Made public

    // Labels Table Columns names
    public static final String KEY_ID = "id";           //<<<< Made public
    public static final String KEY_NAME = "name";       //<<<< made public

    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        // Category table create query
        String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + TABLE_LABELS + "("
                + KEY_ID + " TEXT," + KEY_NAME + " TEXT)";
        db.execSQL(CREATE_CATEGORIES_TABLE);
    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS);

        // Create tables again
        onCreate(db);
    }

    /**
     * Inserting new lable into lables table
     * */
    public void insertLabel(String label){
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_NAME, label);

        // Inserting Row
        db.insert(TABLE_LABELS, null, values);
        db.close(); // Closing database connection
    }

    // Added for adding new data
    public void insertlabel(String id, String label) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put(KEY_ID,id);
        cv.put(KEY_NAME,label);
        db.insert(TABLE_LABELS,null,cv);
        db.close();
    }

    // Added to get Cursor for Simple CursorAdapter
    public Cursor getAllLabelsAsCursor() {
        String[] columns = new String[]{"rowid AS _id, *"}; // Need _id column for SimpleCursorAdapter
        return this.getWritableDatabase().query(TABLE_LABELS,columns,null,null,null,null,null);
    }

    public Cursor getAllLabelsExceptedSelected(long selected) {
        String[] columns = new String[]{"rowid AS _id, *"};
        String whereclause = "rowid <> ?";
        String[] whereargs = new String[]{String.valueOf(selected)};
        return this.getWritableDatabase().query(TABLE_LABELS,
                columns,
                whereclause,
                whereargs,
                null,
                null,
                null
        );
    }

    public Cursor getByRowid(long id) {
        String[] columns = new String[]{"rowid AS _id, *"};
        return this.getWritableDatabase().query(
                TABLE_LABELS,
                columns,
                "rowid=?",
                new String[]{String.valueOf(id)},
                null,null,null
        );
    }
}

修改后的 SpinnerEx4Acitivity.java :-

public class MainActivity extends Activity {
    Spinner s1,s2;
    Button btnAdd;
    EditText inputLabel;
    DatabaseHandler dbhndlr;
    Cursor spinner1csr, spinner2csr;
    SimpleCursorAdapter sca, sca2;
    long spinner1_selected = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        s1 = (Spinner)findViewById(R.id.spinner1);
        s2 = (Spinner)findViewById(R.id.spinner2);
        btnAdd = (Button) findViewById(R.id.btn_add);
        inputLabel = (EditText) findViewById(R.id.input_label);
        dbhndlr = new DatabaseHandler(this);

        // If no data in database then load data for testing purposes only
        if (DatabaseUtils.queryNumEntries(
                dbhndlr.getWritableDatabase(),
                DatabaseHandler.TABLE_LABELS) < 1)
        {
            dbhndlr.insertlabel("899","Chris");
            dbhndlr.insertlabel("890","David");
        }

        // Get Cursors for Spinners
        spinner1csr = dbhndlr.getAllLabelsAsCursor();
        //Setup Adapter for Spinner 1
        sca = new SimpleCursorAdapter(this,
                android.R.layout.simple_list_item_1,spinner1csr,
                new String[]{DatabaseHandler.KEY_ID},
                new int[]{android.R.id.text1},
                0
        );

        // Set the Adapters to the Spinners
        s1.setAdapter(sca);
        // Set Spinner1 OnSelectedItemListener
        s1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(parent.getContext(),
                        "You Selected: " + id + " - " +
                                spinner1csr.getString(
                                        spinner1csr.getColumnIndex(DatabaseHandler.KEY_NAME)) +
                                " - " + spinner1csr.getString(spinner1csr.getColumnIndex(DatabaseHandler.KEY_ID))
                        ,
                        Toast.LENGTH_SHORT).show();
                spinner1_selected = id;
                spinner2csr = dbhndlr.getByRowid(spinner1_selected);
                sca2.swapCursor(spinner2csr);
            }

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

        //Steup Adapter for Spinner2
        spinner2csr = dbhndlr.getByRowid(spinner1_selected);
        sca2 = new SimpleCursorAdapter(this,
                android.R.layout.simple_list_item_1,
                spinner2csr,
                new String[]{DatabaseHandler.KEY_NAME},
                new int[]{android.R.id.text1},
                0
        );
        s2.setAdapter(sca2);
        // Set Spinner2 OnSelectedItemListener
        /* Not needed
        s2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(parent.getContext(),
                        "You Selected: " + id + " - " +
                                spinner2csr.getString(
                                        spinner2csr.getColumnIndex(DatabaseHandler.KEY_NAME)) +
                                " - " + spinner2csr.getString(spinner2csr.getColumnIndex(DatabaseHandler.KEY_ID)),
                        Toast.LENGTH_SHORT).show();
                spinner2_selected = id;
                spinner1csr = dbhndlr.getAllLabelsExceptedSelected(spinner2_selected);
                sca.swapCursor(spinner1csr);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        */
        btnAdd.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                String label = inputLabel.getText().toString();

                if (label.trim().length() > 0) {
                    // database handler commeneted out, use dbhndlr instance instead
                    // inserting new label into database
                    dbhndlr.insertLabel(label);

                    // making input filed text to blank
                    inputLabel.setText("");

                    // Hiding the keyboard
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(inputLabel.getWindowToken(), 0);

                    // loading spinner with newly added data
                    spinner1csr = dbhndlr.getAllLabelsAsCursor();
                    spinner2csr = dbhndlr.getByRowid(spinner1_selected);
                    sca.swapCursor(spinner1csr);
                    sca2.swapCursor(spinner2csr);
                } else {
                    Toast.makeText(getApplicationContext(), "Please enter label name",
                            Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    public void onDestroy() {
        spinner1csr.close();
        spinner2csr.close();
        super.onDestroy();
    }
}

【讨论】:

  • 你好,迈克试过了。但我没有看到它的遗体有任何变化。一样。
  • @Mecido 不同之处在于第二个微调器不显示第一个微调器选择的名称,而第一个微调器不显示第二个微调器选择的名称,所以你可以' t 选择相同的名称。如果那不是你想要的,那么我不知道你想要什么。 PS 根据评论代码修改(您确实使用了这个)已更改为现在在添加新名称/标签后正确刷新游标。 (使用变量spinner1_selectedspinner2_selected,我还重新整理了一些代码,还添加了onDestroy来关闭游标)
  • 麦克谢谢你。但我希望它单向只有 Spinner1 选择第一列(数据库)应该显示在微调器 2(第二列)数据库中。不需要从微调器 2 到微调器 1。还要注意我的表有 1000 个数据。例如:数据库:{ dbhndlr.insertlabel("9001234","Chris") dbhndlr.insertlabel("9001235","Cdedd"); dbhndlr.insertlabel("9003457","Dcdtt"); dbhndlr.insertlabel("9001231","Chrdis"); dbhndlr.insertlabel("9003451","Ddavid");} 例如:如果微调器 1 选择 9001231,那么微调器 2 应该显示 Chrdis。如果微调器 1 选择 9001234,那么微调器 2 应该显示 Chris。
  • 按日期是指 KEY_ID 吗?如果第二个 Spinner 只显示一件事,它有什么用?最好只有一个 textView 或 Spinner 1 同时显示 KEY_NAME 和 KEY_ID。当然,这很容易做到。哎呀,以为你说的是​​日期,但你说的是数据。但是请确认 KEY_ID。
  • 好吧,这就是你所描述的。代码来自cmets后的修改,即最后两段代码。
【解决方案2】:

您应该包含一种方法来仅获取一个标签。

public String getLabelsById(int id){ 
 String result = null;

    // Select Query
    String selectQuery = "SELECT  * FROM " + TABLE_LABELS + " WHERE " + "id" +" = ?";

    SQLiteDatabase db = this.getReadableDatabase();
    cursor = db.rawQuery(selectQuery, new String[] {String.valueOf(id)});

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {

            result = (cursor.getString(0));
    }

    // closing connection
    cursor.close();
    db.close();

    // returning lables
    return labels;
}

您应该创建一个类来存储用户,具有两个属性:名称和号码。然后你应该修改这个函数,比如:

 User user = new User();

然后,返回一个字符串:

 user.setName(cursor.getString(1));
 user.setNumber(cursor.getString(2));

【讨论】:

  • 您好,谢谢。但是从微调器中选择数字时,我无法显示名称详细信息。换句话说,在 textview 中显示 edittext 的最佳方式是什么(应该根据微调器值显示名称)..
【解决方案3】:

有几种方法可以实现这一点。

最容易实现的方法是向 Databasehandler.java 添加另一个方法(例如 getNameById),该方法将从标签表中返回名称,然后在 Spinner 的覆盖 @987654327 中调用它@ 方法。 公共字符串 getNameById(字符串 id){ 字符串 rv = "未找到名称"; SQLiteDatabase db = this.getReadableDatabase(); 光标 csr = db.query(TABLE_LABELS, 无效的, KEY_ID + "=?", 新字符串[]{id}, 空,空,空,空 );

    if (csr.moveToFirst()) {
        rv = csr.getString(csr.getColumnIndex(KEY_NAME));
    }
    csr.close();
    db.close();
    return rv;
}
  • 这假定 id 将是 unqiue
  • 与使用硬编码的列偏移相比,使用 getColumnIndex(column_name) 更灵活,并且不太可能导致错误。

SpinnerEx4Activity.Java 中的重写 onItemSelected 方法可以是:-

@Override
public void onItemSelected(AdapterView<?> parent, View view, int arg2, long id) {
    // On selecting a spinner item
    DatabaseHandler db = new DatabaseHandler(parent.getContext());
    String label = parent.getItemAtPosition(arg2).toString();

    // Showing selected spinner item
    Toast.makeText(parent.getContext(), "You selected: " + id + " " + db.getNameById(label),Toast.LENGTH_LONG).show();
}

替代方法 - 使用光标适配器

另一种方法是使用 CursorAdapter (SimpleCursorAdapter),这样就可以直接访问所有列。

1) 这需要 DatabaseHandler.java 中的方法返回一个游标。注意必须存在名为 _id 的列。由于该表未使用 WITHOUT ROWID 关键字定义,因此存在名为 rowid 的列(通常不可见)。所以我们可以使用rowid AS _id 来得到这个。可以将以下内容添加到 DatabaseHandler.java 中(注意所做的其他更改,请参阅下面的完整 DatabaseHandler.java。)

// Added to get Cursor for Simple CursorAdapter
public Cursor getAllLabelsAsCursor() {
    String[] columns = new String[]{"rowid AS _id, *"}; // Need _id column for SimpleCursorAdapter
    return this.getWritableDatabase().query(TABLE_LABELS,columns,null,null,null,null,null);
}

2) 在 Spinner 的 Activity 中调用新方法 getAllLabelsAsCursor 以检索光标。 (见下文)

3) 替代使用 SimpleCursorAdapter 的 loadSpinner 方法。

除上述之外,还进行了一些更改(请参阅带有 //

完整的工作代码是:-

数据库处理程序.java

public class DatabaseHandler extends SQLiteOpenHelper {
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "spinnerExample";

    // Labels table name
    public static final String TABLE_LABELS = "labels"; //<<<< Made public

    // Labels Table Columns names
    public static final String KEY_ID = "id";           //<<<< Made public
    public static final String KEY_NAME = "name";       //<<<< made public

    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        // Category table create query
        String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + TABLE_LABELS + "("
                + KEY_ID + " TEXT," + KEY_NAME + " TEXT)";
        db.execSQL(CREATE_CATEGORIES_TABLE);
    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_LABELS);

        // Create tables again
        onCreate(db);
    }

    /**
     * Inserting new lable into lables table
     * */
    public void insertLabel(String label){
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_NAME, label);

        // Inserting Row
        db.insert(TABLE_LABELS, null, values);
        db.close(); // Closing database connection
    }

    //<<<< Added for adding new data for testing
    public void insertlabel(String id, String label) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put(KEY_ID,id);
        cv.put(KEY_NAME,label);
        db.insert(TABLE_LABELS,null,cv);
        db.close();
    }

    /**
     * Getting all labels
     * returns list of labels
     * */
    public List<String> getAllLabels(){
        List<String> labels = new ArrayList<String>();

        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_LABELS;

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

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                labels.add(cursor.getString(0));
            } while (cursor.moveToNext());
        }

        // closing connection
        cursor.close();
        db.close();

        // returning lables
        return labels;
    }

    // Added to get Cursor for Simple CursorAdapter
    public Cursor getAllLabelsAsCursor() {
        String[] columns = new String[]{"rowid AS _id, *"}; // Need _id column for SimpleCursorAdapter
        return this.getWritableDatabase().query(TABLE_LABELS,columns,null,null,null,null,null);
    }
}

SpinnerEx4Activity.Java

public class SpinnerEx4Activity extends Activity implements
        AdapterView.OnItemSelectedListener {
    Spinner s1,s2;
    Button btnAdd;
    EditText inputLabel;
    DatabaseHandler dbhndlr;        //<<<<< Single instance for Database handler
    Cursor spinner1csr;             //<<<<< Cursor for spinner (close in onDestroy)

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        s1 = (Spinner)findViewById(R.id.spinner1);
        s2 = (Spinner)findViewById(R.id.spinner2);
        btnAdd = (Button) findViewById(R.id.btn_add);
        inputLabel = (EditText) findViewById(R.id.input_label);
        s1.setOnItemSelectedListener(this);
        dbhndlr = new DatabaseHandler(this);    //<<<< Instantiate Databasehandler
        //loadSpinnerData();                            //<<<< commented out

        // If no data in database then load data
        if (DatabaseUtils.queryNumEntries(dbhndlr.getWritableDatabase(),DatabaseHandler.TABLE_LABELS) < 1) {
            dbhndlr.insertlabel("899","Chris");
            dbhndlr.insertlabel("890","David");
        }
        altLoadSpinnerData();                           //<<<< Load via cursor
        btnAdd.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                String label = inputLabel.getText().toString();

                if (label.trim().length() > 0) {
                    // database handler commeneted out, use dbhndlr instance instead
                    // inserting new label into database
                    dbhndlr.insertLabel(label);

                    // making input filed text to blank
                    inputLabel.setText("");

                    // Hiding the keyboard
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(inputLabel.getWindowToken(), 0);

                    // loading spinner with newly added data
                    //loadSpinnerData();                    //<<<< commeneted out
                    altLoadSpinnerData();
                } else {
                    Toast.makeText(getApplicationContext(), "Please enter label name",
                            Toast.LENGTH_SHORT).show();
                }

            }
        });


    }
    // New method to utilise Cursor adapter
    private void altLoadSpinnerData() {
        // get the cursor
        spinner1csr = dbhndlr.getAllLabelsAsCursor();
        // Instantiaie Simple Cursor Adapter
        SimpleCursorAdapter sca = new SimpleCursorAdapter(this,
                android.R.layout.simple_list_item_2, // Layout to show 2 items
                spinner1csr, // Cursor
                new String[]{DatabaseHandler.KEY_ID,DatabaseHandler.KEY_NAME}, // Source data
                new int[]{android.R.id.text1,android.R.id.text2}, // Views into which data is shown
                0
        );
        //
        //sca.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        s1.setAdapter(sca);
}


    private void loadSpinnerData() {
        // Spinner Drop down elements
        List<String> lables = dbhndlr.getAllLabels();

        // Creating adapter for spinner
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, lables);

        // Drop down layout style - list view with radio button
        dataAdapter
                .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        // attaching data adapter to spinner
        s1.setAdapter(dataAdapter);
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        // Note id will be the same as position for ArrayAdapter but for CursorAdapter
        // will be the _id column (in this case rowid)
        // On selecting a spinner item
        //String label = parent.getItemAtPosition(arg2).toString(); //<<<< no need

        // Showing selected spinner item
        Toast.makeText(parent.getContext(),
                "You selected: " + id +
                        " " +
                        spinner1csr.getString(
                                spinner1csr.getColumnIndex(
                                        DatabaseHandler.KEY_NAME)
                        ) ,
                Toast.LENGTH_LONG).show();

    }
    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub
    }
}

注意事项

  • 以上包括检查无数据并加载上述两行。
  • 将表名和列名设为公开允许访问它们(使用列名而不是使用偏移量来获取游标获得????方法要好得多)。
  • 代码已更改为使用 DatabaseHandler 的单个实例,取代了 DatabaseHandler db = new DatabaseHandler(getApplicationContext()); 的多个实例的创建
  • 应该关闭游标,覆盖onDestroy 方法。但是,您不需要关闭数据库本身,尽管这样做已被保留。
  • 微调器在选定视图和下拉视图中显示两个项目(注释掉 setDropdownView 资源,您可能希望进行试验,也许提供您自己的布局)。

示例屏幕截图:-

  • 注意标签(LabelAcc 和 LabelSubACc)是因为我用文本覆盖字符串资源,而不是猜测字符串资源的值。

编辑重新评论

Spinner1 只工作。spinner 2 没有反应。

1) 添加新方法(可以在一种方法中,但最好将它们分开。如果在一种方法中,则不需要 3):-

// New method to utilise Cursor adapter for 2nd Spinner
private void altLoadSpinner2Data() {
    // get the cursor
    spinner2csr = dbhndlr.getAllLabelsAsCursor();
    // Instantiaie Simple Cursor Adapter
    SimpleCursorAdapter sca = new SimpleCursorAdapter(this,
            android.R.layout.simple_list_item_1, // Layout to show 2 items
            spinner2csr, // Cursor
            new String[]{DatabaseHandler.KEY_NAME}, // Source data
            new int[]{android.R.id.text1}, // Views into which data is shown
            0
    );
    //
    //sca.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    s2.setAdapter(sca);
    s2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            Toast.makeText(parent.getContext(),
                    "You Selected: " + id + " " +
                    spinner2csr.getString(
                            spinner2csr.getColumnIndex(DatabaseHandler.KEY_ID)),
                    Toast.LENGTH_SHORT

            ).show();
        }
        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });
}
  • Note 使用第二个光标,因此每个光标都可以有自己的位置
  • 包括它自己的略有不同(节目 ID 已选择)OnSelectedItemListener

2) 将光标声明更改为 2 个光标,因此它是:-

    Cursor spinner1csr, spinner2csr;             //<<<<< Cursor for spinner (close in onDestroy)

3) 在第一个微调器之后/之前添加调用以加载第二个微调器:-

    altLoadSpinner2Data();

【讨论】:

  • 你好,迈克,你拯救了我的一天。我几乎按照你的魔法密码到达了。但是最好的方法是单独显示而不是在同一个微调器中显示。例如选择“spinner1”(id)并在另一个“spinner2”(名称)或Textview中显示
  • @Mecido 在 Spinner1 中只使用 android.R.layout.simple_list_item_1 而不是 2. 删除第二列即 new String[]{DatabaseHandler.KEY_ID} 并删除第二个视图文本 2 即 new int[]{android.R.id.text1}。对于第二个微调器,使用相同的但将列更改为名称(可以对两者使用相同的光标)。我假设您正在使用 CursorAdapter。
  • Spinner1 只工作。spinner 2 没有反应。私人无效 altLoadSpinnerData1() { spinner2csr = dbhndlr.getAllLabelsAsCursor(); SimpleCursorAdapter sca = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, spinner2csr, // 光标 new String[]{DatabaseHandler.KEY_NAME}, new int[]{android.R.id.text2}, 0 ); s2.setAdapter(sca); }
  • 私有 void altLoadSpinnerData() { spinner1csr = dbhndlr.getAllLabelsAsCursor(); SimpleCursorAdapter sca = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, // 显示 2 个项目的布局 spinner1csr, // 光标 new String[]{DatabaseHandler.KEY_ID}, new int[]{android.R.id.text1 },// 显示数据的视图 0 ); s1.setAdapter(sca); }
  • @Mecido 看到编辑到 Asnwer
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-06
  • 1970-01-01
相关资源
最近更新 更多