gpt4 book ai didi

java - 无法从 sqlite 表获取值

转载 作者:行者123 更新时间:2023-12-01 12:03:54 25 4
gpt4 key购买 nike

在我的应用程序中,我想将数据保存在数据库中。

这是我的 SQLiteHelper 代码

public class UserSqliteHelper extends SQLiteOpenHelper {
private final String LOGCAT = "JBF/SQLite";
private static final int DATABASE_VERSION = 1;

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

private static final String TABLE_NAME = "jbfjsonEntity";

private static final String KEY_JSON = "json";
private static final String KEY_URL_PATH = "url_path";
private static final String KEY_TIME = "added_on";

public UserSqliteHelper(Context context) {
super(context, "dictionarysqlitehelper.db", null, 1);
Log.d(LOGCAT, "Created");
}

@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_NAME + "("
+ KEY_JSON + " TEXT, "
+ KEY_TIME + " TIMESTAMP NOT NULL DEFAULT current_timestamp, "
+ KEY_URL_PATH + " TEXT )";
db.execSQL(CREATE_CONTACTS_TABLE);
}

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

public void addJsonEntity(JsonEntity jsonEntity) {
SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();
values.put(KEY_JSON, jsonEntity.getJson());
values.put(KEY_URL_PATH, jsonEntity.getUrl_path());

// Inserting Row
db.insert(TABLE_NAME, null, values);
db.close();
}

public JSONObject getJsonByUrl(String url) {
String json = "";
SQLiteDatabase db = this.getReadableDatabase();

try {
// Cursor c = db.query(TABLE_NAME, null, KEY_URL_PATH + "=?", new String[]{url}, null, null, null);
String selectQuery = "SELECT * FROM " + TABLE_NAME + " where " + KEY_URL_PATH + "='"+url+"'";
Cursor c = db.rawQuery(selectQuery, null);

if (c == null) {
return null;
} else {
c.moveToFirst();
json =c.getString(c.getColumnIndex(KEY_JSON));
if (json != null) {
return new JSONObject(json);
} else {
return null;
}
}
} catch (Exception e) {
e.printStackTrace();
}

return null;
}
}

当我从我的 Activity 中调用时

UserSqliteHelper sqliteHelper = new UserSqliteHelper(SplashActivity.this);
sqliteHelper.getWritableDatabase();
sqliteHelper.addJsonEntity(new JsonEntity(STRING_CONFIGS_URL,response.toString()));
System.out.println("json ==== "+sqliteHelper.getJsonByUrl(GET_USER_INFO_URL));

我总是遇到这个错误

android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0

谁能告诉我我在这里做错了什么。为什么我无法获取数据库值?

最佳答案

查询与任何数据都不匹配。 moveToFirst() 失败,光标未指向有效行。您应该检查 moveToFirst() 是否成功 - 它返回一个 boolean 值。

它与任何数据都不匹配的原因是您通过不同的键存储和检索数据:STRING_CONFIGS_URLGET_USER_INFO_URL

关于java - 无法从 sqlite 表获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27803036/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com