我正在對'Flash Talk'應用程序進行討論,讓您在EditText上插入問題並返回String作爲答案。我已經創建了一個數據庫,將問題和答案存儲在同一個表上,但在不同的列上,其中每個問題及其相應答案位於同一行。嘗試使用SQLite數據庫時,Android應用程序會凍結
我的問題是,當我嘗試運行應用程序時,它凍結,當我按下按鈕,開始尋找輸入問題的答案(通過使用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;
}
}
長時間運行的操作應該在單獨的線程上執行。 –
我知道這個問題沒有什麼,但是你已經聽說過[Realm.io](https://realm.io/docs/java/latest/)?這是一個很棒的SQLlite框架。 –