2012-02-19 113 views
1

我想寫一個查詢從SQLite數據庫中檢索數據。我想在文本框中打印查詢結果。所以我對光標使用了一個getint()方法。以下是我的代碼。它不會在我的Android模擬器中啓動。這是編寫查詢的正確方法嗎?它沒有顯示任何錯誤。Sqlite數據庫查詢寫作

import android.app.Activity; 
import android.os.Bundle; 
import android.app.Activity; 
import android.database.Cursor; 
import android.database.sqlite.*; 
import android.os.Bundle; 
import android.widget.TextView; 
import android.widget.Toast; 

public class SQLDemo1Activity extends Activity { 
    private SQLiteDatabase db; 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    try{ 
     db= SQLiteDatabase.openDatabase(
     "/data/data/cis493.sqldatabases/databases/multilinguialdatabase.sqlite", 
     null, 
     SQLiteDatabase.CREATE_IF_NECESSARY); 
     db.beginTransaction(); 
     Cursor cursor = db.query(
     "colors" /* table */, 
     new String[] { "ID" } /* columns */, 
     "English = ?" /* where or selection */, 
     new String[] { "green" } /* selectionArgs i.e. value to replace ? */, 
     null /* groupBy */, 
     null /* having */, 
     null /* orderBy */ 
    ); 
     int id = cursor.getInt(0); 
     TextView met = (TextView) findViewById(R.id.t1); 
     met.setText(id); 
     db.endTransaction(); 
     db.close(); 
    } 
    catch(SQLiteException e) { 
     Toast.makeText(this, e.getMessage(), 1).show(); 
    } 
    } 
} 
+0

你會得到什麼錯誤? – Snicolas 2012-02-19 09:32:28

+1

哦,順便說一下,你的ide不需要你縮進你的代碼。你的編譯器也不需要它。但是程序員,可能是你或我們,需要它。 – Snicolas 2012-02-19 09:33:30

回答

1

在嘗試使用getInt()獲取int之前,需要先放置cursor.moveToNext()或cursor.moveToFirst()。將它放在if語句中,因爲在遊標中可能沒有結果。

2

要寫入Android中Sqllite查詢需要特定的參數,如:

//查詢用戶字典並返回結果 mCursor = getContentResolver()的查詢(

URI         // The content URI of the words table 
mProjection,      // The columns to return for each row 
mSelectionClause     // Selection criteria 
mSelectionArgs,      // Selection criteria 
mSortOrder);      // The sort order for the returned rows 

詳情讀機器人。開發人員的網站: http://developer.android.com/guide/topics/providers/content-provider-basics.html