SQLite中数据库动态用户输入的方法

时间:2019-05-24 15:21:07

标签: android database android-sqlite

如何为用户创建和删除数据库列创建动态SQLite格式

例如,在活动屏幕上,它最初是:

Trial 1:   Input 1   Input 2

但是在点击“添加行”按钮后,它会添加如下另一行

Trial 1:   Input 1   Input 2
Trial 2:   Input 1   Input 2

但是,如果用户想删除第二行,它将返回到初始状态。 我在底部添加了图片,以显示我的意思。

我只是开始学习如何使用Android Studio,因此我想我可以将原始SQLite实体设置为具有20列,假设两列代表每个试验的每个输入,并且假设它们不这样做超过10次试用的任何内容。但是由于我不知道用户会输入多少次试用,因此如果用户要进行10次以上,那就是一个问题。

这是对的吗?或者是否可以通过单击“添加行”按钮在数据库中为每个输入动态添加两个额外的列。还是我需要两个不同的数据库,以相同的ID将每个输入保存到每个数据库,并通过相同的主键ID获取值? 这是图片:

最初:

Image 1

单击按钮后:

Image 2

1 个答案:

答案 0 :(得分:0)

  

这是对的吗?还是可以通过单击“添加行”按钮为数据库中的每个输入动态添加两个额外的列。

您可能不希望考虑动态地管理列表,而是利用 ListView 来列出当前数据以及用于输入新数据的一组EditText。

  

或者我需要两个   不同的数据库将每个输入与   相同的ID并通过相同的主键ID获取值?

在列和数据库之间有表。因此,问题似乎是要在实验中增加可变数量的试验。然后,在试验中包含一个试验,因此您可能会有一个试验表和一个试验表,后者引用该试验所属的单个父试验。

多个数据库。您很可能不希望出现并发症,也没有任何必要。

示例

这是一个工作示例(尽管非常基础,尤其是布局方面),其中包含大量可以添加试验的实验。该代码添加了3个实验进行演示,分别命名为实验1,实验2和实验3。

首次运行时,任何实验都不会存在任何试验。输入数据(2个编辑文本)并单击“添加”按钮后,即可添加它们。在顶部显示“实验名称”,然后单击一个“下一步”按钮,将在实验之间循环并显示该实验的试验(如果有)。

每个实验的尝试次数是无限的。

代码

布局

首先布局 activity_main.xml ,该布局具有

  • 标题(无所不在的Hello World)
  • 两个EditTexts和一个用于添加新数据的按钮。
  • 用于列出数据库中数据的ListView。

代码是:-

<?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=".MainActivity"
    >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        />
    <LinearLayout
        android:layout_marginTop="10dp"
        android:id="@+id/experimentsection"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#FFAAAAFF">

        <TextView
            android:id="@+id/currentexperiment"
            android:layout_width="0dp"
            android:layout_weight="8"
            android:layout_height="wrap_content"
            android:text="No Experiment"/>
        <Button
            android:id="@+id/nextexperiment"
            android:layout_width="0dp"
            android:layout_weight="2"
            android:layout_height="wrap_content"
            android:text="NEXT"/>
    </LinearLayout>
    <LinearLayout
        android:id="@+id/inputsection"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <EditText
            android:id="@+id/input1"
            android:layout_width="0dp"
            android:layout_weight="4"
            android:layout_height="wrap_content"/>
        <EditText
            android:id="@+id/input2"
            android:layout_width="0dp"
            android:layout_weight="4"
            android:layout_height="wrap_content"/>
        <Button
            android:id="@+id/add"
            android:layout_width="0dp"
            android:layout_weight="2"
            android:layout_height="wrap_content"
            android:text="ADD"/>
    </LinearLayout>
    <ListView
        android:id="@+id/currentdata"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </ListView>
</LinearLayout>

数据库助手

数据库帮助器 DBHelper.java ,它定义了具有3列的单个表

    id列可唯一标识一行。
    • (请注意,ListView的适配器要求将其命名为_id)
  • 帽子的2个值的列data1和data1将被存储

代码是:-

