如何在运行的应用程序上替换SQLite数据库

时间:2018-03-15 01:24:19

标签: java android sqlite dropdown

我是Android新手。我有一个应用程序,其中包含两个下拉列表,其中的值来自SQLite数据库。

现在我有一个按钮。点击后,我想替换下拉列表的值。

例如,如果我在SQLite DB#1的下拉列表中有{A,B,C,D}, 点击按钮后,我想要来自SQLite DB#2的{Q,W,E,R}。

我如何实现这一目标?

1 个答案:

答案 0 :(得分:0)

假设您只是想切换下拉列表,那么这可以通过两种方式完成;你可以: -

a)交换适配器的源数据或 b)交换视图适配器。

以下是一个示例,其中包括两个使用两个具有相同表格的数据库(看起来与您描述的方案相匹配)。

首先是布局

  • 一个TextView,用于描述使用的适配器和数据库)
  • 两个旋转器
  • 两个按钮(每个方法一个)

activity_main.xml: -

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="ddse.dropdownswitchexample.MainActivity">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />
    <Spinner
        android:id="@+id/dropdown1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </Spinner>
    <Spinner
        android:id="@+id/dropdown2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </Spinner>
    <Button
        android:id="@+id/switchbyadpater"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Switch by Adapter"
        />
    <Button
        android:id="@+id/switchbyswapcursor"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Switch by Cursor"/>
</LinearLayout>

DatabaseHelper for Database 1

DBHelper1.java

public class DBHelper1 extends SQLiteOpenHelper {

    public static final String DB1NAME = "db1";
    public static final int DBVERSION = 1;

    public static final String TBNAME = "dropdowns";
    public static final String DROPDOWNS_COL_ITEM = "item";

    SQLiteDatabase mDB;

