java - 由于某种原因数据没有存储在 SQLite 数据库中?错误

标签 java android sqlite

我试图在新的 SQL 数据库中存储一些数据,但收到 logcat 错误,指出该表不存在,尽管我创建了一种方法来执行此操作。这是我的代码!

DataBaseHelper2.java -

package com.example.david.myview3;

/**
 * Created by David on 23/03/2017.
 */

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

public class DataBaseHelper2 extends SQLiteOpenHelper {
public DataBaseHelper2(Context context, String name, CursorFactory           factory, int version) {
    super(context, name, factory, version);
}

// Called when no database exists in disk and the helper class needs
// to create a new one.
@Override
public void onCreate(SQLiteDatabase _db) {
    _db.execSQL(LoginDataBaseAdapter.DATABASE_CREATE1);
    _db.execSQL(LoginDataBaseAdapter.DATABASE_CREATE2);
    _db.execSQL(LoginDataBaseAdapter.DATABASE_CREATE3);
    _db.execSQL(LoginDataBaseAdapter.DATABASE_CREATE4);
    _db.execSQL(LoginDataBaseAdapter.DATABASE_CREATE5);


}

// Called when there is a database version mismatch meaning that the version
// of the database on disk needs to be upgraded to the current version.
@Override
public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion) {
    // Log the version upgrade.
    Log.w("TaskDBAdapter", "Upgrading from version " + _oldVersion + " to " + _newVersion + ", which will destroy all old data");


    // Upgrade the existing database to conform to the new version. Multiple
    // previous versions can be handled by comparing _oldVersion and _newVersion
    // values.
    // The simplest case is to drop the old table and create a new one.
    _db.execSQL("DROP TABLE IF EXISTS " + "TEMPLATE");


    // Create a new one.
    onCreate(_db);
}
}

SurveyDataBaseAdapter -

package com.example.david.myview3;

/**
* Created by David on 23/03/2017.
 */

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class SurveyDataBaseAdapter {
static final String DATABASE_NAME = "survey.db";
static final int DATABASE_VERSION = 1;
public static final int NAME_COLUMN = 1;
// TODO: Create public field for each column in your table.
// SQL Statement to create a new database.
static final String DATABASE_CREATE1 = "create table " + "USER" +
        "( " + "ID" + " integer primary key autoincrement," + "ID  int,NAME text); ";
static final String DATABASE_CREATE2 = "create table " + "QUESTION" +
        "( " + "ID2" + " integer primary key autoincrement," + "QUESTION  text,ANSWER1 text, ANSWER2 text, ANSWER3 text);  ";
static final String DATABASE_CREATE3 = "create table " + "RESPONSE" +
        "( " + "ID3" + " integer primary key autoincrement," + "ID  int,QUESTION text, ANSWER int);  ";

// Variable to hold the database instance
public SQLiteDatabase db2;
// Context of the application using the database.
private final Context context;
// Database open/upgrade helper
private DataBaseHelper2 dbHelper2;

public SurveyDataBaseAdapter(Context _context) {
    context = _context;
    dbHelper2= new DataBaseHelper2(context, DATABASE_NAME, null, DATABASE_VERSION);
}

public SurveyDataBaseAdapter open() throws SQLException {
    db2 = dbHelper2.getWritableDatabase();
    return this;
}

public void close() {
    db2.close();
}

public SQLiteDatabase getDatabaseInstance() {
    return db2;
}

public void insertQuestion(String question, String answerOne, String answerTwo, String answerThree) {
    ContentValues newValues = new ContentValues();
    // Assign values for each row.
    newValues.put("QUESTION", question);
    newValues.put("ANSWER1", answerOne);
    newValues.put("ANSWER2", answerTwo);
    newValues.put("ANSWER3", answerThree);
    // Insert the row into your table
    db2.insert("QUESTION", null, newValues);
    ///Toast.makeText(context, "Reminder Is Successfully Saved", Toast.LENGTH_LONG).show();
}

//new try

public void insertEntry2(String question, String answer) {
    ContentValues newValues2 = new ContentValues();
    // Assign values for each row.
    newValues2.put("QUESTION", question);
    newValues2.put("ANSWER", answer);

    // Insert the row into your table
    db2.insert("SURVEY1", null, newValues2);
    ///Toast.makeText(context, "Reminder Is Successfully Saved", Toast.LENGTH_LONG).show();
}

public int deleteEntry(String UserName) {
    //String id=String.valueOf(ID);
    String where = "USERNAME=?";
    int numberOFEntriesDeleted = db2.delete("LOGIN", where, new String[]{UserName});
    // Toast.makeText(context, "Number fo Entry Deleted Successfully : "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show();
    return numberOFEntriesDeleted;
}


public String[] getQuestion() {

    final String TABLE_NAME = "QUESTION";

    String selectQuery = "SELECT  * FROM " + TABLE_NAME;
    SQLiteDatabase db = this.getDatabaseInstance();
    Cursor cursor = db2.rawQuery(selectQuery, null);
    String[] data = null;

    if(cursor.moveToFirst()) {
        do {
            // get the data into the array, or class variable
        }while (cursor.moveToNext());
    }

    cursor.close();
    return data;
}

public String getSingleEntry()
{
    Cursor cursor=db2.query("QUESTION", null, null, null, null, null, null);
    cursor.moveToFirst();
    String question= cursor.getString(cursor.getColumnIndex("QUESTION"));
    cursor.close();
    return question;
}

public void updateEntry(String userName, String password) {
    // Define the updated row content.
    ContentValues updatedValues = new ContentValues();
    // Assign values for each row.
    updatedValues.put("USERNAME", userName);
    updatedValues.put("PASSWORD", password);

    String where = "USERNAME = ?";
    db2.update("LOGIN", updatedValues, where, new String[]{userName});
}

}