public class DBHelper extends SQLiteOpenHelper {

    public static final String DBNAME = "mydb";
    public static final int DBVERSION = 1;

    public static final String TBL_EXPERIMENT = "experiment";
    public static final String COL_ID = BaseColumns._ID;
    public static final String COL_EXPERIMENT_NAME = "experiment_name";

    public static final String TBL_MYTABLE1 = "mytable1";
    public static final String COL_EXPERIMENT_REF = "experiment_ref";
    public static final String COl_DATA1 = "data1";
    public static final String COL_DATA2 = "data2";

    SQLiteDatabase mDB;

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

    @Override
    public void onConfigure(SQLiteDatabase db) {
        super.onConfigure(db);
        db.setForeignKeyConstraintsEnabled(true);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE IF NOT EXISTS " + TBL_EXPERIMENT + "(" +
                COL_ID + " INTEGER PRIMARY KEY," +
                COL_EXPERIMENT_NAME + " TEXT UNIQUE" +
                ")"
        );
        db.execSQL("CREATE TABLE IF NOT EXISTS " + TBL_MYTABLE1 + "(" +
                COL_ID + " INTEGER PRIMARY KEY," +

                COL_EXPERIMENT_REF + " INTEGER " +
                " REFERENCES " + TBL_EXPERIMENT + "(" +
                COL_ID +
                ")," +

                COl_DATA1 + " TEXT," +
                COL_DATA2 + " TEXT" +
                ")"
        );
    }

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

    }

    public long addExperiment(String name) {
        ContentValues cv = new ContentValues();
        cv.put(COL_EXPERIMENT_NAME,name);
        return mDB.insert(TBL_EXPERIMENT,null,cv);
    }

    public long addTrial(long expermientId, String data1, String data2) {
        ContentValues cv = new ContentValues();
        cv.put(COL_EXPERIMENT_REF,expermientId);
        cv.put(COl_DATA1,data1);
        cv.put(COL_DATA2,data2);
        return mDB.insert(TBL_MYTABLE1,null ,cv);
    }

    public Cursor getAllRowsForAnExperiment(long experimentId) {
        String whereclause = COL_EXPERIMENT_REF + "=?";
        String[] whereargs = new String[]{String.valueOf(experimentId)};
        return mDB.query(TBL_MYTABLE1,null,whereclause,whereargs,null,null,null);
    }


    public Cursor getAllExperiments() {
        return mDB.query(TBL_EXPERIMENT,null,null,null,null,null,null);
    }

    public int deleteTrial(long id) {
        String whereclause = COL_ID + "=?";
        String[] whereargs = new String[]{String.valueOf(id)};
        return mDB.delete(TBL_MYTABLE1,whereclause,whereargs);
    }
}
  • addRow 是用于添加一行数据的方法。
  • getAllRows 是用于检索所有数据的方法。

活动

最后将所有内容组合在一起是 MainActivity.java

public class MainActivity extends AppCompatActivity {

    //Define Class variables
    DBHelper mDBHlpr;
    Cursor mCursor, mExperiments;
    SimpleCursorAdapter mSCA;
    EditText mInput1, mInput2;
    TextView mExperimentName;
    Button mAdd, mNextExperiment;
    ListView mListView;

