Вставить список, разделенный запятыми, в EditText и сохранить в таблице SQLite в нескольких строках

#java #android #sqlite #android-sqlite

#java #Android #sqlite #android-sqlite

Вопрос:

Мне интересно, как вставить список, разделенный запятыми (test1, test2, test3, test4), в поле EditText и при нажатии кнопки сохранить его в моей таблице базы данных SQLite, каждый в отдельной строке. Это было бы идеально, чтобы пользователи с большим списком (50-100) могли массово вставлять данные. Прямо сейчас у меня есть это, если бы оно вставляло одно имя в мою таблицу.

DatabaseHelper.java

 public class DatabaseHelper extends SQLiteOpenHelper {
    private static final String TAG = "DatabaseHelper";

    private static final String TABLE_NAME = "hashtag_table";
    private static final String COL1 = "ID";
    private static final String COL2 = "name";

    @Override
    public void onCreate(SQLiteDatabase db) {
        String createTable = "CREATE TABLE "   TABLE_NAME   " (ID INTEGER PRIMARY KEY AUTOINCREMENT, "   COL2  " TEXT)";
        db.execSQL(createTable);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP IF TABLE EXISTS "   TABLE_NAME);
        onCreate(db);
    }


    public DatabaseHelper(Context context) {
        super(context, TABLE_NAME, null, 1);
    }

    /**
     * Add data to the table
     * @param item
     * @return
     */
    public boolean addData(String item) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL2, item);

        Log.d(TAG, "addData: Adding "   item   " to "   TABLE_NAME);

        long result = db.insert(TABLE_NAME, null, contentValues);

        if (result == -1) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * Gets the data from the table
     * @return
     */
    public Cursor getData() {
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "SELECT * FROM "   TABLE_NAME;
        Cursor data = db.rawQuery(query, null);
        return data;
    }

    /**
     * Gets the ID from the table
     * @param name
     * @return
     */
    public Cursor getItemID(String name) {
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "SELECT "   COL1   " FROM "   TABLE_NAME   " WHERE "   COL2   " = '"   name   "'";
        Cursor data = db.rawQuery(query,null);
        return data;
    }

    /**
     * Updates the name from the table
     * @param newName
     * @param id
     * @param oldName
     */
    public void updateName(String newName, int id, String oldName) {
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "UPDATE "   TABLE_NAME   " SET "   COL2   " = '"   newName   "' WHERE "   COL1   " = '"   id   "'"   " AND "   COL2   " = '"   oldName   "'";
        Log.d(TAG, "updateName: query: "   query);
        Log.d(TAG, "updateName: setting name to "   newName);
        db.execSQL(query);
    }

    /**
     * Deletes the name from the table
     * @param id
     * @param name
     */
    public void deleteName(int id, String name) {
        SQLiteDatabase db = this.getWritableDatabase();
        String query = "DELETE FROM "   TABLE_NAME   " WHERE "   COL1   " = '"   id   "'"   " AND "   COL2   " = '"   name   "'";
        Log.d(TAG, "deleteName: query: "   query);
        Log.d(TAG, "deleteName: Deleting "   name   " from database.");
        db.execSQL(query);
        db.execSQL("UPDATE SQLITE_SEQUENCE SET seq = 0 WHERE NAME = '" TABLE_NAME "'");
    }
}
  

ListView.java (где EditText и кнопка находятся прямо сейчас)

 //Adds new hashtag to list and prompts if nothing is entered
    btnAdd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String newEntry = editText.getText().toString();

            if (editText.length() != 0) {
                addData(newEntry);
                editText.setText("");
            } else {
                toastMessage("you must put something in the text field");
            }
        }
    });

    populateListView();
}

/**
 * Adds new data into the Database
 * @param newEntry
 */
public void addData(String newEntry) {
    boolean insertData = mDatabaseHelper.addData(newEntry);

    if (insertData) {
        toastMessage("Successfully inserted");
        recreate();
    } else {
        toastMessage("Whoops, something went wrong");
    }
}
  

Комментарии:

1. Кстати, ваш код небезопасен от SQL-инъекции.

2. @Zoe на самом деле он защищен от внедрения SQL (экранирован) как часть построения метода insert convenience для базового SQL.

Ответ №1:

Ниже приведена довольно простая замена для addData, которая использует метод split строки, чтобы разбить строку на значения, разделенные запятыми, и вставить их :-

 /**
 * Add data to the table
 *
 * @param item
 * @return
 */
public boolean addData(String item) {

    String[] splitdata = item.split(","); //<<<<<<<<<< split the input string
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();

    boolean result = true;
    db.beginTransaction(); //<<<<<<<<<< prepare to do in a single transaction
    // Loop through each string inserting an entry into the database
    for (String s : splitdata) {
        contentValues.clear(); //<<<<<<<<<< clear any existing values to be safe
        contentValues.put(COL2, s);
        if (db.insert(TABLE_NAME, null, contentValues) < 1) {
            result = false;
        }
    }
    if (result) {
        db.setTransactionSuccessful(); //<<<<<<<<<< only set the transaction successful if all inserts worked
    }
    db.endTransaction();
    return resu<
}
  

Обратите внимание, что это приведет к откату всех вставок, если есть какие-либо неудачные вставки, и дополнительно вернет значение false.

  • Приведенный выше код в принципе является кодом, он не был протестирован или запущен и поэтому может содержать некоторые ошибки.

Комментарии:

1. ты такой потрясающий! Это сработало отлично. Большое вам спасибо!

2. @Noblefins И это хорошо, пожалуйста, отметьте ответ, если вы считаете, что ответ помог вам решить проблему.

3. Вы получили это! Еще раз спасибо!