CreateSurveyActivity.java

package com.example.david.myview3;

/**
  * Created by David on 23/03/2017.
 */

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.content.Context;
import android.view.inputmethod.InputMethodManager;


public class CreateSurveyActivity extends DashBoardAppActivity {

EditText editQuestion, editAnswer1, editAnswer2, editAnswer3;
Button btnNext, btnComplete;
SurveyDataBaseAdapter SurveyDataBaseAdapter;





@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.photoalbum);

    // get Instance  of Database Adapter
    SurveyDataBaseAdapter = new SurveyDataBaseAdapter(this);
    SurveyDataBaseAdapter = SurveyDataBaseAdapter.open();

    // Get References of Views
    editQuestion = (EditText) findViewById(R.id.editTextQuestion);
    editAnswer1 = (EditText) findViewById(R.id.editTextAnswer1);
    editAnswer2 = (EditText) findViewById(R.id.editTextAnswer2);
    editAnswer3 = (EditText) findViewById(R.id.editTextAnswer3);

    // Get Refs of buttons


    btnComplete = (Button) findViewById(R.id.buttonSignUP);
}


 public void createSurvey(View V){

    final Dialog dialog = new Dialog(CreateSurveyActivity.this);
    dialog.setContentView(R.layout.photoalbum);
    dialog.setTitle("Create");

    // get the Refferences of views
    final  EditText editQuestion=(EditText)dialog.findViewById(R.id.editTextQuestion);
     editQuestion.setOnFocusChangeListener(new View.OnFocusChangeListener() {
         @Override
         public void onFocusChange(View v, boolean hasFocus) {
             if (!hasFocus) {
                 hideKeyboard(v);
             }
         }
     });
    final  EditText editAnswer1=(EditText)dialog.findViewById(R.id.editTextAnswer1);
     editAnswer1.setOnFocusChangeListener(new View.OnFocusChangeListener() {
         @Override
         public void onFocusChange(View v, boolean hasFocus) {
             if (!hasFocus) {
                 hideKeyboard(v);
             }
         }
     });
    final  EditText editAnswer2=(EditText)dialog.findViewById(R.id.editTextAnswer2);
     editAnswer2.setOnFocusChangeListener(new View.OnFocusChangeListener() {
         @Override
         public void onFocusChange(View v, boolean hasFocus) {
             if (!hasFocus) {
                 hideKeyboard(v);
             }
         }
     });
    final  EditText editAnswer3=(EditText)dialog.findViewById(R.id.editTextAnswer3);
     editAnswer3.setOnFocusChangeListener(new View.OnFocusChangeListener() {
         @Override
         public void onFocusChange(View v, boolean hasFocus) {
             if (!hasFocus) {
                 hideKeyboard(v);
             }
         }
     });


     // Set On ClickListener
     Button btnNext = (Button) dialog.findViewById(R.id.buttonNext);
     btnNext.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub

            String question = editQuestion.getText().toString();
            String answer1 = editAnswer1.getText().toString();
            String answer2 = editAnswer2.getText().toString();
            String answer3 = editAnswer3.getText().toString();

            // check if any of the fields are vaccant
            if (question.equals("") || answer1.equals("") || answer2.equals("") || answer3.equals("")) {
                Toast.makeText(getApplicationContext(), "Field Vaccant", Toast.LENGTH_LONG).show();
                return;
            }

            {
                // Save the Data in Database
                SurveyDataBaseAdapter.insertQuestion(question, answer1, answer2, answer3);
                Toast.makeText(getApplicationContext(), "Question Successfully Created ", Toast.LENGTH_LONG).show();
            }
        }
    });
     dialog.show();

    // try to send home on complete button press
    //*
    //btnNext = (Button) findViewById(R.id.buttonNext);
   // btnNext.setOnClickListener(new View.OnClickListener() {

      //  final Intent intent = new Intent(context, DashHomeActivity.class);
        //
   // });
}