    long mCurrentExperimentId = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); // Set the layout to be displayed

        //Instaniate the layout objects to be used
        mExperimentName = this.findViewById(R.id.currentexperiment);
        mNextExperiment = this.findViewById(R.id.nextexperiment);
        mInput1 = this.findViewById(R.id.input1);
        mInput2 = this.findViewById(R.id.input2);
        mAdd = this.findViewById(R.id.add);
        mListView = this.findViewById(R.id.currentdata);

        //Instantiate the Database helper
        mDBHlpr = new DBHelper(this);
        addSomeExperiments();
        mExperiments = mDBHlpr.getAllExperiments();

        // Do the work
        manageExperimentButton();
        manageListView();
        manageAddButton();
    }

    /**
     * Manage the list view,
     * call this anytime the list is to be created (only once)
     * or the list is changed (e.g. after adding)
     */
    private void manageListView() {
        mCursor = mDBHlpr.getAllRowsForAnExperiment(mCurrentExperimentId); // Get the current data

        // If the Adapter hasn't been instantiated do so
        if (mSCA == null) {
            mSCA = new SimpleCursorAdapter(
                    this,
                    android.R.layout.simple_list_item_2,
                    mCursor,
                    new String[]{DBHelper.COl_DATA1, DBHelper.COL_DATA2},
                    new int[]{android.R.id.text1, android.R.id.text2},
                    0
            );
            mListView.setAdapter(mSCA); // Tie the adpater to the listview
            //<<<<<<<<< EXTRA DELETE A ROW WHEN LONG CLICKED >>>>>>>>>>
            mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                    if(mDBHlpr.deleteTrial(id) > 0) {
                        Toast.makeText(view.getContext(),"Deleted",Toast.LENGTH_SHORT).show();
                        manageListView();
                    } else {
                        Toast.makeText(view.getContext(),"NOT deleted????",Toast.LENGTH_SHORT).show();
                    }
                    return true; // set this event as having been actioned
                }
            });
        } else {
            // If adapter has been instantiated tell it that the data has changed
            mSCA.swapCursor(mCursor);
        }
    }

    //Handle the Add button by adding an onClick listener
    private void manageAddButton() {
        mAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //First thing check if there is data to be added
                if (mInput1.getText().toString().length() < 1) {
                    Toast.makeText(v.getContext(),"No data in Input1. Try again",Toast.LENGTH_SHORT).show();
                    mInput1.requestFocus();
                    return;
                }
                if (mInput2.getText().toString().length() < 1) {
                    Toast.makeText(v.getContext(),"No data in Input2. Try again",Toast.LENGTH_SHORT).show();
                    mInput2.requestFocus();
                    return;
                }
                // If there is data to be added, try adding it
                // if the value returned from addRow is less than 1 or more then data was added
                if (mDBHlpr.addTrial(mCurrentExperimentId, mInput1.getText().toString(),mInput2.getText().toString()) > 0) {
                    Toast.makeText(v.getContext(),"Added",Toast.LENGTH_SHORT).show();
                    // As data has been added refresh the ListView
                    manageListView();
                    // and clear the input fields
                    mInput1.setText("");
                    mInput2.setText("");
                    // and finally position the focus on the first input
                    mInput1.requestFocus();
                } else {
                    // Ooops something went wrong (very unlikely with the current db schema)
                    Toast.makeText(v.getContext(),"Not Added????",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
    private void manageExperimentButton() {
        mExperiments = mDBHlpr.getAllExperiments();
        mExperiments.moveToFirst();
        handleCurrentExperiment();
        mNextExperiment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               if(!mExperiments.moveToNext()) {
                   mExperiments.moveToFirst();
               }
                handleCurrentExperiment();
            }
        });
    }

    private void handleCurrentExperiment() {
        mCurrentExperimentId = mExperiments.getLong(mExperiments.getColumnIndex(DBHelper.COL_ID));
        mExperimentName.setText(mExperiments.getString(mExperiments.getColumnIndex(DBHelper.COL_EXPERIMENT_NAME)));
        manageListView();
    }

    //When the activity finishes close the cursor
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mCursor.close();
    }

    //If returning to the activity refresh the ListView
    @Override
    protected void onResume() {
        super.onResume();
        manageListView();
    }

    private void addSomeExperiments() {
        // Add some experiments if none exist
        if(DatabaseUtils.queryNumEntries(mDBHlpr.getWritableDatabase(),DBHelper.TBL_EXPERIMENT) > 0 ) return;
        mDBHlpr.addExperiment("Experiment 1");
        mDBHlpr.addExperiment("Experiment 2");
        mDBHlpr.addExperiment("Experiment 3");
    }
}

结果

具有近20个试验的实验屏幕快照(添加了A-Z)(尽管无用信息)。该代码还包括通过长按列表中的试验来删除试验(可以看到一些试验已被删除,例如试验E已被删除):

enter image description here

点击NEXT即可进入实验1,该实验的试验次数较少:-

enter image description here