    public DBHelper1(Context context) {
        super(context, DB1NAME, null, DBVERSION);
        mDB = this.getWritableDatabase();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String crtsql = "CREATE TABLE IF NOT EXISTS " + TBNAME +
                "(" +
                DROPDOWNS_COL_ITEM + " TEXT " +
                ")";
        db.execSQL(crtsql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public long insertDropDownItem(String item) {
        ContentValues cv = new ContentValues();
        cv.put(DROPDOWNS_COL_ITEM,item);
        return mDB.insert(TBNAME,null,cv);
    }

    public Cursor getAllDropDownItems() {
        String[] columns = new String[]{"rowid AS _id,*"};
        return mDB.query(TBNAME, columns,null,null,null,null,null);
    }
}

DatabaseHelper for Database 2

DBHelper2.java

public class DBHelper2 extends SQLiteOpenHelper {

    public static final String DB2NAME = "db2";
    public static final int DBVERSION = 1;

    public static final String TBNAME = "dropdowns";
    public static final String DROPDOWNS_COL_ITEM = "item";

    SQLiteDatabase mDB;


    public DBHelper2(Context context) {
        super(context, DB2NAME, null, DBVERSION);
        mDB = this.getWritableDatabase();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String crtsql = "CREATE TABLE IF NOT EXISTS " + TBNAME +
                "(" +
                DROPDOWNS_COL_ITEM + " TEXT " +
                ")";
        db.execSQL(crtsql);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public long insertDropDownItem(String item) {
        ContentValues cv = new ContentValues();
        cv.put(DROPDOWNS_COL_ITEM,item);
        return mDB.insert(TBNAME,null,cv);
    }

    public Cursor getAllDropDownItems() {
        String[] columns = new String[]{"rowid AS _id,*"};
        return mDB.query(TBNAME,columns,null,null,null,null,null);
    }
}
  • 注意代码可以很容易地减少/组合,因为两个数据库助手之间几乎没有任何区别。

主要/调用活动

public class MainActivity extends AppCompatActivity {

    // Define View related class variables    
    TextView mTitle;
    Spinner mSpinner1, mSpinner2;
    Button mSwapByAdapter, mSwapByCursor;
    boolean spinner1_using_adapter1_state = true;
    boolean adapter1_using_db1_state = true;

    // define DB related class variables
    DBHelper1 mDB1hlpr;
    DBHelper2 mDB2hlpr;
    Cursor mCsr1, mCsr2;
    SimpleCursorAdapter mSCA1, mSCA2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Set View related variables    
        mTitle = (TextView) this.findViewById(R.id.title);
        mSpinner1 = (Spinner) this.findViewById(R.id.dropdown1);
        mSpinner2 = (Spinner) this.findViewById(R.id.dropdown2);
        mSwapByAdapter = (Button) this.findViewById(R.id.switchbyadpater);
        mSwapByCursor = (Button) this.findViewById(R.id.switchbyswapcursor);

        / Set DB helpers
        mDB1hlpr = new DBHelper1(this);
        mDB2hlpr = new DBHelper2(this);

        loadSomeItems(); // Load data for spinners
        refreshSpinners(); refresh spinners (sets them up)

        // Set button Listeners
        mSwapByAdapter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                spinner1_using_adapter1_state = !spinner1_using_adapter1_state; // Switch Adapters used by Spinners
                refreshSpinners();
            }
        });
        mSwapByCursor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                adapter1_using_db1_state = !adapter1_using_db1_state; // Switch Cursor used by adapters
                refreshSpinners();
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mCsr1.close();
        mCsr2.close();
    }

    // Load data for spinners if none loaded    
    private void loadSomeItems() {
        if (DatabaseUtils.queryNumEntries(mDB1hlpr.getWritableDatabase(),DBHelper1.TBNAME) < 1) {
            mDB1hlpr.insertDropDownItem("A");
            mDB1hlpr.insertDropDownItem("B");
            mDB1hlpr.insertDropDownItem("C");
            mDB1hlpr.insertDropDownItem("D");
        }

        if (DatabaseUtils.queryNumEntries(mDB2hlpr.getWritableDatabase(),DBHelper2.TBNAME) < 1) {
            mDB2hlpr.insertDropDownItem("Q");
            mDB2hlpr.insertDropDownItem("W");
            mDB2hlpr.insertDropDownItem("E");
            mDB2hlpr.insertDropDownItem("R");
        }
    }

    // resfresh the spinners according to the 2 states    
    private void refreshSpinners() {

        // re-get the underlying data
        mCsr1 = mDB1hlpr.getAllDropDownItems();
        mCsr2 = mDB2hlpr.getAllDropDownItems();
        // Prepare for reporting on what is using what
        String adapter1_source = "";
        String adapter2_source = "";
        String spinner1_using = "";
        String spinner2_using = "";

        // If adapter 1 should be using DB1 then
        //     set adapter 1 to use csr from DB1 and 
        //     set adpater 2 to use csr from DB 2    
        if (adapter1_using_db1_state) {
            adapter1_source = "Database 1 ";
            adapter2_source = "Database 2 ";
            // If adapter 1 is null then instantiate it
            if (mSCA1 == null) {
                mSCA1 = new SimpleCursorAdapter(this,
                        android.R.layout.simple_spinner_dropdown_item,
                        mCsr1,
                         new String[] {DBHelper1.DROPDOWNS_COL_ITEM},
                        new int[]{android.R.id.text1},
                        0
                );
            } else {
                // otherwise swap the cursor
                mSCA1.swapCursor(mCsr1);
            }
            / Like adapter 1
            if (mSCA2 == null) {
                mSCA2 = new SimpleCursorAdapter(this,
                        android.R.layout.simple_spinner_dropdown_item,
                        mCsr2,
                        new String[]{DBHelper2.DROPDOWNS_COL_ITEM},
                        new int[]{android.R.id.text1},
                        0
                );
            } else {
                mSCA2.swapCursor(mCsr2);
            }
        } else {
            // Otherwise Adapter1 uses DB2 and adapter2 uses DB1
            // Very much the same as previously used
            adapter1_source = "Database 2 ";
            adapter2_source = "Database 1 ";
            if (mSCA2 == null) {
                mSCA2 = new SimpleCursorAdapter(this,
                        android.R.layout.simple_spinner_dropdown_item,
                        mCsr1,
                        new String[]{DBHelper1.DROPDOWNS_COL_ITEM},
                        new int[]{android.R.id.text1},
                        0
                );
            } else {
                mSCA2.swapCursor(mCsr1);
            }
            if (mSCA1 == null) {
                mSCA1 = new SimpleCursorAdapter(this,
                        android.R.layout.simple_spinner_dropdown_item,
                        mCsr2,
                        new String[]{DBHelper2.DROPDOWNS_COL_ITEM},
                        new int[]{android.R.id.text1},
                        0
                );
            } else {
                mSCA1.swapCursor(mCsr2);
            }
        }

        // Now consider the Spinner state using the appropriate adpater
        if (spinner1_using_adapter1_state) {
            spinner1_using = "Adapter 1" + adapter1_source;
            spinner2_using = "Adapter 2" + adapter2_source;
            mSpinner1.setAdapter(mSCA1);
            mSpinner2.setAdapter(mSCA2);
        } else {
            spinner1_using = "Adapter 2" + adapter2_source;
            spinner2_using = "Adapter 1" + adapter1_source;
            mSpinner2.setAdapter(mSCA1);
            mSpinner1.setAdapter(mSCA2);
        }
        // Build the title to display what spinner/adapater/DB's are being used.
        StringBuilder title = new StringBuilder();
        title.append("Spinner 1 is using ");
        title.append(spinner1_using);
        title.append(" Spinner 2 is using " + spinner2_using);
        mTitle.setText(title.toString());
    }
}

结果应用程序: -

开始时: -

enter image description here

按适配器切换

enter image description here

按光标切换

enter image description here

  • 注意 查看顶行文字以查看适配器/数据库组合。