Android Sqlite"没有这样的表"错误

时间:2017-08-20 20:54:44

标签: android sqlite android-sqlite

我试图在android中学习Sqlite数据库,但我无法处理简单的工作。当我使用" insertWord"在数据库中插入记录时我收到了这个错误。这似乎很有趣,因为类型表是由程序创建和插入的值。我做错了什么?。

这是我的代码(Database.Java)。

package com.pekgenc.mehmet.spinnerexample;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.annotation.NonNull;
import android.util.Log;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

/**
 * Created by Mehmet on 18.08.2017.
 */

public class Database extends SQLiteOpenHelper {

    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "mywordbank";

    // Labels table name
    private static final String TABLE_TYPES = "types";

    // Labels table column names
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";

    // Words table name
    private static final String TABLE_WORDS = "words";

    // Words table column names
    private static final String WKEY_ID = "id";
    private static final String WKEY_TUR_NAME = "tur_id";
    private static final String WKEY_ENGLISH = "english";
    private static final String WKEY_TURKISH = "turkish";
    private static final String WKEY_EXAMPLE = "example";

    public Database(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + TABLE_TYPES + "("
                + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME + " TEXT)";

        String CREATE_WORDS_TABLE = "CREATE TABLE " + TABLE_WORDS + "("
                + WKEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + WKEY_TUR_NAME + " INTEGER,"
                + WKEY_ENGLISH + " TEXT," + WKEY_TURKISH + " TEXT," + WKEY_EXAMPLE + " TEXT)";

        db.execSQL(CREATE_CATEGORIES_TABLE);
        try {
            db.execSQL(CREATE_WORDS_TABLE);
        }
        catch (SQLiteException es)
        {
            Log.e("ERR: ", es.getMessage());
        }


        // Inserting label values
        db.execSQL("INSERT INTO " + TABLE_TYPES + "(" + KEY_NAME + ")" + " VALUES ('Adjective')");
        db.execSQL("INSERT INTO " + TABLE_TYPES + "(" + KEY_NAME + ")" + " VALUES ('Adverb')");
        db.execSQL("INSERT INTO " + TABLE_TYPES + "(" + KEY_NAME + ")" + " VALUES ('Conjunction')");
        db.execSQL("INSERT INTO " + TABLE_TYPES + "(" + KEY_NAME + ")" + " VALUES ('Determiner')");
        db.execSQL("INSERT INTO " + TABLE_TYPES + "(" + KEY_NAME + ")" + " VALUES ('Idiom')");
        db.execSQL("INSERT INTO " + TABLE_TYPES + "(" + KEY_NAME + ")" + " VALUES ('Interjection')");
        db.execSQL("INSERT INTO " + TABLE_TYPES + "(" + KEY_NAME + ")" + " VALUES ('Noun')");
        db.execSQL("INSERT INTO " + TABLE_TYPES + "(" + KEY_NAME + ")" + " VALUES ('Phrasal Verb')");
        db.execSQL("INSERT INTO " + TABLE_TYPES + "(" + KEY_NAME + ")" + " VALUES ('Phrase')");
        db.execSQL("INSERT INTO " + TABLE_TYPES + "(" + KEY_NAME + ")" + " VALUES ('Preposition')");
        db.execSQL("INSERT INTO " + TABLE_TYPES + "(" + KEY_NAME + ")" + " VALUES ('Pronoun')");
        db.execSQL("INSERT INTO " + TABLE_TYPES + "(" + KEY_NAME + ")" + " VALUES ('Verb')");
        db.execSQL("INSERT INTO " + TABLE_TYPES + "(" + KEY_NAME + ")" + " VALUES ('Other')");
    }

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

    // Get all types
    public List<String> getAllLabels() {
        List<String> labels = new ArrayList<String>();

        String selectQuery = "SELECT * FROM " + TABLE_TYPES;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        if (cursor.moveToFirst()) {
            do {
                labels.add(cursor.getString(1));
            } while(cursor.moveToNext());
        }

        cursor.close();
        db.close();

        return labels;
    }

    // inserting a word in database
    public void insertWord(int tur_id, String english, String turkish, String example) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(WKEY_TUR_NAME, tur_id);
        values.put(WKEY_ENGLISH, english);
        values.put(WKEY_TURKISH, turkish);
        values.put(WKEY_EXAMPLE, example);

        try {
            db.insertOrThrow(TABLE_WORDS, null, values);
        }
        catch (SQLiteException e) {
            Log.e("ERR: ", e.getMessage());
        }
        db.close();
    }

    public List<String> fetchAllWords() {
        List<String> words = new ArrayList<String>();
        String selectQuery = "SELECT english, turkish FROM " + TABLE_WORDS;

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

        if (cursor.moveToFirst()) {
            do {
                words.add(cursor.getString(1));
            } while(cursor.moveToNext());
        }

        cursor.close();
        db.close();

        return words;
    }
}

(AddActivity.Java)

package com.pekgenc.mehmet.spinnerexample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import java.util.List;

public class AddActivity extends AppCompatActivity {

    EditText textEng, textTur, textExp;
    Button btnAdd, btnBack;
    Spinner sp;
    ArrayAdapter<String> adaptor;
    int selectedIndex;

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

        textEng = (EditText) findViewById(R.id.editTextEnglish);
        textTur = (EditText) findViewById(R.id.editTextTurkish);
        textExp = (EditText) findViewById(R.id.editTextExample);
        btnAdd  = (Button) findViewById(R.id.buttonAdd);
        btnBack = (Button) findViewById(R.id.buttonBack);
        sp      = (Spinner)findViewById(R.id.spinnerType);

        loadSpinnerData();

        sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectedIndex = parent.getSelectedItemPosition() + 1;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Database db = new Database(getApplicationContext());
                db.insertWord(selectedIndex, textEng.getText().toString(), textTur.getText().toString(), textExp.getText().toString());
                db.close();
            }
        });
    }

    private void loadSpinnerData() {

        Database db = new Database(getApplicationContext());
        List<String> labels = db.getAllLabels();

        adaptor = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, labels);
        adaptor.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sp.setAdapter(adaptor);
    }
}

(logcat的)

08-20 20:29:42.621 16118-16118/com.pekgenc.mehmet.spinnerexample E/SQLiteLog: (1) no such table: words
08-20 20:29:42.622 16118-16118/com.pekgenc.mehmet.spinnerexample E/ERR:: no such table: words (code 1): , while compiling: INSERT INTO words(example,english,turkish,tur_id) VALUES (?,?,?,?)

谢谢。

2 个答案:

答案 0 :(得分:0)

您的代码似乎没问题,是否在您添加单词表时已经拥有了数据库?尝试删除应用程序并再次启动,这应该安全地重新创建所有表。如果这是问题,请在将来正确使用数据库版本字段

我建议将GreenDAO用于Android的sqlite,它会让事情变得更容易

答案 1 :(得分:0)

可能是因为您的设备/模拟器中的数据库版本不包含表格&#34;单词&#34;。您更改数据库的架构并且不会增加版本。因此,onCreate()方法没有被调用,而表格#34;单词&#34;不存在。 要修复它,只需更改private static final int DATABASE_VERSION = 1; private static final int DATABASE_VERSION = 2;