2014-04-03 82 views
-2

我應該如何調用這個方法有字符串作爲參數或我應該如何執行這個查詢?如何在SQLite中創建where子句查詢?

代碼:

public class Samsung extends ListActivity { 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_samsung);   
     Intent intent = getIntent();  
     ArrayList<HashMap<String, String>> SamsungList = getSamsungInfo(null); 
     ListAdapter adapter = new SimpleAdapter(Samsung.this, SamsungList, R.layout.samsung_list, new String[] {Sqlite.COLUMN_MNAME, Sqlite.COLUMN_MMODEL, 
          Sqlite.COLUMN_MPRICE,Sqlite.COLUMN_MCAMERA} , new int[] {R.id.nameofsamsung, R.id.modelofsamsung, R.id.priceofsamsung, R.id.cameraofsamsung}); 
     setListAdapter(adapter); 
    } 

public ArrayList <HashMap<String, String>> getSamsungInfo(String samsung) { 
    ArrayList <HashMap<String, String>> wordList; 
    wordList= new ArrayList <HashMap<String, String>>(); 
    Sqlite sqlll = new Sqlite(this); 
    SQLiteDatabase database = sqlll.getReadableDatabase(); 
    String selectQuery = "SELECT * FROM mobile WHERE mname="+samsung+"'"; 
    Cursor cursor = database.rawQuery(selectQuery, null); 
    if (cursor.moveToFirst()) { 
     do { 
       HashMap<String, String> map = new HashMap<String, String>(); 
       map.put(Sqlite.COLUMN_MNAME, cursor.getString(0)); 
       map.put(Sqlite.COLUMN_MMODEL, cursor.getString(1)); 
       map.put(Sqlite.COLUMN_MPRICE, cursor.getString(2)); 
       map.put(Sqlite.COLUMN_MCAMERA, cursor.getString(3)); 
       wordList. add(map);         
     } while (cursor.moveToNext()); 
    }     
return wordList ; 
} 
} 

這是給我的錯誤,沒有名爲「空」一欄。那麼調用方法時我應該怎樣傳遞。它並不是將三星作爲手機的mname欄中的插入值。

回答

4

你需要引用您的文字在SQL:

String selectQuery = "SELECT * FROM mobile WHERE mname='"+samsung+"'"; 

雖然它是更好地使用綁定指定參數時,是這樣的:

String selectQuery = "SELECT * FROM mobile WHERE mname=?"; 
Cursor cursor = database.rawQuery(selectQuery, new String[] { samsung }); 

此外,通路在實際參數getSamsungInfo()而不是null

+0

這是不允許的。要求我創建語言環境變量「samsung」。如果我將創建,它將是空的ified。 – apurva

+0

這是一個方法參數,請參閱'getSamsungInfo(String samsung)' - 您需要更改調用該方法的部分,使用'getSamsungInfo(null)' – laalto

+0

調用方法:而不是getSamsungInfo(null),我做什麼sholud? ?它不採取任何其他... – apurva

1

這句法錯誤的是:

String selectQuery = "SELECT * FROM mobile WHERE mname="+samsung+"'"; 

它應該是(正確的撇號包圍的字符串值):

String selectQuery = "SELECT * FROM mobile WHERE mname = 'samsung'"; 

,或者更好的(這裏我用一個變量),

String selectQuery = "SELECT * FROM mobile WHERE mname = '" + mobileName + "'"; 

其中mobileName是一個傳遞的字符串,其中包含(例如)「samsung」

,或者甚至更好(綁定參數),

String selectQuery = "SELECT * FROM mobile WHERE mname = ?"; 

依次爲:

Cursor cursor = database.rawQuery(selectQuery, new String[] {mobileName}); 

其中mobileName是包含(例如) 「三星」 一個傳遞的字符串 - 和以前一樣
這裏null被替換字符串參數

+0

我已經嘗試過,但在調用getSamsungInfo時,我傳遞null,所以它再次顯示此錯誤。 – apurva