Android 应用程序在尝试使用 SQLite 数据库时冻结

Android app freezes when trying to use an SQLite database

我正在制作一个 'Talk to the Flash' 应用程序,让您在 EditText 上插入一个问题并 returns 一个字符串作为答案。我创建了一个数据库,将问题和答案存储在相同的 table 但不同的列中,其中每个问题及其对应的答案都在同一行中。

我的问题是,当我尝试 运行 该应用程序时,当我按下开始为输入的问题寻找答案的按钮时,它会冻结。(通过使用 answerToQuestion 方法,传递问题作为参数)

我尝试搜索解决方案但没有找到(有点搜索但不明白它的意思)。

这是我的数据库处理程序class(复制了其中的所有内容):

package com.beacon.talktotheflash;

import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.Cursor;
oimport android.content.Context;

public class MyDBHandler extends SQLiteOpenHelper{

private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "flash.db";
private static final String TABLE_QANDA = "questions_and_answers";
private static final String COLUMN_ID = "id";
private static final String COLUMN_QUESTIONS = "questions";
private static final String COLUMN_ANSWERS = "answers";

public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}

// Initializes the database
@Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_QANDA + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_QUESTIONS + " TEXT, " +
COLUMN_ANSWERS + " TEXT);";
db.execSQL(query);
listOfQandA(db);
}

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

// List of the questions and answers
public void listOfQandA(SQLiteDatabase db){
String query = "INSERT INTO " + TABLE_QANDA + " (" + COLUMN_QUESTIONS + ", " + COLUMN_ANSWERS + ") "
+ " VALUES(\"hello\", \"Hi says the Flash!\")";

db.execSQL(query);
}

// Get the answer for the provided question
public String answerToQuestion(String question){
// Check if the question and the answer are in the same row
// by using a cursor
SQLiteDatabase db = getWritableDatabase();
String final_answer = "";
String query1 = "SELECT " + COLUMN_QUESTIONS + " FROM " + TABLE_QANDA + " WHERE 1";
String query2 = "SELECT " + COLUMN_ANSWERS + " FROM " + TABLE_QANDA + " WHERE 1";

// Cursor point to a location in a column
Cursor c1 = db.rawQuery(query1, null);
Cursor c2 = db.rawQuery(query2, null);

// Move to the first row in column_questions
c1.moveToFirst();

while(!c1.isAfterLast()){
if (c1.getString(c1.getColumnIndex("questions")).equals(question)){
int c1_position = c1.getPosition();
c2.moveToPosition(c1_position);
final_answer = c2.getString(c2.getColumnIndex("answers"));
}
}

c1.close();
c2.close();

return final_answer;
}
}

你在无限循环。您在 c1 上 moveToFirst,但您从不 moveToNext。所以你永远不会在最后一个之后。