Android - SQLite Spinner

首页 / Android入门教程 / Android - SQLite Spinner

在此示例中,无涯教程在单击按钮时添加了一个标签,并在Spinner上显示了所有添加的标签。如您在前面的示例中所看到的,需要扩展SQLiteOpenHelper类以在sqlite上执行操作。

无涯教程在DatabaseHandler类中重写了SQLiteOpenHelper类的onCreate()和onUpgrade()方法,该方法提供了用于插入和显示标签或数据的其他方法。

Sqlite Spinner示例

让无涯教程看看简单的代码可以使用SQLite数据库在Spinner上添加和显示字符串内容。

File: activity_main.xml
<!--?xml version="1.0" encoding="utf-8"?-->
<relativelayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="example.learnfk.com.sqlitespinner.MainActivity">
    <edittext android:id="@+id/input_label" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignparenttop="true" android:layout_centerhorizontal="true" android:layout_margintop="46dp" android:hint="Add item" android:ems="10"></edittext>
    <button android:id="@+id/btn_add" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/input_label" android:layout_centerhorizontal="true" android:layout_margintop="67dp" android:text="Add item"></button>
    <spinner android:id="@+id/spinner" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignparentleft="true" android:layout_alignparentstart="true" android:layout_below="@+id/btn_add" android:layout_margintop="70dp"></spinner>
</relativelayout>
File: MainActivity.java
package example.learnfk.com.sqlitespinner;

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.List;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
    Spinner spinner;
    Button btnAdd;
    EditText inputLabel;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        spinner = findViewById(R.id.spinner);
        btnAdd =  findViewById(R.id.btn_add);
        inputLabel = findViewById(R.id.input_label);

        spinner.setOnItemSelectedListener(this);

       //从数据库加载spinner数据
        loadSpinnerData();

        btnAdd.setOnClickListener(new View.OnClickListener() {

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

                if (label.trim().length() &gt; 0) {
                    DatabaseHandler db = new DatabaseHandler(getApplicationContext());
                    db.insertLabel(label);

                   //将输入字段文本设为空白
                    inputLabel.setText("");

                   //隐藏键盘
                    InputMethodManager imm = (InputMethodManager)
                            getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(inputLabel.getWindowToken(), 0);
                   //使用新添加的数据加载Spinner
                    loadSpinnerData();
                } else {
                    Toast.makeText(getApplicationContext(), "Please enter label name",
                            Toast.LENGTH_SHORT).show();
                }

            }
        });
    }

    /**
     * 从 SQLite 数据库加载Spinner数据的函数
     * */
    private void loadSpinnerData() {
        DatabaseHandler db = new DatabaseHandler(getApplicationContext());
        List<string> labels = db.getAllLabels();

       //创建适配器
        ArrayAdapter<string> dataAdapter = new ArrayAdapter<string>(this,android.R.layout.simple_spinner_item, labels);

       //下拉布局样式 - 带有单选按钮的列表视图
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

       //将数据适配器附加到Spinner
        spinner.setAdapter(dataAdapter);
    }

    @Override
    public void onItemSelected(AdapterView&gt; parent, View view, int position,
                               long id) {
       //在选择Spinner项目时
        String label = parent.getItemAtPosition(position).toString();

       //显示选定的Spinner项目
        Toast.makeText(parent.getContext(), "You selected: " + label,
                Toast.LENGTH_LONG).show();

    }

    @Override
    public void onNothingSelected(AdapterView&gt; arg0) {
       //TODO Auto-generated method stub

    }
}
File: DatabaseHandler.java
package example.learnfk.com.sqlitespinner;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;

public class DatabaseHandler extends SQLiteOpenHelper {
    private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "spinnerExample";
    private static final String TABLE_NAME = "labels";
    private static final String COLUMN_ID = "id";
    private static final String COLUMN_NAME = "name";

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

   //创建表
    @Override
    public void onCreate(SQLiteDatabase db) {
       //类别表创建查询
        String CREATE_ITEM_TABLE = "CREATE TABLE " + TABLE_NAME + "("
                + COLUMN_ID + " INTEGER PRIMARY KEY," + COLUMN_NAME + " TEXT)";
        db.execSQL(CREATE_ITEM_TABLE);
    }

   //升级数据库
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
       //删除旧表(如果存在)
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);

       //再次创建表
        onCreate(db);
    }

    /**
     * 将新标签插入标签表
     * */
    public void insertLabel(String label){
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(COLUMN_NAME, label);//列名,列值

       //插入行
        db.insert(TABLE_NAME, null, values);//表名,nullColumnHack,CotentValues
        db.close();//关闭数据库连接
    }

    /**
     * 获取所有标签
     * 返回标签列表
     * */
    public List<string> getAllLabels(){
        List<string> list = new ArrayList<string>();

       //全选查询
        String selectQuery = "SELECT  * FROM " + TABLE_NAME;

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

       //循环遍历所有行并添加到列表
        if (cursor.moveToFirst()) {
            do {
                list.add(cursor.getString(1));//添加第二列数据
            } while (cursor.moveToNext());
        }
       //关闭连接
        cursor.close();
        db.close();
       //返回标签
        return list;
    }
}
android sqlite example output 1android sqlite example output 2android sqlite example output 3

这一章《Android - SQLite Spinner》你学到了什么?在下面做个笔记吧!做站不易,你的分享是对我们最大的支持

猜你喜欢

朱赟的技术管理课 -〔朱赟〕

透视HTTP协议 -〔罗剑锋(Chrono)〕

Flutter核心技术与实战 -〔陈航〕

成为AI产品经理 -〔刘海丰〕

好记忆不如烂笔头。留下你的足迹吧 :)