【问题标题】:Android How To Get The Return Value String From SQLite Cursor Query And Display It In Edittext?Android 如何从 SQLite 游标查询中获取返回值字符串并在 Edittext 中显示?
【发布时间】:2013-04-22 20:15:16
【问题描述】:

当我运行 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();
}

【问题讨论】:

    标签: android sqlite cursor android-edittext


    【解决方案1】:

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

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

    【讨论】:

    • dymmeh,您的解决方案效果很好!感谢您提供答案。
    • dymmeh,您的解决方案效果很好!感谢您提供答案。
    • @user2308699 - 没问题。如果您认为这是正确的解决方案,请务必将其标记为答案。
    猜你喜欢
    • 1970-01-01
    • 2011-03-27
    • 1970-01-01
    • 1970-01-01
    • 2020-04-21
    • 2018-10-26
    • 1970-01-01
    • 2012-03-13
    • 1970-01-01
    相关资源
    最近更新 更多