public void hideKeyboard(View view){
    InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE);
    inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}


@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();

    SurveyDataBaseAdapter.close();
}
}

logcat-

04-17 20:26:41.408 14322-14322/com.example.david.myview3 E/SQLiteLog: (1)       no such table: QUESTION

   04-17 20:26:41.408 14322-14322/com.example.david.myview3 E/SQLiteDatabase:    Error inserting ...
                                                                          android.database.sqlite.SQLiteException: no such table: QUESTION (code 1): ,    while compiling: INSERT INTO QUESTION(QUESTION,ANSWER3,ANSWER2,ANSWER1)    VALUES (?,?,?,?)
                                                                              at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                                              at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:919)
                                                                                 at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:530)
                                                                              at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                                           at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
                                                                           at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
                                                                             at    android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1547)
                                                                             at    android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1404)
                                                                              at    com.example.david.myview3.SurveyDataBaseAdapter.insertQuestion(SurveyDataBase   Adapter.java:59)
                                                                              at    com.example.david.myview3.CreateSurveyActivity$5.onClick(CreateSurveyActivity   .java:117)
                                                                              at android.view.View.performClick(View.java:4785)
                                                                              at android.view.View$PerformClick.run(View.java:19869)
                                                                              at android.os.Handler.handleCallback(Handler.java:739)
                                                                              at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                              at android.os.Looper.loop(Looper.java:155)
                                                                              at android.app.ActivityThread.main(ActivityThread.java:5696)
                                                                              at java.lang.reflect.Method.invoke(Native Method)
                                                                              at java.lang.reflect.Method.invoke(Method.java:372)
                                                                              at    com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:10   28)
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)

最佳答案

使用SurveyDataBaseAdapter.DATABASE_CREATE1而不是LoginDataBaseAdapter.DATABASE_CREATE1

DataBaseHelper2.java 中,更新 onCreate() 方法,如下所示:

@Override
public void onCreate(SQLiteDatabase _db) {
    _db.execSQL(SurveyDataBaseAdapter.DATABASE_CREATE1);
    _db.execSQL(SurveyDataBaseAdapter.DATABASE_CREATE2);
    _db.execSQL(SurveyDataBaseAdapter.DATABASE_CREATE3);
}

在您的 SurveyDataBaseAdapter 中,更新 SQL 表创建语句,如下所示:

static final String DATABASE_CREATE1 = "CREATE TABLE " + "USER" + "( " +
        "ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
        "ID1 INTEGER, " + "NAME TEXT " + ")";
static final String DATABASE_CREATE2 = "CREATE TABLE " + "QUESTION" + "( " +
        "ID2 INTEGER PRIMARY KEY AUTOINCREMENT, " +
        "QUESTION  TEXT, " + "ANSWER1 TEXT, " + "ANSWER2 TEXT, " + "ANSWER3 TEXT " + ")";
static final String DATABASE_CREATE3 = "CREATE TABLE " + "RESPONSE" + "( " +
        "ID3 INTEGER PRIMARY KEY AUTOINCREMENT, " +
        "ID  INTEGER, " + "QUESTION TEXT, " + "ANSWER INTEGER " + ")";

关于java - 由于某种原因数据没有存储在 SQLite 数据库中?错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43457183/

相关文章:

java - 向元素添加 MouseOverHandler?

android - Android onPreviewFrame()回调中的图片方向不正确?

android - 这指向什么错误 - "new_window_surface returns 0x3000"

java - Realm Android - 多个库的多 Realm 模块

android - SQLite是否可以支持按笔画或发音排序?

java - 错误: not found: java Usage: selenium-standalone action [options]

java - POI - 在 Excel 中打开时无法写入文件?

sqlite - SQL 查询中本地时间的 18 位时间戳

java - 无法理解为什么要使用参数化日志记录

node.js - 某些软件包(sqlite3、socket.io)的 npm install 在 Windows 7 上失败并出现错误 MSB8020