Android Studio SQLite不能在数据库表中添加多个字符串

时间:2018-11-29 23:36:41

标签: java sqlite android-studio android-toast

我正在创建一个应用,该应用可基于某些过滤器生成随机食谱,并具有添加和删除食谱的功能。现在,我正在添加一个配方(将作为URL输入),方法是将从两个EditText框收集的数据插入数据库中。填写文本字段并单击“提交”按钮时,我不断收到我设置的错误消息“错误。请输入一些数据”。关于db.insertData(String recipe, String category)的某些信息无法正常工作。当我将代码格式化为db.insertData(String recipe)时,效果很好,但是由于某种原因,它没有使用多个参数进行计算。

MainActivity.java

package com.example.randomrecipeapp;
import com.example.randomrecipeapp.helper.DatabaseHelper;
import com.example.randomrecipeapp.model.Category;
import com.example.randomrecipeapp.model.Recipe;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.List;


public class MainActivity extends AppCompatActivity {

//Fields
EditText add_link;
EditText add_category;
Button insert_recipe;

DatabaseHelper db;

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

    db = new DatabaseHelper(getApplicationContext());

    //Connect fields
    add_link = findViewById(R.id.add_link);
    add_category = findViewById(R.id.add_category);
    insert_recipe = findViewById(R.id.insert_recipe);

    insert_recipe.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String link = add_link.getText().toString();
            String category = add_category.getText().toString();

            if (!link.equals("") && !category.equals("") && db.insertData(link,category)) {
                Toast.makeText(MainActivity.this, "Link and category added to database", Toast.LENGTH_SHORT).show();
                add_link.setText("");
                add_category.setText("");
            } else {
                Toast.makeText(MainActivity.this, "Error. Please enter some data", Toast.LENGTH_SHORT).show();
            }


        }
    });
}
}

DatabaseHelper.java

package com.example.randomrecipeapp.helper;

import com.example.randomrecipeapp.model.Category;
import com.example.randomrecipeapp.model.Recipe;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

public class DatabaseHelper extends SQLiteOpenHelper {

// Logcat tag
private static final String LOG = "DatabaseHelper";

//database name
private static final String DATABASE_NAME = "recipes.db";

//table names
private static final String TABLE_RECIPES = "recipes";


//common column name
private static final String KEY_ID = "id";

//RECIPES table - column names
private static final String KEY_RECIPES = "recipes";
private static final String KEY_CATEGORIES = "categories";

//CREATE TABLE statements

//create RECIPES table
private static final String CREATE_TABLE_RECIPES =
        "CREATE TABLE " + TABLE_RECIPES + "(" + KEY_ID + " INTEGER     PRIMARY KEY," + KEY_RECIPES + " TEXT" + KEY_CATEGORIES + "TEXT" + ")";

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

}

@Override
public void onCreate(SQLiteDatabase db) {

    // creating required tables
    db.execSQL(CREATE_TABLE_RECIPES);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int  newVersion) {
    // on upgrade drop older tables
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_RECIPES);
    // create new tables
    onCreate(db);

}

//insert data

public boolean insertData(String link, String category) {

    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(KEY_RECIPES, link);
    contentValues.put(KEY_CATEGORIES, category);
    long result = db.insert(TABLE_RECIPES, null, contentValues);
    return result != -1;
}

}

ActivityMain.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    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=".MainActivity">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/add_link"
        android:layout_weight="1"
        android:hint="Recipe Link"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/add_category"
        android:layout_weight="1"
        android:hint="Recipe Category"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/insert_recipe"
        android:text="add"/>

</LinearLayout>

</android.support.constraint.ConstraintLayout>

1 个答案:

答案 0 :(得分:0)

您的问题是,由于创建表SQL中存在一些错误,因此不存在名为category的列,因此插入操作无法返回-1。

您有:-

private static final String CREATE_TABLE_RECIPES =
    "CREATE TABLE " + TABLE_RECIPES + "(" + KEY_ID + " INTEGER     PRIMARY KEY," + KEY_RECIPES + " TEXT" + KEY_CATEGORIES + "TEXT" + ")";

应该是:-

private static final String CREATE_TABLE_RECIPES =
        "CREATE TABLE " + TABLE_RECIPES + "(" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_RECIPES + " TEXT," + KEY_CATEGORIES + " TEXT" + ")";

  1. 应该将配方列和类别列分开的逗号已被省略。
  2. 类别和TEXT之间必须有一个空格

修改代码后,您需要执行以下操作之一:-

  • 删除应用程序的数据,或者
  • 卸载应用程序,或
  • 将数据库版本号从1增加,即将super(context, DATABASE_NAME, null, 1);更改为super(context, DATABASE_NAME, null, 2); // <<<<<<<<<<从1更改为2

完成上述操作之一后,应重新运行该应用程序。