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

时间:2016-08-24 19:26:30

标签: android android-studio android-sqlite

我正在制作一个“与Flash对话”应用程序,它允许您在EditText上插入一个问题并返回一个字符串作为答案。我创建了一个数据库,将问题和答案存储在同一个表中但位于不同的列上,其中每个问题及其相应的答案都在同一行。

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

我尝试寻找解决方案,但没有找到(有点做但却不明白它的意思)。

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

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;
}
}

1 个答案:

答案 0 :(得分:2)

你无限循环。你在c1上移动了ToFirst,但你永远不会移动到下一个。所以你永远不会追求最后。