Android Sqlite 示例(帶下拉列表)含代碼

Android Sqlite 示例(帶下拉列表)

在這個例子中,我們在按鈕點擊時添加一個標簽,并在下拉列表上顯示所有添加的標簽。愛掏網 - it200.com正如您在前面的例子中看到的一樣, 需要擴展 SQLiteOpenHelper 類才能在sqlite上執行操作。愛掏網 - it200.com

我們在 DatabaseHandler 類中覆蓋了 SQLiteOpenHelper 類的 onCreate() 和 onUpgrade() 方法,該類提供了其他方法來插入和顯示標簽或數據。愛掏網 - it200.com

Android Sqlite 下拉列表 示例

讓我們看一下使用 sqlite 數據庫添加和顯示字符串內容的簡單代碼。愛掏網 - it200.com

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.javatpoint.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" />  

    <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" />  

    <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" />  
</RelativeLayout>  

Activity類

package example.javatpoint.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);

        // Loading spinner data from database
        loadSpinnerData();

        btnAdd.setOnClickListener(new View.OnClickListener() {

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

                if (label.trim().length() > 0) {
                    DatabaseHandler db = new DatabaseHandler(getApplicationContext());
                    db.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();
                } else {
                    Toast.makeText(getApplicationContext(), "Please enter label name",
                            Toast.LENGTH_SHORT).show();
                }

            }
        });
    }

    /**
     * Function to load the spinner data from SQLite database
     * */
    private void loadSpinnerData() {
        DatabaseHandler db = new DatabaseHandler(getApplicationContext());
        List labels = db.getAllLabels();

        // Creating adapter for spinner
        ArrayAdapter dataAdapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item, labels);

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

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

    @Override
    public void onItemSelected(AdapterView parent, View view, int position,
                               long id) {
        // On selecting a spinner item
        String label = parent.getItemAtPosition(position).toString();

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

    }

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

    }
}

數據庫處理器類

package example.javatpoint.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);
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        // Category table create query
        String CREATE_ITEM_TABLE = "CREATE TABLE " + TABLE_NAME + "("
                + COLUMN_ID + " INTEGER PRIMARY KEY," + COLUMN_NAME + " TEXT)";
        db.execSQL(CREATE_ITEM_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_NAME);

        // 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(COLUMN_NAME, label);//column name, column value

        // Inserting Row
        db.insert(TABLE_NAME, null, values);//tableName, nullColumnHack, CotentValues
        db.close(); // Closing database connection
    }

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

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

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

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                list.add(cursor.getString(1));//adding 2nd column data
            } while (cursor.moveToNext());
        }
        // closing connection
        cursor.close();
        db.close();
        // returning lables
        return list;
    }
}

下載此Android示例

輸出:

聲明:所有內容來自互聯網搜索結果,不保證100%準確性,僅供參考。如若本站內容侵犯了原著者的合法權益,可聯系我們進行處理。
發表評論
更多 網友評論0 條評論)
暫無評論

返回頂部

主站蜘蛛池模板: 香蕉免费在线视频| 久久中文娱乐网| 韩国女友的妈妈| 日本按摩高潮a级中文片| 四虎影院最新域名| heisiav1| 欧美人妖视频网站| 国产女人高潮视频在线观看| 丰满亚洲大尺度无码无码专线 | www.一级毛片| 欧美综合自拍亚洲综合图片区| 国产精品videossex另类| 久久精品国产一区二区电影| 美女的尿口视频网站| 天天舔天天干天天操| 亚洲国产精品成人久久久| 黄色a一级视频| 忘忧草www日本| 亚洲欧洲自拍拍偷综合| 麻豆国产剧果冻传媒视频| 性欧美高清come| 亚洲国产欧美久久香综合| 韩国免费毛片在线看| 妖神记1000多章哪里看| 亚洲成人在线网| 菠萝蜜国际通道麻豆三区| 天天干夜夜夜操| 五十路六十路绝顶交尾| 精品欧美一区二区在线观看| 国产高清在线观看| 久久久综合香蕉尹人综合网 | 性高湖久久久久久久久aaaaa | GOGOGO高清在线观看中文版| 欢愉电影完整版免费观看中字| 四虎色姝姝影院www| 99久re热视频这里只有精品6 | 浮力影院第一页小视频国产在线观看免费 | 中文字幕丰满孑伦| 欧美精品在线免费观看| 国产人与禽zoz0性伦多活几年| av免费不卡国产观看|