为Android上的另一个表中的每个项创建新表

时间:2017-06-14 10:56:36

标签: java android

我想在数据库中为用户输入的每个标签创建一个新表,该表将有两列测验和注释,但我不断收到错误。我还想知道是否有其他方法可以实现这一目标。

这些是我的代码:

package com.example.mybank;

public class SomeActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.select);
        choose = (Button) findViewById(R.id.register);
        save = (Button) findViewById(R.id.save);
        inputcos = (EditText) findViewById(R.id.inputcos);
        select = (Spinner) findViewById(R.id.spinner);
        choose.setOnClickListener(this);
        save.setOnClickListener(this);
        select.setOnItemSelectedListener(this);
        loadSpinnerData();
    }


    private void loadSpinnerData() {
        // TODO Auto-generated method stub
        DatabaseHandler db = new DatabaseHandler(getApplicationContext());

        // Spinner Drop down elements
        List<String> lables = db.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
        select.setAdapter(dataAdapter);
    }


    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        Boolean testing = true;
        switch (v.getId()) {
            case R.id.register:
                save.setVisibility(View.VISIBLE);
                inputcos.setVisibility(View.VISIBLE);
                break;
            case R.id.save:
                try {
                    label = inputcos.getText().toString();
                    if (label.trim().length() > 0) {
                        // database handler
                        DatabaseHandler db = new DatabaseHandler(getApplicationContext());

                        // inserting new label into database
                        db.insertLabel(label);

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

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

                        // loading spinner with newly added data
                        loadSpinnerData();
                    } else {
                        Toast.makeText(getApplicationContext(), "Please enter course",
                                Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    testing = false;
                    if (testing) {
                        if (testing) {
                            Dialog dd = new Dialog(this);
                            String error = e.toString();
                            dd.setTitle("Error");
                            TextView tv = new TextView(this);
                            tv.setText(error);
                            dd.setContentView(tv);
                            dd.show();
                        }
                    }
                } finally {
                    if (testing) {
                        Dialog dd = new Dialog(this);
                        TextView tv = new TextView(this);
                        if (label.trim().length() > 0) {
                            dd.setTitle("Success");
                            tv.setText("course sucessfully added");
                        } else {
                            dd.setTitle("warning");
                            tv.setText("no course input");
                        }
                        dd.setContentView(tv);
                        dd.show();
                    }
                }
                break;
        }

    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position,
                               long id) {
        //creating database table for each label of the list view

        if (label.trim().length() > 0) {
            DatabaseHandler db = new DatabaseHandler(getApplicationContext());
            db.createnewtable(label);
        }


        Intent i = new Intent(this, choices.class);
        startActivity(i);
        // Showing selected spinner item


    }

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

    }
}

数据库类:

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";
    static final String TABLE_SPINNER = "course";

    // Labels Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";
    private static final  String KEY_NOTE="note";
    private static final  String KEY_QUIZES="quiz";
    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 + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT NOT NULL)";
        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);


    }
    // creating tables for labels
    public void createnewtable(String course){
        SQLiteDatabase db = this.getWritableDatabase();
        String sql = "CREATE TABLE " + course + " (" + KEY_QUIZES
                + " text not null, " + KEY_NOTE + " text not null " + ");";
        Log.i("createDB=", sql);
        db.execSQL("DROP TABLE IF EXISTS TABLE_SPINNER");
        db.execSQL(sql);
    }

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

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

        // Inserting Row
        int i = (int)  db.insert(TABLE_LABELS, null, values);
        db.close(); // Closing database connection
        //Now create new table for this category
        if (i > 0) {
            createnewtable(label);}
    }
    public long insertquiz(String quiz){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(KEY_QUIZES, quiz);
        // Inserting Row
        return db.insert(TABLE_SPINNER,null, values);

    }
    public long insertnote(String note){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(KEY_NOTE, note);
        // Inserting Row
        return   db.insert(TABLE_SPINNER,null, values);

    }

    /**
     * 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(1));
            } while (cursor.moveToNext());
        }

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

        // returning labels 
        return labels;}
    public  List<String> getAllquestions(){
        List<String> quiz = new ArrayList<String>();

        // Select All Query
        String selectQuery =  "SELECT * FROM TABLE_SPINNER WHERE category =" + KEY_QUIZES;

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

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

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

        // returning labels 
        return quiz;
    }
}

1 个答案:

答案 0 :(得分:0)

这是我看到的错误列表。

  • 每次删除并插入TABLE_SPINNER。从未在onCreate中创建。

  • 您每次拨打createnewtable时都会丢弃该平板电脑,但从未创建它。

  • 您在插入语句中使用TABLE_SPINNER作为正确的表名,但是它在DROP和SELECT语句中的字符串文字中,所以你要这样做很可能得到一个Table not found错误。您需要始终使用您的变量。

  • 解决上述问题后,必须合并插入测验和插入注释。您将这些列定义为not null,因此如果在内容值中插入一个键,则另一个值将为null,并抛出错误。

  • 小心 SQL注入 - "SELECT * FROM " + TABLE_LABELS;

可以由db.query(TABLE_LABELS, null, null,...

替换

Ovrerall,你不应该根据任意字符串值创建表。你以后如何查询?您必须知道要执行此操作的表的名称。

将同一模式的任何数据划分为单个表并没有什么好处。您应该在表格中添加String course列,而不是仅为String course创建表格,然后使用WHERE course = ?

进行过滤