gpt4 book ai didi

Android 如何从SQLite 游标查询中获取返回值字符串并显示在Edittext 中?

转载 作者:行者123 更新时间:2023-11-29 21:44:47 25 4
gpt4 key购买 nike

当我运行 SQLite 游标查询时,它无法在编辑文本中显示结果字符串。

失败并显示 Logcat 消息:

java.lang.RuntimeException: Unable to start activity
android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1

如何从游标中获取查询结果值字符串并显示在edittext中?

public class Books extends Activity implements OnClickListener {

private BooksData books;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.books);

books = new BooksData(this);

}

SQLiteDatabase db1 = books.getReadableDatabase();

SEARCH_TERM = "math";

EditText edittext = (EditText) findViewById(R.id.edittext1);

// Get the value from TITLE when the TOPIC value is specified, ie such as "math".

Cursor cursor_2 = db1.query(TABLE_NAME, new String[] {"_id", "TOPIC", "TITLE"}, "TOPIC = ?", new String[]{ ""+SEARCH_TERM+"" }, null, null, null, null);

String TEMP_DATA = cursor_2.getString(2);

edittext.setText(TEMP_DATA);

books.close();
cursor_2.close();
}

最佳答案

您需要移动到游标中的第一条记录,然后才能从中提取数据。

Cursor cursor_2 = db1.query(TABLE_NAME, new String[] {"_id", "TOPIC", "TITLE"}, "TOPIC = ?", new String[]{ ""+SEARCH_TERM+"" }, null, null, null, null);

if (cursor_2 == null)
return;

try{
if (cursor_2.moveToFirst()) // Here we try to move to the first record
edittext.setText(cursor_2.getString(2)); // Only assign string value if we moved to first record
}finally {
cursor_2.close();
}

关于Android 如何从SQLite 游标查询中获取返回值字符串并显示在Edittext 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16155914/

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