2013-04-22 29 views
1

當我運行SQLite遊標查詢時,它無法在edittext中顯示結果字符串。Android如何從SQLite光標查詢獲取返回值字符串並在Edittext中顯示它?

它無法與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(); 
} 

回答

2

您需要先移動光標中的第一條記錄,然後才能從數據中提取數據。

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

dymmeh,您的解決方案效果很好!感謝您提供答案。 – user2308699 2013-04-22 22:05:03

+0

dophie,你的解決方案效果很好!感謝您提供答案。 – user2308699 2013-04-22 22:07:05

+0

@ user2308699 - 沒問題。如果您覺得這是正確的解決方案,請務必將其標記爲答案。 – dymmeh 2013-04-23 00:33:05

相關問題